import {defaults,normalize,geometry,curvature,surfacePoint,elevated,sampleScene,pixelOffset} from './core.mjs'; const $=id=>document.getElementById(id);let state={...defaults},timer;try{const hash=location.hash.slice(1);if(hash)state=normalize(JSON.parse(decodeURIComponent(hash)));else if(localStorage.getItem('cave-lab'))state=normalize(JSON.parse(localStorage.getItem('cave-lab')));}catch{$('error').textContent='Saved scenario invalid; defaults restored.';} const fields=[['distance','Surface distance',0.01,200,0.01,'basic','km'],['observer','Observer height',0.1,1000,0.1,'basic','m'],['target','Target height',0.1,1000,0.1,'basic','m'],['radius','Surface radius',1000,10000,1,'basic','km'],['k','Refraction coefficient k',-5,5,0.01,'uniform',''],['temperature','Surface temperature',-60,60,0.1,'atmosphere','°C'],['pressure','Surface pressure',300,1100,1,'atmosphere','hPa'],['layerGradient','Near-surface gradient',-0.5,0.5,0.001,'atmosphere','°C/m'],['gradient','Background gradient',-0.05,0.05,0.0005,'atmosphere','°C/m'],['layer','Layer transition height',1,500,1,'atmosphere','m'],['fov','Horizontal field of view',0.1,120,0.1,'camera','°'],['width','Image width',100,10000,1,'camera','px']]; function factor(key){if(['distance','radius'].includes(key))return state.units==='imperial'?1609.344:1000;if(['observer','target','layer'].includes(key))return state.units==='imperial'?0.3048:1;return 1;} function unit(key,u){return ['distance','radius'].includes(key)?(state.units==='imperial'?'mi':'km'):['observer','target','layer'].includes(key)?(state.units==='imperial'?'ft':'m'):u;} for(const [key,label,min,max,step,group,u] of fields){const el=document.createElement('div');el.className='control';el.innerHTML=`
`;$(group).append(el);for(const id of [key,key+'N'])$(id).addEventListener(id===key?'input':'change',()=>{try{state=normalize({...state,[key]:Number($(id).value)*factor(key)});$('error').textContent='';sync();schedule();}catch(e){$('error').textContent=e.message;}});} function sync(){for(const key of ['model','mode','units'])$(key).value=state[key];for(const [key,,min,max,step,,u] of fields){const f=factor(key),base=['distance','radius'].includes(key)?1000:1;$(key).min=min*base/f;$(key).max=max*base/f;$(key).step=step*base/f;$(key).value=state[key]/f;$(key+'N').value=Number((state[key]/f).toPrecision(8));$(key+'Unit').textContent=unit(key,u);} $('uniform').hidden=state.mode!=='uniform';$('atmosphere').hidden=state.mode!=='atmosphere';} for(const key of ['model','mode','units'])$(key).addEventListener('change',()=>{state=normalize({...state,[key]:$(key).value});sync();schedule();}); const presets={clear:{...defaults},standard:{...defaults,mode:'uniform',k:0.17},upward:{...defaults,mode:'atmosphere',observer:2,layerGradient:-0.15,layer:8},inversion:{...defaults,mode:'atmosphere',layerGradient:0.08,layer:25}}; for(const button of document.querySelectorAll('[data-preset]'))button.onclick=()=>{state=normalize({...presets[button.dataset.preset],units:state.units});document.querySelectorAll('[data-preset]').forEach(b=>b.classList.toggle('active',b===button));if(state.mode==='atmosphere')$('advanced').open=true;sync();schedule();}; $('reset').onclick=()=>{state={...defaults};history.replaceState(null,'',location.pathname);sync();schedule();};$('share').onclick=async()=>{const url=location.href.split('#')[0]+'#'+encodeURIComponent(JSON.stringify(state));history.replaceState(null,'',url);try{await navigator.clipboard.writeText(url);$('error').textContent='Scenario link copied.';}catch{$('error').textContent='Scenario saved in address bar; copy the URL.';}};$('save').onclick=()=>{try{localStorage.setItem('cave-lab',JSON.stringify(state));$('error').textContent='Scenario saved on this device.';}catch{$('error').textContent='Local storage unavailable.';}}; function schedule(){clearTimeout(timer);$('status').textContent='Updating scenario…';timer=setTimeout(render,100);} function render(){const s=state,g=geometry(s),c=curvature(s),scene=s.mode==='none'?null:sampleScene(s,Math.min(100,s.distance/100),161);let rays;if(scene){const paths=scene.paths;rays=(paths.length?paths:scene.rays.filter(r=>r.status==='surface')).filter((r,i,arr)=>i%Math.max(1,Math.floor(arr.length/8))===0).slice(0,10).map(r=>r.points);}else rays=[[{x:0,y:s.observer},elevated(s.distance,s.target,c)]]; const surface=Array.from({length:101},(_,i)=>surfacePoint(s.distance*i/100,c)),all=[...surface,elevated(s.distance,s.target,c),{x:0,y:s.observer},...rays.flat()],lo=Math.min(...all.map(p=>p.y)),hi=Math.max(...all.map(p=>p.y)),range=Math.max(10,hi-lo),X=x=>45+x/s.distance*610,Y=y=>350-(y-lo)/range*270,path=ps=>ps.map((p,i)=>`${i?'L':'M'}${X(p.x).toFixed(2)},${Y(p.y).toFixed(2)}`).join(' ');const top=elevated(s.distance,s.target,c),base=surface.at(-1); $('diagram').innerHTML=`${rays.map(ps=>``).join('')}OBSERVERTARGET${s.model.toUpperCase()} · ${s.mode.toUpperCase()}`; const fmt=n=>`${(n/(s.units==='imperial'?0.3048:1)).toLocaleString(undefined,{maximumFractionDigits:2})} ${s.units==='imperial'?'ft':'m'}`,metric=(label,value,color='')=>`
${label}
${value}
`;$('readouts').innerHTML=metric('Geometric hidden height',fmt(Math.min(s.target,g.hidden)),'red')+metric('Geometric visible height',fmt(g.visible),'green')+metric('Surface tangent drop',fmt(g.drop),'red')+metric('Chord sagitta',fmt(g.sagitta),'red')+metric('Geometric horizon',g.horizon?(g.horizon/(s.units==='imperial'?1609.344:1000)).toFixed(2)+(s.units==='imperial'?' mi':' km'):'No finite horizon')+metric('Straight target top angle',(g.angle*180/Math.PI).toFixed(4)+'°','green'); const angles=scene?.paths.map(r=>r.angle)||[Math.atan2(base.y-s.observer,base.x),g.angle],positions=angles.map(a=>90-pixelOffset(a,s.fov,180));$('view').innerHTML=`EYE LEVEL${positions.length?``:''}`; const extent=angles.length?(Math.max(...angles.map(a=>pixelOffset(a,s.fov,s.width)))-Math.min(...angles.map(a=>pixelOffset(a,s.fov,s.width)))).toFixed(1):'0';$('cameraNote').textContent=`${s.fov}° horizontal FOV · ${s.width}px image · sampled angular span ${extent}px. Angular framing only; displayed image paths may be outside the frame.`; $('status').textContent=scene?`${scene.paths.length?'Target reached by sampled rays':'No target path found in sampled angular range'} · illustrative scenario`:'Exact geometric model · straight light';$('limits').textContent=scene?`Ray results are sampled, not certified hidden-height predictions. Angular sampling ${(scene.resolution*180/Math.PI).toFixed(4)}°. Narrow branches can be missed. ${scene.converged?'Halved-step checks agree within 5 cm for checked paths.':'Convergence not established for this scenario.'} Boundary paths are refined within discovered continuous branches; narrow or undiscovered branches can still be missed. Readouts above remain geometric, without refraction.`:'Geometric readouts assume smooth surfaces and straight light. No terrain, waves, or atmospheric distortion. Camera settings change framing—not obstruction.';document.documentElement.dataset.ready='true';} sync();render();