diff --git a/src/experiments/firefly/firefly-beat-ui.mjs b/src/experiments/firefly/firefly-beat-ui.mjs index 3d9be47..7d9d9fa 100644 --- a/src/experiments/firefly/firefly-beat-ui.mjs +++ b/src/experiments/firefly/firefly-beat-ui.mjs @@ -1,4 +1,4 @@ -import {createBeatLesson,selectBeatCase,guessBeat,runBeat,retryBeat,createCatBeatScene,runCatBeat} from './firefly-beat.mjs?v=pond-bobby-v1'; +import {createBeatLesson,selectBeatCase,guessBeat,runBeat,retryBeat,createCatBeatScene,runCatBeat} from './firefly-beat.mjs?v=firefly-render-v1'; const names={faster:'加快追上',slower:'放慢等一等',same:'照自己的节拍走'}; const contexts={ahead:'三只邻居此刻领先 ¼ 圈。它们和金色这只的天生步速完全相同。',behind:'三只邻居此刻落后 ¼ 圈。它们和金色这只的天生步速完全相同。',out:'邻居仍领先 ¼ 圈,但距离在听见范围外。这只还会追上去吗?'}; @@ -99,7 +99,19 @@ export function mountBeatLesson({document=globalThis.document,onStart=()=>{}}={} }); $('beat-retry').addEventListener('click',()=>{prepare();state=retryBeat(state);index=0;render();$('beat-faster').focus({preventScroll:true});}); $('beat-scrub').addEventListener('input',()=>{if(!state.comparison)return;prepare();const value=Number($('beat-scrub').value);index=Number.isFinite(value)?Math.max(0,Math.min(30,Math.round(value))):0;renderFrames();}); - function schedule(){const current=token;raf=requestAnimationFrame(now=>{if(current!==token||document.hidden)return;raf=null;if(origin===null)origin=now;index=Math.min(30,startIndex+Math.floor((now-origin)*30/2000));if(index<30)schedule();renderFrames();});} + function schedule(){ + const current=token; + raf=requestAnimationFrame(now=>{ + if(current!==token||document.hidden)return; + raf=null;if(origin===null)origin=now; + const previous=index; + index=Math.min(30,startIndex+Math.floor((now-origin)*30/2000)); + if(index<30)schedule(); + // This replay shows recorded beats, not interpolated animation. Preserve + // the DOM until the beat changes, including the final stopped state. + if(index!==previous)renderFrames(); + }); + } $('beat-replay').addEventListener('click',()=>{ if(!state.comparison||reduced||document.hidden)return; if(raf!==null){stop();renderFrames();return;} diff --git a/src/experiments/firefly/firefly-beat.mjs b/src/experiments/firefly/firefly-beat.mjs index a31b3d4..18af444 100644 --- a/src/experiments/firefly/firefly-beat.mjs +++ b/src/experiments/firefly/firefly-beat.mjs @@ -1,4 +1,4 @@ -import {TAU,stepSwarm,configureSwarm,perturbSwarm} from './firefly-core.mjs?v=pond-bobby-v1'; +import {TAU,stepSwarm,configureSwarm,perturbSwarm} from './firefly-core.mjs?v=firefly-render-v1'; const copy=world=>({...world,settings:{...world.settings},points:world.points.map(p=>({...p}))}); const scenarios=new Set(['ahead','behind','out']),guesses=new Set(['faster','slower','same']); diff --git a/src/experiments/firefly/firefly.html b/src/experiments/firefly/firefly.html index 288e292..c74f3cf 100644 --- a/src/experiments/firefly/firefly.html +++ b/src/experiments/firefly/firefly.html @@ -4,8 +4,8 @@ - - 算法游乐场 · 萤火虫合奏 + + 算法游乐场 · 萤火虫合奏 diff --git a/src/experiments/firefly/firefly.mjs b/src/experiments/firefly/firefly.mjs index 8d7159a..d9211f3 100644 --- a/src/experiments/firefly/firefly.mjs +++ b/src/experiments/firefly/firefly.mjs @@ -1,5 +1,5 @@ -import {TAU,createSwarm,stepSwarm,coherence,configureSwarm,perturbSwarm,measureGroups,createListening,advanceListening,chooseListening,listeningOutcome,answerListening} from './firefly-core.mjs?v=pond-bobby-v1'; -import {mountBeatLesson} from './firefly-beat-ui.mjs?v=pond-bobby-v1&entry=bobby-tap'; +import {TAU,createSwarm,stepSwarm,coherence,configureSwarm,perturbSwarm,measureGroups,createListening,advanceListening,chooseListening,listeningOutcome,answerListening} from './firefly-core.mjs?v=firefly-render-v1'; +import {mountBeatLesson} from './firefly-beat-ui.mjs?v=firefly-render-v1&entry=bobby-tap'; const $=id=>document.getElementById(id),field=$('fireflies'),ctx=field.getContext('2d'); const clock=$('phase-clock').getContext('2d'),chart=$('history').getContext('2d'); @@ -152,8 +152,11 @@ if(!ctx||!clock||!chart){ function frame(now){ raf=null;if(!playing||document.hidden)return; if(last!==null)accumulator+=Math.min(.1,(now-last)/1000);last=now; - while(accumulator>=DT&&playing){tick();accumulator-=DT;} - draw();schedule(); + let advanced=false; + while(accumulator>=DT&&playing){tick();accumulator-=DT;advanced=true;} + // Display refreshes may outnumber the fixed simulation steps. Inputs still + // draw immediately; an unchanged animation frame needs no duplicate paint. + if(advanced)draw();schedule(); } function cancelGesture(){gesture=null;} function pause(message){document.dispatchEvent(new Event('firefly-world-action'));playing=false;cancelGesture();if(raf!==null)cancelAnimationFrame(raf);raf=null;last=null;accumulator=0;controls(message);draw();} diff --git a/tests/experiments/firefly/firefly-beat-ui.test.mjs b/tests/experiments/firefly/firefly-beat-ui.test.mjs index ea861f1..6ed32d7 100644 --- a/tests/experiments/firefly/firefly-beat-ui.test.mjs +++ b/tests/experiments/firefly/firefly-beat-ui.test.mjs @@ -1,13 +1,14 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import {readFile,access} from 'node:fs/promises'; -async function boot({reduced=false,hash='#listening-lesson'}={}){ +async function boot({reduced=false,hash='#listening-lesson',source=false}={}){ const html=await readFile(new URL('../../../dist/firefly.html',import.meta.url),'utf8'); assert.match(html,/id="beat-open"/,'the microscope needs a real user entry point'); - const file=new URL('../../../dist/firefly-beat-ui.mjs',import.meta.url);assert.ok(await access(file).then(()=>true,()=>false)); + const file=new URL(`../../../${source?'src/experiments/firefly':'dist'}/firefly-beat-ui.mjs`,import.meta.url);assert.ok(await access(file).then(()=>true,()=>false)); let doc,pauses=0,seq=0; class Element extends EventTarget{ - constructor(){super();this.dataset={};this.attrs={};this.hidden=false;this.disabled=false;this.value='';this.textContent='';this.innerHTML='';} + constructor(){super();this.dataset={};this.attrs={};this.hidden=false;this.disabled=false;this.value='';this.textContent='';this.htmlWrites=0;this.innerHTML='';} + set innerHTML(value){this.html=value;this.htmlWrites++;}get innerHTML(){return this.html;} setAttribute(k,v){this.attrs[k]=String(v);}getAttribute(k){return this.attrs[k];} focus(){doc.activeElement=this;}scrollIntoView(options){doc.scrollTarget=this;doc.scrollOptions=options;} } @@ -27,6 +28,26 @@ async function boot({reduced=false,hash='#listening-lesson'}={}){ visible(value){doc.hidden=!value;doc.dispatchEvent(new Event('visibilitychange'));}, reduce(value){media.matches=value;media.dispatchEvent(Object.assign(new Event('change'),{matches:value}));}}; } +test('slow replay draws each of its 30 recorded beats once on a 120Hz screen',async()=>{ + const u=await boot({source:true});try{ + const e=id=>u.els.get(id); + u.click('beat-open');u.click('beat-faster');u.click('beat-run'); + const sealed=e('beat-numbers').textContent,finalDial=e('beat-after').innerHTML; + u.click('beat-replay'); + const writes=e('beat-after').htmlWrites,before=e('beat-before').innerHTML; + assert.match(e('beat-replay').textContent,/暂停/); + u.frame(0);u.frame(1000/120); + assert.equal(e('beat-after').htmlWrites,writes,'no DOM replacement while the recorded beat is unchanged'); + for(let i=2;i<=240;i++)u.frame(i*1000/120); + assert.equal(e('beat-after').htmlWrites-writes,30); + assert.equal(e('beat-scrub').value,'30');assert.equal(u.frames.size,0); + assert.equal(e('beat-after').innerHTML,finalDial); + assert.equal(e('beat-before').innerHTML,before); + assert.equal(e('beat-numbers').textContent,sealed,'slow playback cannot change the sealed experiment'); + assert.match(e('beat-replay').textContent,/慢放/,'the final beat must restore the replay action'); + }finally{u.restore();} +}); + test('the listening heading offers one optional native link to the cat beat',async()=>{ const html=await readFile(new URL('../../../dist/firefly.html',import.meta.url),'utf8'); const links=[...html.matchAll(/]*href="#cat-beat"[^>]*>/g)]; diff --git a/tests/experiments/firefly/firefly-ui.test.mjs b/tests/experiments/firefly/firefly-ui.test.mjs index 6d4437d..5a599e8 100644 --- a/tests/experiments/firefly/firefly-ui.test.mjs +++ b/tests/experiments/firefly/firefly-ui.test.mjs @@ -12,11 +12,13 @@ test('mobile reading order reaches scene settings before secondary observation c } }); let bootNumber=0; -async function boot({hidden=false,reducedMotion=false}={}){ +async function boot({hidden=false,reducedMotion=false,source=false}={}){ const frames=new Map();let nextFrame=0; + const paints={field:0,gradients:0}; const arcs=[]; - const context={createRadialGradient:()=>({addColorStop(){}})}; + const context={createRadialGradient:()=>{paints.gradients++;return {addColorStop(){}};}}; for(const name of ['fillRect','beginPath','arc','fill','stroke','setLineDash','ellipse','moveTo','lineTo','clearRect','fillText'])context[name]=()=>{}; + context.fillRect=()=>{paints.field++;}; context.setLineDash=values=>{context.dash=[...values];}; context.arc=(...args)=>arcs.push({args,dash:[...(context.dash||[])]}); class Element extends EventTarget{ @@ -42,15 +44,32 @@ async function boot({hidden=false,reducedMotion=false}={}){ const previous=new Map(Object.keys(globals).map(key=>[key,Object.getOwnPropertyDescriptor(globalThis,key)])); const restore=()=>{for(const [key,descriptor] of previous)if(descriptor)Object.defineProperty(globalThis,key,descriptor);else delete globalThis[key];}; Object.assign(globalThis,globals); - try{await import(new URL(`../../../dist/firefly.mjs?lifecycle-test=${++bootNumber}`,import.meta.url));} + try{await import(new URL(`../../../${source?'src/experiments/firefly':'dist'}/firefly.mjs?lifecycle-test=${++bootNumber}`,import.meta.url));} catch(error){restore();throw error;} - return {document,frames,elements,arcs,restore,visible(value){document.hidden=!value;document.dispatchEvent(new Event('visibilitychange'));}}; + return {document,frames,elements,arcs,paints,restore, + frame(now){const pending=[...frames.values()];frames.clear();for(const callback of pending)callback(now);}, + visible(value){document.hidden=!value;document.dispatchEvent(new Event('visibilitychange'));}}; } const press=(field,key,repeat=false)=>field.dispatchEvent(Object.assign(new Event('keydown',{cancelable:true}),{key,repeat})); function tap(field,x,y){ for(const name of ['pointerdown','pointerup'])field.dispatchEvent(Object.assign(new Event(name),{pointerId:1,pointerType:'touch',isPrimary:true,button:0,clientX:x,clientY:y})); } +test('high-refresh playback redraws the pond only after a real simulation step',async()=>{ + const ui=await boot({source:true});try{ + const initial={...ui.paints}; + ui.frame(0);ui.frame(1000/120); + assert.equal(ui.paints.field-initial.field,0,'unchanged 120Hz frames must not rebuild the pond'); + assert.equal(ui.paints.gradients-initial.gradients,0); + for(let i=2;i<720;i++)ui.frame(i*1000/120); + ui.frame(6001); + assert.equal(ui.paints.field-initial.field,360,'six simulated seconds still run 360 original steps'); + assert.equal(ui.paints.gradients-initial.gradients,360*81,'each changed frame keeps all 80 original fireflies and the backdrop'); + assert.equal(ui.elements.get('elapsed').textContent,'6.0 秒'); + assert.equal(ui.frames.size,1,'skipping a redraw must not stop the simulation clock'); + }finally{ui.restore();} +}); + test('range legend distinguishes the adjustable neighbor radius from the fixed direct intervention',async()=>{ const ui=await boot({reducedMotion:true}); try{