({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; YnKCsrMUFyExNDdzdHWSlNIVFhgjMzU2QVFVYWVxk6LiJCc4Q1NWlcImRlRXY2SBhJHD0yUoREeDoaPRRbG0weHw/8QAGwEBAQADAQEBAAAAAAAAAAAAAAIDBAYFAQf/xAAyEQEAAgECBAMHAwUAAwAAAAAAAgMEARIFERMzITEyBhQVIkFSYRYjUTRCU4GRJGJx/9oADAMBAAIRAxEAPwCriKQ7MREgUiJAIiQCIkbQREgERIBESAREtogREgEQ2pAiJIvu1ICW192qREkTakNqQ+qR2gbQcOQAAAEgERIQI7XG1MBHaJbUdqwEhAiJbUdqxwOQHG0cgOHIAAACQCIkPm1KIkJUiJCtoiJIvm0AHwBIWI7TakIERJEASH3aIiQ+CIkPu0R2m1IfBHabUgETakjtWDhyIHA5NqxwbU9qKAEh92iG1yG1QAA4c7QQBtSAR2iSL7tSAPu1QA+gJIgBtSBEBO0AHwHDkWOBybQNrja5AcOQAAQAJAAitKQAAAAAAAAAAAACgASAAAAAAAAAAAAAACKQAAKAFJAEgAAAAAAAAAAAKRSAAAAASAAAAAAAAikAAAoAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAClACQAEgAACgAFACUgAAAAAoAQAIrSkAoAEgAAAAAAAAAAAAAoAAABQAJAEgAAAAAABtAAAAAAAAUACQAUAIikhESJAjuBIBQA'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; AAAAAAAKAAUAAA'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; AAAAAAAAAAAKAAAAUAACKSUgAAAAAAAAAAAAIgkApQAJAEgAAAoAAABQCO5KUhHckKAAAEAAtIAoAEgAAAoAEgAAAAAoAEgAAAoAEgAAAAAAAAAoAEgAAAoABQAAG5ESkAKRSAAAABKQAAAAAAAAAAAABQAJABQAAAJANwAApQAAAAAJAAR2pAAAkAAAAAFAAkAAAFAAAAAAAAkAAAAAAEUgAAUAAikikgABIAygAkAAAFAAAAKAAAAABIAAAAAKAAABIAAAAAkAFAAAAKAAAARS2gAAAAAAJAEgAAAAAAAAAoAEgAAAAAoAAABQAAAAAAAJAAAAAAABQAJAAAAAAAEgAoAAAAABQAJAAAAAAABQCKRKIAIpIpIAASALAAAAABQACgABEBIkikAAKAAAAAAAAAAABIAKAEpAFAAAAKAAAAAAAAAAAAABIAAAkAFAAKABIAAAAAAAKAAAAAAABIAKAAAAAAAAAAAAAAAAAAAAAAAAABIAKAAAAAAAAAAAEgACKSKSEgSBQAtIAAAAAoAAAAEUgEUgAAFAAAAAAAAAAAAAAAAkAAAAAFAAAAAAkAFAAAAAAAAkAAAFAAkAAAFAAkAAAFAAAAAAAAAAAAAAAAkAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQABFIEBIASALAAABQACgBKQBQACgAAAAAAAAAAAAAAAAASAJABQAAACgAAAAAAASAAiJIgJIgJAAACgAAASAJAAABSgASAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASAAACgAAAAASAAAJUAACKSAAEopIpMoACgAAAAASACgAAAAAAAAAAAAAAAAASAAAAACgAAAAASAAAAACgAAAEdqQAAAAAAAAAAAACQAUAAAAACQAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAUAAAAACQBIAAAAikikKAEJAFgAoABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAEgApQAAAAAACIJAAACQAUACQAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACQAAAAAAAAAUAAAAAJABSUdwCQAiKTcAhIAsAAAFKAABy4EgAAAoAAAAAAAEgAoAAAAAAAAAAAEgCQAUAAAAAAoAAAAAAAEgCQAAAUAAAAAAoAAAAAAAAAEgAoAAAAAAAAAAAAAAAAAAAAAAAAAEgAACQAAAUAAoAAAAAAASAAlFJFIUAISALAAABQAAAAACgAAAAAAAAAAAAAAAAAAAAAAAAASAAACgAAAAAAAAAAAAAAAAAAASACgAAAAASACgASAJABSgAAAAAAAAAAASACgAAAAAAAAAAAAAABKQAABQAAACgASAAACgBIAIS5cAKAFpAAAFKABIAKAAAAAAAAAAAAAAAAAAAAAAABIAAAKAAAAAAAAAAAAAAAAAAAAABIAKAAAAAAAAAAAAABIAKAAAAAAAAAAAAAAAAAAAAABIAKAAAAAAABIAAAKAAABIAkABQAAAgABIAsBFIABQAJABSgAAAAAAASAAAAAAACgAAAAAAASAJABSgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASACgAAAAAAAAAAACQAAAAAAAAAAAAI7gSEdxuBIAAAAASACgAAASAJAAUAAAIAABEGVIkAACQAUAAoAAAAAAAEgCQAAAUAAAAAAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEEgBIAKAAAAAAAAAAAAAAABIAKAAAAAAAAAAAAAADaAIpbQEgAoAADcAAAAAAAA'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; AKUikIpSkAmQAEVADIkAAASACgAFAAAAAAAAAAAAkASAAACgAAAFAACKSKRKIikAAoAAAAAAAAAAAAAEpAFAAAAAAAAKABIAAAAIpAAAAAACgAAAAAAAAAAAAAAAAAAASAJABQACgAAAAADaAJAAABQAAAlIAoAEgAgAAAFgAAAAAoAAAAAkiCQikAAKAAABIAkAFAAAAAAKAEgbQAAUkNzKOF8dE1dWW9tr+F7hk1fmTuLOtsnb4/enL1JbofhXBseSxwhvLWndWlfO69vWhhOnVhmGGMZ4Y+tKOOEWjfmwoltlEUU3C+f1J3Cn8OffL/wB1H6lDhR+fv7Q/da/xatShyS9/1KHCr8/f2h+6fUo8KPz98v8A3X34tWKIC9/1KPCj8/fL/wB0+pR4Ufn75f8AuvnxWoUQF7/qUeFPc598v/dPqUeFPc598v8A3T4pUKIC9+HJT4Uffhnny/8AdaT5WPCPR/DXI8hvNM08wjVv7qrSrSubrsvNjT3eoyU8Rqsns0FfAfrawjUvKMJdGdWMZfGekmXyx3PyG2fpD09u29ju/wBefSDp7uLv9ey9CTyPjGO1MNt/SBp7+ju/16Xpe6c7i7/Xp6Mj43jtRDb3pe6c/o735Qel5pzuL39erpST8cx/y1CNwx4daa/o735Sl6XOmu4vflP7qejJPx7H/LTg3H6XGmO4vflKXpc6b/o7z5SdGR8exfy00N00eGenKvRpXvyl9lPhRpfb9clff7Ln906cmOXtLiR8+bRQ33HhTpLtqd/L/ef3X6elVo//ACe++VSOnJi/VWF+WgNwsB6VGkP6C8+VYnpU6O/ye++VSTskn9VYX5V/G/anCTSWPR+iFP8ARcfuvjr8G8hl9gzHMaUu+2T/AP6NklR9qMCX8tHDbF9wXusIylYZ5Qn+StQlD9qO5jOacMtXWG6UcujeQj9+2nGf7PSTtk36ONYVvpmw0fteWd3ZVexXltWtqvcVYShL9p+L69KM4z8YgAsAFAAAAAAkAFAAkAAAFAAAAkAAASAAAAAClAAAAIpIpCQAAAAAUAAAAAJABCQAUAMqQBIAAAKAAAAUAAAAA'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; AAAAAAAKAAUAAAAAAAAA'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; 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'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; 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'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; 3P1fBwasKrp1xAHxugCgbm4D0NmnL25/pbrbHxYx+c0ysDwvs/QGiMvpyw2zqxlWl40t3k7V0epzntLZtxNv86ssji53PyfpubMn53KKZuR3OEMe11+qK3YNNZnX7izqy/ZkrFHo4LDcT7r0NoPNZbtsp0sKUf9soxV5Y7Xfeyde3HnL8gDA6sRSRUCQAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEUgRBAkAJAGVQAAAAAAAAAJAAABQAAAAAJABQAAAAAAAJAEgApQAAAAikJBFJEFsOp4+yda+52f/NW6VF6nl7K1p4Fn5VVbhy+d3pJAGoOJKsdUG+0mj/fV15EFqJKr9UG+0mj/AH1debg2cHvxFQn15D9vcv8AfVLy4vkfXkP29y/31S8uLqtGPJ7Ulp93Pl4SccX47ufLwn6xxb30fjVkfn1fobkNyW5LBKLDONfte3Xu9Hy1elg+NfteXfu1Dy1fGC71P0n2T/ov9gDE6cAUACQAAl0Vo9Kz/wAGcslLmx9B0t3xIquM51Tr+vfaXsdPZZGdtRhawp3lXoyq4xj0MO98plhLa53j3DLOIdOEP58Xa8VuIcsxwq5DkVeUbLo3NzDH2R3se88rwWr4m0Y5Sevg4NWHVpXWkA+N0AAAB9eT2NTMs2tcvpdO4qxgstbwp29CFCEdsIRjCPgxaj4J5NjWzG4zyrH63b4diobvvzl0vix8ptyLZqjti4T2kyerdpVH6P3ji5ji/OOKe5mcvJPcjucbkdyE7WAcdb3sOmrSxjLnXFx18fBhH50otLM/445h6J1RQscMevG0oc7Dv587ydrAGtP1P0zgdHRwofkSRSfHrgAoAEgCQAUAAoAAAAAAAAAEgAoAAAAAAAAAAAAABESRSkAQpIB9iADIkAFAAAAAAAAAAAAAAAAAAAAkAFAAAAACUopIgJAKUAAAAAAAJFrup4+ytZeBZ/8A7qrcKj9Tz9maz8Cz8qqtw5jO70kyAGmElWOqDfaPSPvy68iC06rXVBMP8HtIy/1648iLawe/EU/fZkP29y/35S8uL432ZF9vcv8AfVLy4uq082PI7clod3Pl4ScX5y+yS/S5i3dPJ+PTj8799zl+UcUtyWKUWH8ava8u/d6Hlq+LBcZ/a+u/daPlxV9YLvU/RPZX+i/2AIdMAAAJAABFKSICSICQAoAEj6ctsbnML+jY2tPslavPZHB80fVk3Lwv0p9BrT6J5hDbmFxT5sMf5mHc+FJ9jDfJocSzo4dXP6sr07llDJsot8st+hSjzpd1LtpOxQilubr82slKyUpyT3Jbn57h9Ydr9Nz861SnRpTq1ZbYQjKUpdzFLcwvi/nX0N0zKxpT23F/LsUe9h28v7vjIlLa2MPGlkXxr0+rTuoMxnm2d3mYz6VxVlOOHc4drH4r4Aar9Urr0rjGOgkAoAFAAkAAAFAAAAAAAAAAkASAClAAAAAAAAAAAAAIgkikJEQkAkAmKQRSZAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAkAAAAAFAAACUgApa7qefszWfgWflVVuFR+p5+zdZ+5WflVVunMZ/eklEBpgq31Qb7mdJe/rjzUVpFXeqDfctpL3/AFvNRbOD34inj7Ml+3WX++qXlxfG+vJft3Ye+6XnIuq0Yr+3JZ/dz5eEnF+O7ny8JOOLe08n5FZHxfrucoG59YZRYjxl9r6991peXFX9v/jHL/AC991peXFoBq3ep+heyv8AR6//AEAYnTAAAClAACKSIAJAiJCU8xzGMpyjGMZSlLmxww7Z2+n9M5xnc4+g7WUaPbVqvNhHxu28VtXSGjsuyHCNxL+FX39NOPNh4Ee18Jca5SeXncVoxo8vOTqeHeh/QM6ebZ1Sj6K9ejb4/wA130u+71sKKCbbjGMY8tHEZeXbkz3zfpuc7kEo4vrST3G5Hc43CXO7bFoPiJnuGfakrV6M91pQ+s2/gx7bxpNh8WNSfQrKfoZa1Nt7eRlGW3pQpdtLxuj8Zphr2y+jsfZzh/Tj15/6AGJ1KUQBQAAAlIAoABQAAAAAJAAAAAAABQAAAAAABIBEBJuSRIpEgBQACIJIAASAMoAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAASACgAABKQAUtZ1PP2frP3Kz8qqt4qH1PP2frP3Kz8qqt45jP70kogNMFX+qCfctpL3/X81FaBV3qgkv8FdJYf6/X81FsYffiKePsyX7c2Hvql5yL432ZL9ubD31S85F1ejFf25LMylz5eEnHF+cpc+XhOY4t7V+TWeb9dxuR3ONyWDaxLjD9wV37rS8uLQjfPGD1dA3vh0vLi0MxW+b9C9l/6T/YAwOlb55K3B7S/FLLs+r6huczoY5dXoQpeg60Ybo1IylLdujLuW6/qR+Gn4z1H8rpf9NjPU88f+yNYx/1q1l+xNahzeXkWxvlHSSVe/qReGv411L8qpf9M+pF4a/jXUvyql/0lhHDB71f9wr79SRwzj/+S1LL/fKX/SaS5VXCTSvC600/U07VzSrPMateNeV3XjPbGnGG3btjHul71UOqD+xNG+63nk0mzhZFs746ayFX9L5PTzq4rUp15UOxQjPdhDdu5zv/AKR6X4yq/qo/OfLwz+2N77hHymdO3oohZDnLR4WZl2128o6sP+kal+Mqn6qPzk46Gtu2zKr+qiy5KnCU6mEYx3Sky+61fw05cQu/litvoWxlKMZXd3UlLtYxjFl2Q6LyLLdtWVnGvW7q4lv2/wB13GX2kbeG6XOnLpSfZFinGr6aPJyuJX2/LuTjHbHbGPNj0Un5pIeWmlFCLncCccUkNxuShN12os2tMkyqtmF5LmQ6MO2nLtYxfRmF7bWNlVvLyrGlRpR6854tF641Nc6kzLsst1K0pbo21Hue+l30mOctr1OF8NlmWc5enR1mdZldZvmdfMLyW6tXl15dbo4dzGPeviSRar9AjGNcdsRIBQAAAAAAAAAKAAAAAAAAABIAKAAAAAAAAAAR2iQAAAABuASIpIpIBy4cvsUuAFAAAAAApQAAAJABQAJAAAAABQAAAAAAAAAAAAAJABQAAAlIAKWu6nn7N1n7lZ+VVW6VF6nn7M1n4Fn5VVbpzGd3pJRAaYKu9UEl/gzpLDtvR9bzUVolXOqC/c1pL3/ceai2MHvxFPX2ZL9ubD31S85F8r6sl+3Nh76peci6vRiv7cllJfZJfpS3ISlz5eEbm9p5PymcfF+u43Pz3MC4na2+hUJ5PlVX/tCUdtWph/4ePc+H5KZS2suJhTy7enB1fGHVtCtSnpux2VcMJ4Suqv4MY87ZH+81edIa0pbn6Xg4cMOmNcABDdW76np9r9Z+72nkzWrVT6nn7A1n7rZ+TVWsctnd+SZDhyNUcKodUJ9iaN91vPJpLXqodUIw/gmjfdbzyaTcwP6iIrpwz9n3vuEfKZ0wXhr6mY3vuEfKZ1H1X6FjdvRzfEO9qnTjKcoxjHdKTucvtI28N0udOXSk/PLbTsMd9Tpy/ZfdEts/tc/ffu+XROKW5Dc5azU2pm5DcluBOOKW5+W43CU9z580zCzyyyneX1eNKjDpYy8mPdSdTqjVGWZBQ/hFTstzKPMt4dKXhdzFp/U2oMyz+87PfVNsI/YqMPscP3u+Y7LNr1uH8Inky3S8Ivu1tqy61Hd7edQsaUvrVHd6/fS75jiI05S3O1oohRDZDyS3IglmSAUAAACQAUAAoAAAAAAAABESkIgJAAAAAAACgAAAAAAAAAABIikiAk5cCYpAGQAAAAAAAAABQAAAJAAABQAAAAAAAAAAAAAAAAAAAAACKQJFrOp4+ztZ+5WflVVvFROp5+zdZ+5WflVVu3MZ/eklEBpgq71Qb7mtI+/7jzWC0SrnVBvub0l7+uPIi2MHvxFPX2ZP9ubH3zS8uL432ZL9ubH3xS8uLq4sd3bksdKXPl4SW5+Upc+TEeIWsaeQ2/oGxlGpmdWPN7aNHDupd93ODfl8vm/NKMSeVdsgjxH1rHJKUsuy6cZZlOPOn0o2+HdeE0vKcpzlUqSljOUt0sZS52Mkq1WpWqzq1akp1Zy685ylulKT82nZPc7/AIfw+vDhy09SQikh6AAKW56np7E1n7rZ+TVWtVS6nn7D1n7rZ+TVWtctnd+SQBqjhVLqhHsPRvut55NJa2SqXVCJfwLR3ut55NJuYP8AURFb+HP2yu/cI+U2dlNt1ttepHndpFrrhTTjWzu6jLoxoRl+02pH1HeVWftaOS4zZtt5RfpEcCXgbU9xuQ3I1Jxp0+yVJxpw7qctsXx92Sk/fcbmO5lrHT1hHGM8wp154dpb8+X7PNYfnHEi8rRlDKrOnbx/pa3Pn8Xo+UxysjFvUcLyL/LRsrML+zy+1lcX1zTtqWHbzlt+K13qjiLVrRnbZDTlSh0fRNWPOl4Me1YNmF7eZhcSub66q3NXupy3PnYZW/w6DC4LVT81njq5rVKlarOrVqVKk5y3SnOW6UnCIwbnuaacgB8fRJGKQAAAAACgAFAAAAAAACUgAAChESAABQAAAAAAAAAAAAAAAAAkRABIBMUgDIAAAAoAEgAoAAAAAAAAAEgAoAAAAAAAAAAAAAAAAAAASAALW9Tz9m6z9ys/Kqrcqj9Tz9maz8Cz8qqtw5jP70kgDTBVzqg2P+DekY9t6OuPIitFJVvqg33PaR9/XHkRbGF34in76sn9TN7D3zS8qL5X6W9SVvXpV4bd1KcZx3d7Lc6yKLI7oyi3VxC1bS05byoUNtXMav2KGPRhHu5fNaSuLirc3M7m5qyq1qst054y50pJ5hdXN/e1ry8qyq1q85TnOXbPwZLLNzSwOHww4ctPMAYnoCSMUhQAC3PU8/Yes/dbPyaq1qqXU8/Yes/dbPyaq1rls7vySANUJKn9UI9j6Mj3955NJbCXRVN6oR9i0X7peeTSbeD34ir2n87vcjuqtezjSlOrDZLssd3Nd36Yef8Aa07L9VL5zEZDq42Si1rMSmzXdOLLZcQtRy7ayj/6H7z8KmvNTz6N3Qp+DbxYyHUkmODj/Zo7m41bqW4jtqZvcxj3m2HkuruLm5uZbrm5q18fw1Zyl5T8kdr5ukyxx64eUUgBm8gAERLaJERJEEgFAAAAkAFAAKABIAKAAAAABIAAAKAAABIAKAAAAAAAAAABESJIgJABSQCEgDKAAAAAAAAoAAAAAAAAAAAAAAAAAAAEgAAAoAAAAAAASkAFLYdTz9laz8C0/wCatsqP1PP2VrPwLPyqq3DmM/vSSANMJKudUG+5vSMv9duPNRWjVd6oNh/gvpL3/X81FsYffiKeScEh1YiJApESREpACgAFuep5+w9Z+62fk1VrVUep4+wtZ+62nk1VrnLZ3fkkAaoKn9UI+waN90u/JpLYKn9UI+waM90vPJpNvB70RUqThyOqU4AHwAH0AEgAACQAUAAoAEgAAAoAAAEgCQAUoAAAAAEgAoAAAEgAoAAAAAAAAABGQkCRFISpECIJAIABlAAAAAAAAAAAAAAAAAAAAAAAAAASAJABQACgAAASACgBIAAtd1PP2ZrPwLPyqq3SonU8/Zus/crPyqq3bls/vySiA1QVf6oN9y2kvf8AW81FaBV7qg33L6T9/wBfzUWxh9+Ip3JwSHVgACIkKABKgAFuOp4+w9Z+62fk1VrlUOp4+xNa+62fk1Vr3LZ3fkkAaoKn9UI9j6M8O78mktfJVDqhHsXRfut55NJt4PeiKlOHLh1SgAAAAAABKQBQACgAAAAAAAAAAAAASAAACgASAAAAACgASACgAAAAAAAAAAEQSRBKQAUkAgAFpAFAAkAAAFAAKAAAAAAAAAAAAAAABIAAAAAKAAAEpAFCIltRSJAClrOp5+z9Z+5WflVVvFQup5/bPWXuFn5VVb1zGf3pJRAaY4Vc6oR9zWkff9x5qK0irXVCPuc0f7+uPIi2MHvxFPgHVgAoABQAAAkW46nj7C1n7raeTVWuVQ6nj7E1r7rZ+TVWvctnd+SQHDVBVPqhGH8C0bL/AEt55NJaHN8wscoy24zTM7qla2drCVWvXqy2whHDtpKA8pji76aGpbell1vjRyHK5VMLHsmG2rWxlt69WXc7tvNi3uH1ylfHXT6DUYIunUkIpCQAUAAACQAAAUAAAAAAASAAAABFIREpACgASAJABQAAAChEkCUgRBIAUAAAAAAAAIpAIiQlKISIoUkAAAypAAAEgAAAoAEgAAAoAAABQAAAAAAAJABQAAAJABQAlIAAAAACyPId1VpzTGZaplqDPMvymFxQt+xSu7mNLfKMqm7rbvCWl9NThp/X3TP9o0vnPMnrddHrR7l5t/Do2z37h6bS4q8MsP8AH/TP9o0vnEeKvDLH/H/TP9o0vnPMvrR7k60e5YfhOn3D04jxQ4cT6OvdM/2nS+crdy59VaZ1HkelqWQZ/leazoXlfGrGzuoVdkZQjt3bZc1VjrR7kZaOG6VTjPcoR3A9NIkiKEgBQAlIAKW36nj7E1r7rZ+TVWvVR6nn7C1r7raeTVWuctnd+SR8uaX1plmX17+/uKVtaW8MatatVlthCMelKWKeY3tpl1jWvr25pW9rQhjVq1qktsIRj68pSUP5TXHK74iX9TT2nqlW20pbz8GV/OPbz7zuY+NLvZxseV8tsR8/KW42XnEfNJZLktStbaUtqnXpQx9SV7PD+dnHue5j43rtLA6ammNMdsVADKJAKSACgASAAAAAJAAABQAjIEhFIAAUAAAAAAACQAAAUAAAAAACKQkAFAAAAAAAAAAACQkAAOXCEgCwAAAAAAAAAAAAAAAAAUoAAAAASkAAAAAUAAAAoAEgCQAARSARikAACgAARSEiIJAACgAAAFuOp54fwLWsv9LZ+TVWmv7u2y+zrXl5XpW9tRhjUq1aktsYRj0pYyVY5Ad1a5fpjW2YX1xSt6FKvbzq1KktsYRjCfOlJr3lPcc7niBeVdN6brVaGlqNTnz6Mr+eH38e87mPjSc/bjyvypRiIcp3jpc8Qr6rpvTtarbaWt586XRlfzw7eXedzHxpd7osHt00xpjtilJEGdQAlKQikoAEgAAAAAoAAAAAEgAoAAAAREtqIJbhFIAAUACQAAAAAAABFIFAAAAAAAAAAAAAAACQEUkAOXAkAWAAACgASACgAAAAASAAACgAFAAkASAAAAAClAAAAkAAAFAAACUgClAIiUgBQAAAAAAAkARB2drn+cWunb3T9tf1aWV39eFa6oQ5sa2MPW3d7Hr9F1gk+RjEREh9AAERIUlEBIkAoAEgAAAAAoARBIAUAAAJAASAKUAAACQBIAAAKAAUAAAAAAAAAAAAAAAAAAA'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; ikikhTlw5cPsUgCgAARSFAAKAAABIAkAAAAAFAAKAAABIAAAlQAoAAEUgSAAACgAABKQBQAChFIAAAAAAAASEkUpIiRLciAkAKNyKW4UlESR2gBtASAAAAASAAACgRSRAABJFIAAFACQAUAIgkIpAAABJESkIpCgAAAAAAAAAAAAAAAAAAAABKUUgQoAEgDKAAAAAAoAAAEgCQAAAAAUoAAAAAAAAAAAAAAAEgCQAUoAAASkBFQkAKAAAEgCIJAKSAJAERSSJuSUIpIgAAJBuREgAJAChFIEgikkABSICkiSJuAASJCKQoAUAIpEkQEiSIoBIABEEkdqQCISAEkUkqAFAAAAAAAAAAAAAAAAAAkAEyAAikAZAAAAFAAAAAAkASAAAClAAAAAAAAAAAAACUg+nK8vv8ANb+jl+WWde8va8utSt7eEp1J49zGMekyWPCviZLo6B1N/Z1X5qJWRj6pKYiMozDhvxCy+yrX2YaI1BbW1CEp1a1WynGnCMelKUtvNixcjZGXpAGX2vC7iReWtO6tdC6gr0asMJ0pwspyjOOPRlgSsjX6hiAzGXCjidDpcPtTfIJ/NY5n2SZxkF/9D88yq8yu72Rn2G7oSpT2y7bbLtUxurl6ZD4QGUAAEX15Tl2YZtmNHLsss695e3E9lC3ow3znLuYxZXLhHxSw/wDL/UXyGTFK6uPqkM'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; 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'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; 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'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; 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'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; n1ZeT6+RfDkNy/iPh8KXH91Q/117uQ3zeB8PhO4/ut3ivZfG+WpuMnA3T/ABRz6yzjOs3zWzq2lr6GhC0xhtxjulLdjujj6vObX3G54EJyhruiK3/Uf6E+/qbUnxqHzEvqP9Af1j1N+sof9JY7cMvvl/3Cuf1H+gP6w6m/W0P+k5+pB4f/ANYdTfraH/SWKcvvvl/3Dzo5S/DvJuGWvbTIMjur65t6uXQuZTu6kZVOyY1Kke1jHm82LVywfL29uWxw7nJKPnaqvzosSUpURl'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; IDYSkAoNoAoAAASkAUAAoAAAAAEgAACQAUoASAAIpIpIAASALAAAAAAAAAAAAABSgAAAAAAAAAAAAAABI7nRGorzSerMs1JYUaVa5y+vhWpQrbtkpYd1tb2hyv8AXeHr6a07L9f89XnKcvvs2zK3yzLLSd3e3U40qFGlHnTnLoxizb0kuLfW3fSFnPxI/OamRXjyl+6Ngaq5U+sdQ6azPIrnTmR0KOYWtS2nVpSq7oYVI7ZSw3S75oFl+c8LeJOUW07rMdD59Qt4R3Tq+hZTjGPfbeuw/cyY8aY9ocyb50zyqNeZDkNhk9DJNP16Nhbwt4Tqwq7pYQjtj19s+9aKtaFe7uqVpbUqlW4rzwpUqUI7pTlKW2MYsh1Pw/1vpbK4ZnqLS+Y5VZzqxpYVrml1o4zl0Y/+0i6umzXbYN1fVga87bTOnf8A5/ntG8RNVXmttZ5jqjMLahbXOYTjOdKju7HHbGMebu53asfZjkvC3iFneno6gyrS19d5XUp1KsbuGzZKMd26XOl+TFEaaKJbtPAYckR53W29syvOOG2vsoyWedZppHN7TLqcMJ1LmdHmRwl20u9bMrYx9T6xQHdaS0nqXVt3Vs9MZJeZrWow31YUIdfZh3UiUox+aQ6anOUJxlHpRluWAo8rXiPSpRhHKtN7Yx63q29X57S+rdK6k0le0rLUuT3WVXNeHZadOvhHCUo9Hc6u1oV7u4pW1pQq17irLZClShKUpy7mMY9JilVVdHdLxfG/vqt+JH4q038nq/PaEzK7q3+ZXV9X2xq3VedaeGHR3TlKUvKbGy/gBxfvbTC6paLuoQxw6+GFavSpVPiynuYVq7SmptI38bHU2SX2VVpdDC4pbYz8GXRl4rFTpjxl+0Om3N18N+UhrLQ2kMv0xluUZFc2dhGUaU7iFXfLdKUudtn3zSTJNKaE1lqu0rXmm9N5jmtvRn2KrVtqXXjCW3r7f+DNdXVZH93yG748sHXXbaZ07/8AN89qDjDxDzPiZqmGoc2sbSyuIWsLXZbbtm3CUpbudLpc5ieZWd5luY3GX5hbVba7t5ypV6NWO2pCcelGT59zHXjVVy3Q0Ehk2hOH+stc15w0rp68zGMJbZ1o4RhShLvpy2xZnmnJw4w2FnK4lpenc4Rj15Qtr6lOp8XdzmSWRTGW2UhqZy/fMrK+yy/q2GZ2dzZXdCW2rb3FKUKkJd9GT52TcCL7siyjNM9zOllmS5dc5hfVuhQoUpTnJsmXJz4x4WXor6UcdvW6/Yo31Df8Xex2XV1+qQ1QOw1BkmcaezKeWZ7lV5ld7DpUbmlKEvC53Sj30XX7WSMtJ+kbB4bcZOIGgYwoZHnlSrl8f/AXmHZqHixlzoeLKLeGn+WLVjSjDUGh4yn21WxvNscfEnH+8qck1rMKizzilcityxNMRjj2LRuczl3MrilHBherOV5qq9pTpaa03luVbujXuqsripHxebHylayOEpSjGMd0pdGODHHh1EfHkO81lrDU2s8y+iGp86vc0rR6HZp/W4eBDox8V0bJNScP9baayilm+odL5pltjVnGEK1xS2xlKUd0Y970e2Y226unt/bU5cOXDINh8I+L+quGFpmFvpyhltSF/VhVq+i6Ep87CMo4bdso/hZ5hyteJuHSsNNy/wB1n89rvTfBvihqG0heZZovNJW847oVa0Y0Izj3u+UXVa04f630ZHCeptM5lltHGW3CtVhupYy8OO6P7TSlDGsl48uY27HlbcSfxZpuX+71fnufquOJH4p018nq/PV7F+5UfaLCfVc8SPxPpr5PV+efVdcSPxPpv9RV+er5RpVK1WFKlTlUqzlGMIYR3SlKXRjFkeo9Aa301l+GY6h0pm+WWeMow7PcW8ow3S6MdzHLGxoy2yiNx4crriJj0sj03+oq/PaEzy/qZrnN7mdaFOjVvLmdxOEOjGVSUpSjH4z5HDYqorp8YRB+tjd3VjeUryxua9tdUJbqVajOUKkJd1GUeiyHS3D7W+q7DG/03pbM8ztITlSxrUKXXhhOPSju8Z2dbg3xXow3z0Bn3W72hu8mRK6v0ykM90HypeIeQUIWudU7PUtvDm4SucOx19vhx6XjRbMseWLk0oYejtDZhTn23YbyE4/tRiqTnWT5vkd36DzrKr7Lbr+iu6EqUviyi+Nrywsaz5tNBbzNOWPl2FLH6GaGu51e1xub6MY/sxk1ZrzlN8TNSU6trYXNpp20nzetYQl2Xb7rLnfF2tOWNnd5he0bGxtqtzd3E8KVCjSjuqTlLoxjFlEuFHE7+oGpPkE/mmmJjVeoYncXFW5rzr3NWpVrVZbp1Zy3SlLupSR3Mslwp4nYevw+1N8gm6vUGktVado0q+f6azbKqVWeyE721nSjOXcxlKLbjZX6YyHTttcJ+PWreHOmPpeyfLcoubTs86265hUlPdLpdGUWq8vs7u/vaNjY21S5uricaVCjSjulOcujGMe6d3qPRGstMWkLzUOmM1yq2nPZhWubeUISn3O78L5dGuz5bBur6rzX/wCINO/Eq/PQlyu+IXa5Dp2P/pVfnq8JWtCvd3VK1tqVSrcV6kYUqUI7pTlLmxjFg9yo+1KwMuV1xG/Eum/1FX57j6rriR+KNN/J6vz2ptR8MuIGmsnq5zn+k8xy2wpSwjUr1oRjGMpS60e27p02ldO55qrN8Mp0/l1XMcwnCU8KFOUd0ox6W3dJEcfElHdyU3l9V7xHw/8Aw+mZf+hV+e/aPK/4gYR52ntNy8Sr89o/V+jdW6RqUY6n0/mGUeiOv2HG5pdaM9vS60nQ7VRxMacd0dBmvF3iLmvE3VMNR5xZ2VncwtYWsYWm7se2MpS3c6Uudz2Hst0zws4h6kyaGcZLpPMbzL59fZXhhGMJ4Yev1t0sNzEJRxjLbLpNinWvSO2H0EkUu1RZUpAAACgASAJABSgAAAAASAAACgASAAACgBIikCAAEgCwAAAAAAAAAAAAAUoAAAAAAAAAAAAAAASM34Bx3catHfDFHyl4eUFxRnwp0xl+cQyWOayvLz0L2LG57Ft5kpbt22XcqO8BpbeNWjvhi38pbflj6L1VrfROT2Olsonmla1zHGvXpQqQjKMOxSju50o7udi8bP0jrfDd5Jk6Th1yr8i1DqC1yfP9O18i9F1Y0aV1C67NSwnLm4b+bGUcOv2zH+W5w0ySzyWhxAyezpWV76LjbZjCjT2wr7922e3ut0du7ttzX3DHk28Q801RY1dR5V9Acpo14VbitcVqcqs8Iy3bYQjKXOl3zcnLs1FY2fDey03KrH0dmV/CtGju50aVLdKU/jYxwYY6QhkR6IqPw5jGXEPTUfzta+diuDy88f4oLCPdZ3S81VU+4e47df6cl+dbXzsXoPxv4a2vFHS9HILzNbnLaVC9jdYVaNKM5SlGMo7ed4TazrNK74S1HmztegHAGOzkrZXHusnu5ftVWBfUd5Bu3S1xm/W/JZ0m68p01a6M4RVNLWNxVuLfLcprUoVa23fPmTlult8JgzcqF2kdIDzQp/Yo+CvTyR9d22veGVfR+e7Lq/yqh6Fr06vO9EWeMdsZY91zeZL/AGKLU/sUfBZhwj1tmHD3XmX6my/dONCWy6o7vs9GX2SHze+jF6OXR1af/ZWr7+OPD+54c8Q8wyKpGpjYyl6Iy6tL+dt8fW/2x6MvBW15PGmbDg7wRu9Uam/g13c0PojmOOPShDCP1ql+nrY+t3U2d55pTRXFLL9N6hvaFO/t7apDMLCtHtoy52yX4Yy9TdHvVe+XTxH7NeW/DfKq/wBao7bnNsYdtPpUqXi9OX6YvN688vbT/wBFeeJur8x13rjMtT5lhtqXlXmUt26NGlh6kIR8HD+8tbyIdC5LYaFlxAvKNKtmt9WqwpVp4bvQ1CnLbLDDuZSxjLGUvBUuWy5EvFLJrDJbnh/qC/t7Gca8rjLqtxOMIVcJ9Olulzd27nYd1uk3+IVyhj7YD5dRcsTM4ahrQyDSVjVyiFSWFKd3XnGtVj3XN5sev+DnMx15xK4Z8TuT7mN5nN5YWF7O1qyt7C5rxldW93DDHseEMMOdLry63O2+rGXqu51pyXuGupp1b7KcLzILitz91jVwnQ3eBLdH4vWV04v8nXWWgbKtnVpWpagyajzqte2pyjVox7qdLufyxlJoVaY09Y8vl1PBphdHqfeHW4f6jl3Wb4eYiph1+uuf1P3ncO9R/DGHmKbf4n2DVWDjhh/HHrH4auvOyZDybOFuPE3W0qF7jOGR5dHCtmM4c2U93RpYS7qW2Xixkx/jhzeMmsfhm68uS1fINy+hS4SZhfU4x7Nd5xVwqy72EIRjH/3l8ZjvtlVjc4jJ+LfFjRnBDIrHIsvyqlVvZUt1nlVntpRpU+7nj2sf/eTUuQ8si7xzOGGe6KoRsJY+rOzvMZVaeHgyj1pfstDceM6u9Q8YtVZndylKX0Rq0IRl2kKUtlOPxYsKTj8PqlXzn56pX2482nCfiNwjjq/M85y+yjK3lPK839TssZ/0W3pT53NlTUOQ3SlGMd0pRj0Y7uim28bF93jt3cxe/kf6VynS/Bm11RhQhLMM2pTu7q527p9iwlLbTw72MY+t3WLWV5yxc3lnkpWejbHHKcJ+pGpcT7PKHhR5sZeK73kbcWMnx0rDh/qHMLaxu7KcvodVr1MKcK9KUt2zdLto44y5v34yZnrPkx8M9TXFbMMtjfZFcV5b+vl1XDGjux7bscuvH4u148tIQul19FMb5TWtuGGqeDFteXV1bX2ZX9vhVyinbzpzurSrKO7n87mw7WfXUxbZ438B9TcMoSzaNSGcZDKfW9G0aWyVDHteyw7X9PRamerhQrjD5NeYAN4Gz+S9o+WseMeU21Wl2Sxy6X0QvO52Q6MfGntwaxjgu9yLdHU9L8M7nWGZ4QpXOdfXsZTw63YrWl19v/HnS+K0s67p1a6DanGnSkNccM8903thK4r2+ONtjj2txDn0/wBqMf8Ai8z6kKkJypzpypzhLbKMulGXcrj8nXjTPVnGrVOUX1TGFlndeV3lGEu0xpQjDZ41KEZeFGTTfK90J9J/Fi5zC1pdjyzPt17Q60ebGr/Ow+NzvHaWBrKizpTGmlxOSRway6xyO04gaqsYXGY3cez5ZQuI7oWtLtauMZdvLpYdzFUvTdhTzXUeVZZU6F5eULeXg1Jxj/eX35U2aXOmOAeefQjHG2lUp0cvhKHN7HSnOMJdbxN2HjM3EbJc41R+owTibysMkyTOKmV6Syb6P40JbKt5Vr9ioYy7zbGUpYfl5ruuFvKJ0RxCo1si1bZ22QXNWEoyo31aM7O6j20d8utHr97JRXrdZzzcebI+G17eX9yWz+UXkegMm1vKfD3PbK+y64wljVtLecpxtKv34xn0ZQl97nS285rJFJv119OMYqba5Jujpas4y5bVq0eyWOTf9oXXXjzd0PsWHjT2/FkvDxJ0/Y630Pnuk6lSlOdzQxpdLr40a+2M6Usf9uyTVnJE0rb6F4N19VZxttq2awlmFzUn/NWtOMux7vF3T8Zg3Jb4t3epeOGqbPNZyhS1NOV3YwlL7FOlHbGEf/Q8h4eTrO+yU4f2CrF9aV7K9uLO7pSpXFvVlSqwx6UakZbZR+M+dvflp6J+l3idhn9pQ2WOfw9ES60ebG4jzasfG5svGk0Q9rHs6tcZi73IJ9qHMPhur5qkxvPOVnXybVmaZPc6GpVqFhfVbWVWnmOMZ4xpzlHdtlDvWTcgv2ocw+HKvmqSn/E6PW4k6oj+eLzz83l1UQuyJ6TF69Oan4Z8e9I3OXVbWF5GEP4RY3cNl1Zyl28cf78ZKZcdOG19wx1rPJ6tWVzl9xHs2XXMo/ZaW7oy76PRl+87HkqZpc5Zx501jQqSjG7q1Larhh29OcJc3422Xit/8vjLaFTh7kWZ4xj6Itc17FDHttlSlLdH9iKq/wDxsjZH06isnAyP8c+jvhm384vByguLdtwkyvKswu8mr5rHMK06EYUq0aWzbGMu2jio/wADJfxz6O+Gbfy16eOnCbK+LOVZZYZpmd9l8MvuJ1oStoRlKe6O3bjuTxHZ14b/ACJNN0+WZkuP+ImZfL4fNav5RPHGx4r5FlOX2uQXeVysLudeU61zGe/rw27ebFuGPIz0l/W/Po/+lS+arPxq0dZ6B4m5tpSwuri6oWXYtla4278d1KE/V283tlY0cWVn7fml8/B/m8WNIy/PVr52L0X4laVy/WujMz0zmcY9hvaUoRnt51KfaTj30ZbZPOfhHj1uKukvhqz87Ff/AIsa8tNB3ul7nMpRhl2ZZpjl91OX81hOEpRqeLKMd3eykx8S3dWPIedWpMnv9O6gzDI81pdivrCtO3rw77CXky9fwZN5cifh59MOtZ60zGhuy3I5da168ebVupdH4ked4Uosw5anDO5v8yyzW+QWnZri6q0stv4Uo9KcpbaFX+5LxGxdSXOWcAuT/RsbGdP6IQpRtbXuri9q9Kfi86XgxZb83qUaRj6tRzy1Md3J/wA2992nnYqL6P1DmOldUZbqHKKvYr2wrxrUse67qMu9lHdGXhLxcsbD/u7Zj222vZer/wCrFQZk4bHdTKMlPQjiNlOUceuAVK+ynCONzXt/RuWY49KjdQjj16Uv2qclL+D2gL7iBxDsdLwhVoUuySnf1dvOt6MOnu77tfCk29yHOI0sn1PW0FmVfHCxzaWNWwxxlzYXUY86Pjxj8aPfLRab0PpXR2e6k1Rl9vhaVs5q+ir6rPHm0oxjult7mO7dOXfSanWlib6v+DV/K01hZ8PeENto3II4WVxmlL0Ba06PN7Ba04x7JL4u2HjSUaizjjhru44icRcwz+Up4WMZeh8uo4y+xW8fW8aXOlLvpMHenhUdKr5vPUAG4lIAAAUACQBIAKUACQAAAAAUAACKQAAAAACUgCAAAAWACgAAASAAAAAAAAAClAAAAAAkAAAFAAACRm3AXncadHfDFDyl1+UfxTveFOnsqzOxye3zOpf3kreUK1XGEYRjCUt3NUd4O5pYZJxT0zm+a3Mbaxs8zpVa9afRhCMudJvLln8RdF600xpy10rqGzzWrb39WrXhR3boR7F1oylui8rLq6mRCOungl1eecrnXd3b40sr09keWTl0a2O+tLDwd0oxaH1Ln+damzm4znPsxr39/W6datLr4+DHuY966wb9WNVV6IjIOHOHX4h6aj+drXzsVzOWtqTUOmeGeW32nM4vcquamcQpTrWlWUKkqfYqstvXj2u6MVLdD3ltYa1yK+vKsaVrb5jb1atWXRhTjOMpSWP5YfFDQmtuHmWZZpXUVtmd3DNY150qUJxlGGFKpHdzo4dtKLSya92RD5fAaIjxd4p7t3pgai+WyXa4T5nmefcnLLs1za+r3t9dZJcSr3FaW6c5darhuk88tq5XCDjDw3ybgNk+nM01RQtM1oZXVt6tvKhVlKM5b+tHdGO3tsHziFMdNI7IkVNqf2PD9CRH7HH9A9XT0qXw5D95dXPA+nC5rzqwt80uKNDCXaU+bLbh40pfGUw4m3Nxd8SNTXF1VnVrTza66859LH67KKy3JF4oaC0jwrqZPqbU1nll99FK1aNCtGe7ZKMNsubH8isevrm0vNd6gvLGvGvaV8zuKtCrDozhKrKUZR8V5WFGUciY6RtjhZwA1nxG0nPUmVXeV2VjunChG6nLfXlD19uEY47cN3N5zU7d/Jt47V+Gsp5FnlvVvdN3NXsvWpYYSq2k8fXlCPbRl22HxW7mSt6f7XmlqnLc+1dpXMZ0svzrOcou7WrKE6VK6nSlCcelGUdy9nJd1hqXXnCv6I6todmqwuJ29O7lT2xvaUY9LGPR/DHHHoydNmepuTFra7jn+cXOl7i9xjuqTvKUqNWXhxlt3eN13XcQuUrw+0pkGOWaAwp5vf06XYrWFvQlSs7fuevLrR68Y9zF49spX6bYw+YVN4wZVY5FxT1RlGXRjCytczrQoQj2kd3R8XorUdT59r/Ucfzth5qKmmZX13mWZXWZX1WVe6uqs69erLpTnKW6UvjLL8jPiXonQ+ks+sdU6htsrr3F/CrRhVhOW+PYox3c2OP32/nVy912/UaW47x63GnWcfzzceXJYTkC6stvofnmia9WOFzGvHMLXDGXTjKMYVNvg7Y4+MrfxdzWxzvinqjN8srxubG8zKtXoVo7ts4SlzZc51mkdQ5vpXUVln+R3crTMLKp2SlPD9qMu6jLoyiudGtuNsU21yvOGGZ6T4gX+qrW1qVdP5xXxuMK8I7o29eXqzhPuedulHwu9aOo0qlxXhQoQqVatWW2EIR3SnLuYxXe0JyoOH2pcmxsNd2uOTXM4bLinUt5XFpX8HbhKXW/JKLsrPiHyaNKXEs4yWtpq2vPXjPL8sxlX/2bYc1qV5dtMenOHilWDUnALiPp/RVLVl9lVKVt2CVe6t4VcOz2kO6qwl3vc7tvbNYetFYHlB8oq511llbTGlrSvl2R1+bc1rjH6/dYdztj0IftSV+ejiyulDnaNz0eTZxDnoGerd2V4x9CejKVhTnKdxVht3c3bHbu29rua20vrDVGmLuF1kOoc0y2dKX81cyjHwZQ6MvBlFv7k8cpO10xkttpXXVK5q2NpHClaZjQw7JOlDtYVY+vLCP3pR+K2hV1XyXr3Mvpkr3Okal9LHsuNWraY9kxl3WMNvr+K86V9s'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; 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'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; AioAEqSAQkEUlgAAAoAEgApQAAAJAAABQAAAAAlIApQAAAJAAAAAEgACO0SFAAAAkAAAFKAAAEpAAAAAAABQAAAAAJABQAJABQAJAAAAAAAAAAAADaApHabUhSQBIAKAAUAAAAAAAAACQAAAUAAACQAABIAKUAAIpIpSAkhQAJAGUAEgAoABQAAAAAJAAABQAAAJAEgApQAAAASASAAACgBKQBQAAAJABQACgAAAABKQAAAAAAAAAAAAAABQACgAABKQAAAAABFIAAUoAAAAAEgAoAEgAoAAAAAAAAAEgAoAAASkAUAAAAoAARSRSCSKSAAEgDKACQAUAAoAAAEgCQAUACQAUAAoASkAUoAAAAAAAEgAoAEgAACQAAAAAUAAoAEgCQAAAAAAAAAAAAAAAUAAoAEgCQAAAAAAAUoAEgAAAoAAAAAAAAAAAAAEgAAAoAAAAAEgAoAAAAAARSEiKSKSEgD7EAGQAEgAoABQAAAAAJAAAAAAAARASCQKAAAAABIAAAAAKAAABIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKABIAAAKAAUACQAAAAEQSAFAAAAAAAAAAkAAAFAAAAAAAAAAkAFAAACQAQkAAAZQASACgAFAAAAAAkAFAAAAkAAkikiCQAoASkAAAAAAAUoAAAAASkAAAAAUAAAAACQAUAAAAAAAAAAACQAAAAAUoAAAAAEgAAAoAAAAAAAAAAAAAAAAAAAAAAABFIAAAAAAAAAAAAAAEiKSKSAAEgDKAAAAoAAAAAEgAAAoAAAEgCQAUoAAAEgCQAAAUAAoAAAEgCQAAAAAUACQAUAAAAAAAAoAAAAAEgAAAAAoAAAAAAAAAEgAoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARBKRJFIABAAMoACgAAAAAAASACgAAAAAAASACgAAAAAAAAAAAAAAAABKQAABQACgASACgASAAAAACgAAAAAAAAAAAAAAAAAAAAASAJABQACgAAAAAEUgAAAAAAAAAAAAAAAAAAAAAAEgAoABFIEpAEAAAAygAKAAAAAAABIAKAAAAAAAAAAAAAAAAAAABIAAAAAAAkAAAFAAkAFAAkAFAAAAkAAAFKABIAAAAAKAAABIAKAAAAABIAkAFKAAAAAAAAAAAAAciXAAAAAAoAAAEgAoAAAAASkAUoAAASkAQAD7EAGQAAAAAAAEgAoAAAAABQAAAAAAAAAJAAAAABQAJAAAAAAAEgAAAoAEgAoAEgAAAAAAApQAlIAoAAABQAAAJABQAAAAOXAkAAAAAAAAAAASAAAAAAAAACgAAAAAAAFAAAAkAAAAAAASACAAAAWAAAAAAAAAAAAAAACgAAAFAAkAAAAASAAAAAAACgAAAAAAAFAAACUgCgASAAAAAAACgAAAFAAAAAAACUgCgAFAAkASAAAAAAACgASAAAAAAAAAAAAAAAAACgAAAFACUgAAAAAoAEgCAAAAZQAAASAAAAAAAAAAAAACgEUgA3AoAAAEgCQAAAUoAAASkAUAAAAAAoAEgAAAACQAAAUAjFJIAAACgBQA'use strict'; const $=id=>document.getElementById(id),cv=$('bench'),g=cv.getContext('2d'),KEY='ivl-cp14-thermal-studio-v1',LF=334000,LV=2260000,CW=4200,CI=2100,TM=69.3,LC=200000,CS=2000,TS=-78.5,LS=571000; const names={heat:'Heating ice',cool:'Cooling stearic acid',sub:'Sublimation'}; let store={runs:[],current:null,answers:{}},R,active=false,transfer=null,depth=0,dragging=false,selectedPoints=[],graphMap=null,last=0,saveAt=0,uiAt=0,viewId=null; const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)),fmt=(n,d=1)=>Number(n).toFixed(d),esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function say(s){$('status').textContent=s;} function save(){try{localStorage.setItem(KEY,JSON.stringify(store));$('saveStatus').textContent='Saved on this device';}catch(e){$('saveStatus').textContent='Storage unavailable · export your readings';}} function state(r=R){let h=r.h; if(r.mode==='heat'){if(h<0)return{T:h/CI,phase:'Ice warming',solid:1,liquid:0,remaining:1};if(h=1?'Sample evaporated':'Boiling',solid:0,liquid:1-f,remaining:1-f};} if(r.mode==='cool'){if(h>LC)return{T:TM+(h-LC)/CS,phase:'Liquid cooling',solid:0,liquid:1,remaining:1};if(h>=0)return{T:TM,phase:'Solidifying',solid:1-h/LC,liquid:h/LC,remaining:1};return{T:TM+h/CS,phase:'Solid cooling',solid:1,liquid:0,remaining:1};} if(h<0)return{T:TS+h/850,phase:'Solid CO₂ warming',solid:1,liquid:0,remaining:1};let f=clamp(h/LS,0,1);return{T:TS,phase:f>=1?'Sample sublimed':'Sublimating',solid:1-f,liquid:0,remaining:1-f};} function newTrial(mode=R?.mode||'heat'){active=false;transfer=null;depth=0;let r={id:Date.now()+Math.random(),mode,mass:mode==='heat'?50:25,power:100,bath:25,model:'ideal',probe:'out',stir:true,speed:20,auto:false,interval:30,next:30,time:0,h:mode==='heat'?-10*CI:mode==='cool'?LC+CS*(80-TM):850*(-100-TS),sensor:22,started:false,finished:false,heatOn:false,transferred:false,records:[],note:'',energy:0};store.runs.push(r);store.current=r.id;R=r;viewId=r.id;selectedPoints=[];refresh();say('Place the temperature probe in the sample before starting. Earlier trials remain in Results.');save();} function measuredTarget(r=R){if(r.probe==='out'||depth<.99)return 22;let t=state(r).T;if(r.probe==='wall'){if(r.mode==='heat')t+=r.heatOn?Math.min(6,r.power*.03):0;else if(r.mode==='cool')t-=Math.max(0,(t-r.bath)*.12);else t+=8;}else if(r.mode==='heat'&&r.model==='real'&&!r.stir&&r.heatOn)t+=Math.min(3,r.power*.01);return t;} function updateSensor(dt){let target=measuredTarget(),ideal=R.mode==='heat'&&R.model==='ideal'&&R.probe==='center'&&depth>=.99;if(ideal)R.sensor=target;else R.sensor+=(target-R.sensor)*(1-Math.exp(-dt/(R.stir?3:10)));} function record(source='manual'){if(!R.started){say('Start the trial first, then record temperature against elapsed time.');return;}let t=+fmt(R.time,2);if(R.records.some(r=>Math.abs(r.t-t)<.005)){say('A reading at this time is already recorded. Let time advance for the next reading.');return;}let st=state();R.records.push({t,T:+fmt(R.sensor),power:R.mode==='heat'&&R.heatOn?R.power:0,probe:R.probe,stir:R.stir,source,phase:st.phase});$('count').textContent=R.records.length+' readings in this trial.';if(source==='manual'){say('Recorded '+fmt(t)+' s and '+fmt(R.sensor)+' °C.');save();}} function begin(){if(depth<.99||R.probe==='out'){say('Insert the probe into the sample first.');return;}if(R.finished){say('This sample is finished. Start a new trial to repeat.');return;}if(R.started){active=true;refresh();return;}if(R.mode==='cool'&&!R.transferred){transfer={progress:0};say('Moving the clamped tube into the cooling bath. The clock will start when it arrives.');refresh();return;}R.started=true;R.heatOn=R.mode==='heat';active=true;R.sensor=measuredTarget();R.next=R.interval;if(R.auto)record('timed');refresh();say(R.mode==='heat'?'Heater and clock started. Record readings at regular intervals.':'Clock started. Observe the sample and record temperature regularly.');save();} function advance(dt){if(!active||R.finished)return;while(dt>1e-7&&active){let toLog=R.auto?Math.max(0,R.next-R.time):Infinity;if(toLog<1e-7){record('timed');R.next+=R.interval;continue;}let step=Math.min(.25,dt,toLog),st=state(),rate=0,m=R.mass/1000;if(R.mode==='heat'){let pin=R.heatOn?R.power:0;rate=pin-(R.model==='real'?.35*(st.T-22):0);R.energy+=pin*step;}else if(R.mode==='cool')rate=-.7*(st.T-R.bath);else rate=.45*(22-st.T);R.h+=rate*step/m;R.time+=step;updateSensor(step);dt-=step; if(R.mode==='heat'&&R.h>=LF+CW*100+LV){R.h=LF+CW*100+LV;finish('The sample has evaporated. The heater has switched off; escaping vapour is not retained as a sample.');} else if(R.mode==='sub'&&R.h>=LS){R.h=LS;finish('The solid sample has sublimed. No liquid formed; the gas dispersed into the room.');} else if(R.mode==='cool'&&state().T<=R.bath+.5){finish('The solid is now within 0.5 °C of the bath. The run has ended near thermal equilibrium.');} if(R.auto&&R.time>=R.next-1e-6){record('timed');R.next+=R.interval;} }} function finish(message){R.finished=true;R.heatOn=false;active=false;if(R.auto)record('end');say(message);refresh();save();} function getView(){return store.runs.find(r=>r.id===viewId)||R;} function page(id){document.querySelectorAll('.page').forEach(e=>e.hidden=e.id!==id);document.querySelectorAll('[data-page]').forEach(e=>e.classList.toggle('active',e.dataset.page===id));if(id==='results'){viewId=R.id;renderResults();}draw();} function refresh(){document.querySelectorAll('[data-mode]').forEach(e=>e.classList.toggle('active',e.dataset.mode===R.mode));$('modeDescription').textContent=R.mode==='heat'?'Ice → liquid water → evaporation. Explore mass, power and heat loss.':R.mode==='cool'?'A prepared liquid sample cools and solidifies in a water bath.':'Virtual extension · solid CO₂ changes directly into gas in an open sample.';for(let k of ['mass','power','bath','model','probe','speed','interval'])$(k).value=R[k];for(let k of ['stir','auto'])$(k).checked=R[k];$('massOut').textContent=R.mass+' g';$('powerOut').textContent=R.power+' W';$('bathOut').textContent=R.bath+' °C';$('mass').disabled=$('model').disabled=R.started||!!transfer;$('bath').disabled=R.started||!!transfer;$('bathRow').hidden=R.mode!=='cool';$('powerRow').hidden=$('modelRow').hidden=R.mode!=='heat';$('stirRow').hidden=R.mode==='sub';$('heater').hidden=R.mode!=='heat';$('heater').disabled=!R.started||R.finished;$('heater').textContent=R.heatOn?'Switch heater off':'Switch heater on';$('start').textContent=R.started?(active?'Experiment running':'Resume experiment'):R.mode==='heat'?'Start heating & clock':R.mode==='cool'?'Transfer & start cooling':'Start observation & clock';$('start').hidden=R.started;$('pause').hidden=!R.started;$('pause').classList.add('primary');$('start').disabled=active||!!transfer||R.finished;$('pause').disabled=!R.started||R.finished;$('pause').textContent=active?'Pause experiment':'Resume experiment';$('insert').textContent=R.probe==='out'?'Insert probe':'Remove probe';$('insert').disabled=!!transfer;$('probe').disabled=!!transfer;$('prediction').value=R.note;$('count').textContent=R.records.length+' readings in this trial.';$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';$('phaseText').hidden=!$('overlay').checked;guide();draw();} function guide(){let msg=R.probe==='out'?'The probe is outside the sample: it reads room air. Insert it before taking sample readings.':R.probe==='wall'?'The probe is touching the container. Reposition it centrally, then wait for its reading to settle.':!R.started?'Predict the shape, then start the experiment. Choose manual readings or timed logging.':R.finished?'Use your graph to explain the changes. Start a new trial to compare a different mass or power.':'Look at both the sample and thermometer. Record regularly, even if temperature appears unchanged.';$('guide').textContent=msg;$('moreText').textContent=R.mode==='heat'?'A plateau can occur while energy still enters the sample. Track the shrinking ice and, later, the falling water level. Keep the probe immersed and away from the wall.':R.mode==='cool'?'Look for liquid turning cloudy and solid. Above and below the transition, cooling becomes slower as the sample approaches the bath temperature.':'Watch the solid become smaller. There is no liquid layer. The visible mist represents water droplets in the surrounding air, not the invisible CO₂ gas.';} function renderResults(){let r=getView();$('runSelect').innerHTML=store.runs.map((r,i)=>``).join('');$('runSelect').value=r.id;$('trialInfo').textContent=names[r.mode]+' · '+r.mass+' g · '+(r.mode==='heat'?(r.model==='ideal'?'ideal energy transfer':'heat loss & sensor lag'):r.mode==='cool'?'bath '+r.bath+' °C':'room 22 °C')+' · '+r.records.length+' readings';$('data').innerHTML=r.records.map((d,i)=>`${fmt(d.t,1)}${fmt(d.T)}${d.power}${esc(d.probe)}${d.stir?'Yes':'No'}${d.source}`).join('')||'No readings saved in this trial.';document.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{r.records.splice(+b.dataset.del,1);selectedPoints=[];renderResults();save();});for(let id of ['pointA','pointB'])$(id).innerHTML=r.records.map((d,i)=>``).join('');if(r.records.length>1)$('pointB').value=r.records.length-1;let checks=r.mode==='heat'?[['melting','Melting point'],['boiling','Boiling point']]:r.mode==='cool'?[['freezing','Solidification point']]:[['sublimation','Sublimation point']];$('plateauChecks').innerHTML=checks.map(([key,name])=>`
`).join('');document.querySelectorAll('[data-check]').forEach(b=>b.onclick=()=>checkPlateau(b.dataset.check));$('plateauFeedback').textContent='';$('slopeFeedback').textContent='';drawGraph();} function checkPlateau(key){let r=getView(),expected={melting:0,boiling:100,freezing:TM,sublimation:TS}[key],phase={melting:'Melting',boiling:'Boiling',freezing:'Solidifying',sublimation:'Sublimating'}[key],evidence=r.records.filter(d=>d.phase===phase&&d.probe==='center'&&Math.abs(d.T-expected)<=2),out=$('plateauFeedback');if(evidence.length<2){out.textContent='Collect at least two settled, centred-probe readings during this transition before checking the graph estimate.';return;}let val=parseFloat($('ans-'+key).value);out.textContent=Number.isFinite(val)&&Math.abs(val-expected)<=1?'Correct — your estimate agrees with the transition in this model.':'Check the temperature of the nearly horizontal section. Use the vertical axis, not the duration.';} function exportCSV(){let r=getView(),header=['Trial','Experiment','Mass_g','Model','Bath_C','Time_s','Temperature_C','Heater_W','Probe_position','Stirring','Recording'];let rows=r.records.map(d=>[store.runs.indexOf(r)+1,names[r.mode],r.mass,r.model,r.mode==='cool'?r.bath:'',d.t,d.T,d.power,d.probe,d.stir,d.source]);let csv=[header,...rows].map(row=>row.map(x=>'"'+String(x).replace(/"/g,'""')+'"').join(',')).join('\r\n');let a=document.createElement('a'),url=URL.createObjectURL(new Blob([csv],{type:'text/csv'}));a.href=url;a.download='CP14-'+r.mode+'-trial-'+(store.runs.indexOf(r)+1)+'.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);} function rr(g,x,y,w,h,r=8){g.beginPath();g.roundRect(x,y,w,h,r);} function box(g,x,y,w,h,top,bottom,r=8){let grad=g.createLinearGradient(x,y,x,y+h);grad.addColorStop(0,top);grad.addColorStop(1,bottom);g.fillStyle=grad;rr(g,x,y,w,h,r);g.fill();} function line(g,x1,y1,x2,y2,col,width=2){g.strokeStyle=col;g.lineWidth=width;g.beginPath();g.moveTo(x1,y1);g.lineTo(x2,y2);g.stroke();} function text(g,s,x,y,size=13,col='#233e45',align='left'){g.fillStyle=col;g.font=`${size}px system-ui`;g.textAlign=align;g.fillText(s,x,y);} function circle(g,x,y,r,fill,stroke){g.beginPath();g.arc(x,y,r,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=1;g.stroke();}} function screw(g,x,y){circle(g,x,y,3,'#8a9b9d','#465d63');line(g,x-2,y+1,x+2,y-1,'#344951',1);} function lcd(g,x,y,w,value,label){box(g,x-4,y-4,w+8,48,'#273d43','#162a30',5);box(g,x,y,w,36,'#a9c8b8','#d3dfc2',3);g.fillStyle='#203e37';g.textAlign='right';g.font='bold 22px monospace';g.fillText(value,x+w-8,y+26);text(g,label,x,y+57,10,'#e0e7df');} function knob(g,x,y,r,a){circle(g,x+2,y+4,r+2,'#17272d40');let gr=g.createRadialGradient(x-5,y-8,1,x,y,r);gr.addColorStop(0,'#657983');gr.addColorStop(.7,'#253e47');gr.addColorStop(1,'#142a34');circle(g,x,y,r,gr,'#849493');for(let t=0;t<16;t++){let q=t*Math.PI/8;line(g,x+Math.cos(q)*(r-2),y+Math.sin(q)*(r-2),x+Math.cos(q)*r,y+Math.sin(q)*r,'#94a19d',1);}line(g,x+Math.cos(a)*8,y+Math.sin(a)*8,x+Math.cos(a)*(r-5),y+Math.sin(a)*(r-5),'#fff0bf',3);} function ellipse(x,y,rx,ry,fill,stroke){g.beginPath();g.ellipse(x,y,rx,ry,0,0,Math.PI*2);g.fillStyle=fill;g.fill();if(stroke){g.strokeStyle=stroke;g.lineWidth=2;g.stroke();}} function glass(x,y,w,h,fillHeight,color){let grad=g.createLinearGradient(x,y,x+w,y);grad.addColorStop(0,'#bedcdd88');grad.addColorStop(.12,'#ffffff15');grad.addColorStop(.85,'#e3f5ef22');grad.addColorStop(1,'#88afb47a');g.fillStyle=grad;rr(g,x,y,w,h,14);g.fill();if(fillHeight>5){box(g,x+5,y+h-fillHeight,w-10,fillHeight-5,color,'#74afbb75',10);ellipse(x+w/2,y+h-fillHeight,(w-10)/2,8,color,'#a6dce180');}g.strokeStyle='#7b9fa8';g.lineWidth=2;rr(g,x,y,w,h,14);g.stroke();ellipse(x+w/2,y,w/2,8,'#e3f3ec22','#94b5bb');line(g,x+12,y+15,x+12,y+h-25,'#ffffffaa',6);line(g,x+w-9,y+16,x+w-9,y+h-25,'#e4f8e466',3);for(let j=1;j<5;j++){line(g,x+w-34,y+h-j*h/5,x+w-10,y+h-j*h/5,'#668e93',1);}} function tubeX(){return R.mode==='cool'?(R.transferred?700:transfer?490+210*transfer.progress:490):550;} let lastProbeSide='center'; function probePoint(){ let base=tubeX(),s=state(); if(R.probe!=='out')lastProbeSide=R.probe; let targetX=lastProbeSide==='wall'?base+(R.mode==='cool'?27:120):base; let targetY=R.mode==='heat'&&s.solid===0?Math.min(390,Math.max(360,405-R.mass*s.liquid)):360; // Lift completely clear of the rim, move above the opening, then lower vertically. // Removal retraces the same route; the long handle briefly passes above the bench view. let d=clamp(depth,0,1),parkX=base+160,clearY=R.mode==='cool'?145:150; if(d<.3)return{x:parkX,y:360+(clearY-360)*d/.3}; if(d<.6)return{x:parkX+(targetX-parkX)*(d-.3)/.3,y:clearY}; return{x:targetX,y:clearY+(targetY-clearY)*(d-.6)/.4}; } function drawProbe(){let p=probePoint();line(g,p.x,p.y-210,p.x,p.y,'#6d868b',7);line(g,p.x-1,p.y-205,p.x-1,p.y-4,'#e8efe6',2);box(g,p.x-10,p.y-240,20,35,'#5d8b8c','#214951',6);g.strokeStyle='#263b44';g.lineWidth=3;g.beginPath();g.moveTo(p.x,p.y-240);g.bezierCurveTo(p.x,40,870,50,895,235);g.stroke();text(g,'DRAG PROBE',p.x,p.y-250,10,'#53736e','center');} function bubbles(x,y,w,h){if(!R.started)return;for(let i=0;i<11;i++){let f=(R.time*.05+i*.137)%1,xx=x+18+((i*37)%Math.max(20,w-30)),yy=y+h-f*h;circle(g,xx,yy,2+(i%4),'#e3f8fb55','#b4e5ec99');}} function mist(x,y,n=6){if(!R.started)return;for(let i=0;i0){for(let i=0;i<13;i++){let scale=Math.cbrt(s.solid),xx=x+25+(i*49)%190,yy=y+h-20-Math.floor(i/4)*34;g.save();g.translate(xx,yy);g.rotate(Math.sin(i)*.25);g.scale(scale,scale);box(g,-15,-30,34,30,'#e7f9f7','#a4d5e5',4);line(g,-12,-27,13,-27,'#ffffff',2);line(g,-12,-25,-12,-4,'#ffffff88',2);g.restore();}} if(s.phase==='Boiling'&&s.remaining>0){bubbles(x,y+h-2*R.mass*s.remaining,w,2*R.mass*s.remaining);mist(x+w/2,y-12);} if(R.stir&&R.started&&s.liquid>.1){let xx=x+w/2+Math.sin(R.time*.15)*25;line(g,xx-15,y-35,xx,y+h-30,'#ddece7aa',5);ellipse(xx,y+h-2*R.mass*s.liquid,28,5,'#ffffff00','#b2e1e799');} text(g,'OPEN BEAKER · '+R.mass+' g initial sample',552,541,12,'#46645e','center');} function drawCooling(s){let warmX=350,coldX=610,by=265;ellipse(610,493,300,22,'#36585024');glass(warmX,by,200,190,120,'#c8b88655');glass(coldX,by,200,190,120,'#9acbdc99');text(g,'PREPARATION BATH',warmX+100,490,11,'#55736c','center');text(g,'COOLING BATH · '+R.bath+' °C',coldX+100,490,11,'#55736c','center');line(g,825,102,825,470,'#678187',11);line(g,822,102,822,470,'#d5e2d8',3);box(g,775,465,140,22,'#5c7c7b','#304f56',5);let x=tubeX();line(g,825,170,x,170,'#7f999b',9);circle(g,825,170,13,'#40646a');box(g,x-40,164,80,16,'#678484','#314e57',4);glass(x-32,165,64,235,165,'#ddc891aa');if(s.solid>0){box(g,x-25,393-158*s.solid,50,158*s.solid,'#f6efe0','#d5d1be',9);for(let i=0;i<12*s.solid;i++)circle(g,x-18+(i*13)%36,385-(i*27)%(150*s.solid),2,'#ffffed99');}text(g,'STEARIC ACID · '+R.mass+' g',x,125,11,'#4c6a62','center');if(transfer)text(g,'TRANSFERRING · CLOCK NOT STARTED',600,554,13,'#8d6722','center');} function drawSub(s){ellipse(550,470,190,25,'#43696022');box(g,395,410,310,32,'#c1cccb','#647d85',9);ellipse(550,410,145,18,'#b1c1c4','#506d77');let size=Math.cbrt(s.remaining),w=140*size,h=90*size;if(size>.001){box(g,550-w/2,402-h,w,h,'#f6f7ee','#b7cadb',7);g.fillStyle='#d6e6eb';g.beginPath();g.moveTo(550-w/2,402-h);g.lineTo(550-w/2+20*size,390-h);g.lineTo(550+w/2+20*size,390-h);g.lineTo(550+w/2,402-h);g.closePath();g.fill();for(let i=0;i<8;i++)line(g,550-w/2+(i*23)%Math.max(w,1),402-h+8,550-w/2+(i*23)%Math.max(w,1)+10*size,402-h+25*size,'#ffffff88',2);mist(550,400-h,8);}text(g,'OPEN SAMPLE · NO LIQUID PHASE',550,495,12,'#4a6e68','center');text(g,'Room at 22 °C supplies energy',550,523,13,'#4a6e68','center');} function miniGraph(x,y,w,h){box(g,x,y,w,h,'#183a43','#14333d',4);let data=R.records;if(!data.length){text(g,'NO SAVED READINGS',x+w/2,y+h/2,11,'#92b7b6','center');return;}let max=Math.max(30,data[data.length-1].t),lo=R.mode==='heat'?-15:R.mode==='cool'?20:-105,hi=R.mode==='heat'?110:R.mode==='cool'?85:-65;for(let j=1;j<4;j++)line(g,x+10,y+j*h/4,x+w-10,y+j*h/4,'#28515b',1);g.beginPath();data.forEach((d,i)=>{let xx=x+10+d.t/max*(w-20),yy=y+h-10-(d.T-lo)/(hi-lo)*(h-20);i?g.lineTo(xx,yy):g.moveTo(xx,yy);});g.strokeStyle='#e9cc75';g.lineWidth=2;g.stroke();} function draw(){if(!R)return;let s=state();g.clearRect(0,0,1200,620);box(g,0,0,1200,620,'#e1e8df','#bdcfc3',0);for(let y=60;y<620;y+=45)line(g,0,y,1200,y,'#b2c6b733',1);box(g,0,590,1200,30,'#a2b8aa','#7d9789',0);text(g,'IVL / THERMAL LABORATORY',25,34,12,'#52736a');text(g,active?'RUNNING · '+R.speed+'×':transfer?'PREPARING':R.finished?'RUN COMPLETE':R.started?'PAUSED':'SETUP',1175,34,12,'#52736a','right'); if(R.mode==='heat')drawHeat(s);else if(R.mode==='cool')drawCooling(s);else drawSub(s); // Independent energy controller with physical output switch. box(g,45,250,255,200,'#d2dcd7','#809997',12);box(g,56,261,233,175,'#6f9394','#426c75',8);text(g,R.mode==='heat'?'HEATER CONTROLLER':'ENVIRONMENT',75,286,13,'#ddeae0');lcd(g,77,307,170,R.mode==='heat'?R.power+' W':R.mode==='cool'?R.bath+' °C':'22 °C',R.mode==='heat'?'SAMPLE HEATING POWER':'BATH / ROOM TEMPERATURE');knob(g,240,397,23,R.mode==='heat'?-.8*Math.PI+R.power/200*1.6*Math.PI:0);box(g,80,384,90,33,'#264a52','#18353f',5);text(g,R.mode==='heat'?(R.heatOn?'HEATER ON':'HEATER OFF'):'RESERVOIR',125,405,10,R.heatOn?'#b7ebb8':'#c4d9d0','center');for(let p of [[55,260],[290,260],[55,438],[290,438]])screw(g,...p); if(R.mode==='heat'){g.strokeStyle='#2e4b51';g.lineWidth=4;g.beginPath();g.moveTo(290,411);g.bezierCurveTo(335,495,377,520,414,476);g.stroke();}drawProbe(); box(g,895,215,260,280,'#d8e1da','#779197',12);box(g,906,226,238,257,'#436b75','#294b5a',8);text(g,'TEMPERATURE LOGGER',920,248,12,'#d5e7df');lcd(g,922,263,204,fmt(R.sensor)+' °C','PROBE TEMPERATURE');box(g,922,335,204,30,'#1b3b46','#17333d',4);text(g,fmt(R.time,1)+' s',1024,356,18,'#dfdca6','center');miniGraph(922,380,204,77);text(g,R.records.length+' READINGS SAVED',1024,477,9,'#b8d5cc','center'); if(R.probe==='out')text(g,'Probe is reading room air',1024,523,12,'#8c5a2c','center');else if(depth<.99)text(g,'Positioning probe…',1024,523,12,'#8c5a2c','center');else if(R.probe==='wall')text(g,'Probe touching container',1024,523,12,'#a04c33','center');else text(g,'Probe immersed in sample',1024,523,12,'#426b60','center'); if($('overlay').checked){box(g,360,55,450,45,'#163e43','#163e43',8);text(g,s.phase+' · '+fmt(s.T)+' °C',585,83,18,'#f2d58d','center');}if(!active&&R.started&&!R.finished){box(g,472,550,230,28,'#f5e4b9','#e9d8a6',5);text(g,'EXPERIMENT PAUSED',587,569,12,'#765b2b','center');}} function drawGraph(){let r=getView(),d=r.records,c=$('graph'),ctx=c.getContext('2d'),W=850,H=500,l=70,right=825,t=30,b=435,maxT=Math.max(60,...d.map(x=>x.t)),lo=Math.floor((Math.min(0,...d.map(x=>x.T))-5)/10)*10,hi=Math.ceil((Math.max(10,...d.map(x=>x.T))+5)/10)*10;let X=v=>l+v/maxT*(right-l),Y=v=>b-(v-lo)/(hi-lo)*(b-t);graphMap={d,l,right,t,b,maxT,lo,hi,X,Y};ctx.fillStyle='#fffef9';ctx.fillRect(0,0,W,H);for(let i=0;i<=6;i++){let x=l+i/6*(right-l),y=t+i/6*(b-t);line(ctx,x,t,x,b,'#dde6dd',1);line(ctx,l,y,right,y,'#dde6dd',1);text(ctx,fmt(maxT*i/6,0),x,b+22,11,'#55756d','center');text(ctx,fmt(hi-i/6*(hi-lo),1),l-8,y+4,11,'#55756d','right');}text(ctx,'Temperature / °C',l,18,12,'#325b5e');text(ctx,'Time / s',W/2,H-15,13,'#325b5e','center');if($('join').checked&&d.length){ctx.beginPath();d.forEach((p,i)=>i?ctx.lineTo(X(p.t),Y(p.T)):ctx.moveTo(X(p.t),Y(p.T)));ctx.strokeStyle='#72a7a1';ctx.lineWidth=2;ctx.stroke();}d.forEach((p,i)=>circle(ctx,X(p.t),Y(p.T),4,selectedPoints.includes(i)?'#c1852f':'#087f80','#ffffff'));if(selectedPoints.length===2){let a=d[selectedPoints[0]],z=d[selectedPoints[1]];if(a&&z){ctx.setLineDash([5,4]);line(ctx,X(a.t),Y(a.T),X(z.t),Y(a.T),'#bd8a32',2);line(ctx,X(z.t),Y(a.T),X(z.t),Y(z.T),'#bd8a32',2);ctx.setLineDash([]);$('pointInfo').textContent=`A: ${a.t} s, ${a.T} °C. B: ${z.t} s, ${z.T} °C.`;}}else $('pointInfo').textContent='Select two readings to calculate an average rate.';if(!d.length)text(ctx,'Record measurements to build your graph',W/2,H/2,19,'#628378','center');} for(let b of document.querySelectorAll('[data-page]'))b.onclick=()=>page(b.dataset.page);for(let b of document.querySelectorAll('[data-mode]'))b.onclick=()=>{if(b.dataset.mode!==R.mode)newTrial(b.dataset.mode);}; $('insert').onclick=()=>{R.probe=R.probe==='out'?'center':'out';refresh();save();};$('probe').onchange=e=>{R.probe=e.target.value;refresh();save();};$('start').onclick=begin;$('pause').onclick=()=>{if(R.finished)return;active=!active;refresh();say(active?'Experiment resumed.':'Time, energy transfer and readings are paused.');save();};$('heater').onclick=()=>{R.heatOn=!R.heatOn;say(R.heatOn?'Heater on. The clock continues.':'Heater off. The clock continues; in heat-loss mode the sample exchanges energy with the room.');refresh();save();};$('record').onclick=()=>record();$('resultsButton').onclick=()=>page('results');$('newRun').onclick=()=>newTrial();$('expand').onclick=()=>{let on=$('frame').classList.toggle('expanded');$('expand').textContent=on?'Fit bench':'Enlarge bench';};$('hint').onclick=()=>{$('more').open=!$('more').open;guide();say($('guide').textContent);}; for(let k of ['mass','power','bath','speed','interval'])$(k).oninput=e=>{R[k]=+e.target.value;if(k==='interval')R.next=(Math.floor(R.time/R.interval)+1)*R.interval;refresh();save();};$('model').onchange=e=>{R.model=e.target.value;refresh();save();};$('stir').onchange=e=>{R.stir=e.target.checked;save();};$('auto').onchange=e=>{R.auto=e.target.checked;R.next=(Math.floor(R.time/R.interval)+1)*R.interval;say(R.auto?'Timed logging enabled. Next reading at '+R.next+' simulated seconds.':'Timed logging off. Use Record reading to save measurements.');save();};$('overlay').onchange=refresh;$('prediction').oninput=e=>{R.note=e.target.value;save();};document.querySelectorAll('[data-answer]').forEach(e=>e.oninput=()=>{store.answers[e.dataset.answer]=e.value;save();});$('runSelect').onchange=e=>{viewId=+e.target.value;selectedPoints=[];renderResults();};$('export').onclick=exportCSV;$('deleteRun').onclick=()=>{let r=getView();if(!confirm('Delete this trial and its readings?'))return;store.runs=store.runs.filter(x=>x.id!==r.id);if(r===R){transfer=null;if(store.runs.length){R=store.runs[store.runs.length-1];store.current=R.id;active=false;depth=R.probe==='out'?0:1;refresh();}else newTrial(r.mode);}viewId=R.id;selectedPoints=[];renderResults();save();};$('join').onchange=drawGraph;$('selectPoints').onclick=()=>{selectedPoints=+$('pointA').value===+$('pointB').value?[+$('pointA').value]:[+$('pointA').value,+$('pointB').value];drawGraph();};$('checkSlope').onclick=()=>{let r=getView(),out=$('slopeFeedback');if(selectedPoints.length!==2){out.textContent='Choose two distinct readings first.';return;}let a=r.records[selectedPoints[0]],b=r.records[selectedPoints[1]];if(!a||!b||a.t===b.t){out.textContent='Choose readings taken at different times.';return;}let correct=(b.T-a.T)/(b.t-a.t),answer=parseFloat($('slope').value);out.textContent=Number.isFinite(answer)&&Math.abs(answer-correct)<=Math.max(.002,Math.abs(correct)*.05)?'Correct — your average rate agrees with these readings.':'Try (temperature B − temperature A) ÷ (time B − time A). Keep the sign and use seconds.';}; function gp(e){let r=$('graph').getBoundingClientRect();return{x:(e.clientX-r.left)*850/r.width,y:(e.clientY-r.top)*500/r.height};}$('graph').onpointermove=e=>{if(!graphMap)return;let p=gp(e),m=graphMap,t=(p.x-m.l)/(m.right-m.l)*m.maxT,T=m.lo+(m.b-p.y)/(m.b-m.t)*(m.hi-m.lo);$('coords').textContent='Cursor: '+fmt(t)+' s, '+fmt(T)+' °C. Select measured points for an interval.';};$('graph').onpointerdown=e=>{let p=gp(e),m=graphMap;if(!m||!m.d.length)return;let near=m.d.map((d,i)=>({i,dist:Math.hypot(m.X(d.t)-p.x,m.Y(d.T)-p.y)})).sort((a,b)=>a.dist-b.dist)[0];if(near.dist>25)return;if(selectedPoints.length===2)selectedPoints=[];if(!selectedPoints.includes(near.i))selectedPoints.push(near.i);drawGraph();}; function bp(e){let r=cv.getBoundingClientRect();return{x:(e.clientX-r.left)*1200/r.width,y:(e.clientY-r.top)*620/r.height};}cv.onpointerdown=e=>{if(transfer)return;let p=bp(e),q=probePoint();if(Math.hypot(p.x-q.x,p.y-(q.y-222))<35){dragging={x:p.x,y:p.y};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>610&&p.x<680&&p.y>440&&p.y<500){dragging={power:true,y:p.y,p:R.power};cv.setPointerCapture(e.pointerId);}else if(R.mode==='heat'&&p.x>75&&p.x<175&&p.y>380&&p.y<420&&R.started&&!R.finished)$('heater').onclick();};cv.onpointermove=e=>{if(!dragging)return;let p=bp(e);if(dragging.power){R.power=clamp(Math.round((dragging.p+(dragging.y-p.y)*2)/10)*10,40,200);$('power').value=R.power;$('powerOut').textContent=R.power+' W';draw();return;}let x=tubeX(),dist=Math.abs(p.x-x);R.probe=dist>(R.mode==='cool'?50:135)||p.y<90?'out':dist>(R.mode==='cool'?17:100)?'wall':'center';updateSensor(.25);$('probe').value=R.probe;draw();};cv.onpointerup=()=>{dragging=false;refresh();save();};cv.onpointercancel=()=>dragging=false; function tick(now){let dt=last?Math.min(.08,(now-last)/1000):.016;last=now;if(!dragging)depth=R.probe==='out'?Math.max(0,depth-dt*.8):Math.min(1,depth+dt*.8);if(transfer){transfer.progress=Math.min(1,transfer.progress+dt*.7);if(transfer.progress===1){R.transferred=true;transfer=null;begin();}}else if(active)advance(dt*R.speed);else if(!R.started)updateSensor(dt*R.speed);if(now-uiAt>80){$('temperature').textContent=fmt(R.sensor)+' °C';$('clock').textContent=fmt(R.time,0)+' s';let st=state();$('phaseText').textContent=st.phase+' · '+fmt(st.T)+' °C (model sample temperature).';draw();uiAt=now;}if(now-saveAt>3000){save();saveAt=now;}requestAnimationFrame(tick);} try{let old=JSON.parse(localStorage.getItem(KEY));if(old&&Array.isArray(old.runs)&&old.runs.length){store=old;R=store.runs.find(r=>r.id===store.current)||store.runs[store.runs.length-1];viewId=R.id;depth=R.probe==='out'?0:1;refresh();say(R.finished?'Your completed trial was restored. Open Results or start a new trial.':'Your trial was restored and is paused. Resume when ready.');}}catch(e){} if(!R)newTrial('heat');document.querySelectorAll('[data-answer]').forEach(e=>e.value=store.answers[e.dataset.answer]||'');requestAnimationFrame(tick); window.LAB={state,get run(){return R;},get runs(){return store.runs;},advance,begin,newTrial,record,refresh,get active(){return active;},set active(v){active=v;},set depth(v){depth=v;},draw,save}; AKAABHckiAkiAkIpCgBKQBSgASAJAAAAAAABQACgASAJAAAAAAAAAAABQAAAAAJAAUAAAAAIABaQAABQAJAAAAUAAAAACQAAAAAAAUACQAAAAAUAAAKABKQAUACQAUAAAAAAAAAG5IAAAKABKKQCgAAAAAAASAAAAG0AEUgAAAAAAAAAAAAAAAAUACQAAAAAAAAAAAAAUACQAAAAAAAAAAAUCKSAAWAAAAAAAAAIgkAAAAAAAAAAAAAAAAAAAAAAAAAACIJAAAAAiCQAAAAikgAFgAAAAAgBFJYAAAAAiCSIAJAAAAAAAAAAAAAAAAAAIpAAAAAAAAAAIABYAAAAAiCQiAkIpAAAAAAAAAAAAiCQAAHrg//Z" alt="Impulse Virtual Labs">
Thermal physics · IVL CP14

Temperature–Time Lab

Follow the temperature. Look for the change.

Place the temperature probe in the sample before starting.

Set up the investigation

Mass and model are fixed once a trial starts. Heater power and probe placement can change; each reading records their settings.

Measure & record

Probe temperature— °C
Elapsed time0 s

No readings recorded.

Manual recording is the default. Timed logging samples at exact simulated intervals. A paused experiment preserves both time and temperature.

✦ Ember · Lab Guide

More help

Try to explain your measured curve before turning on the state explanation.