@overglaze/web 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -41,7 +41,7 @@ never throws for the plugin: a fault shows in the box and in the diagnostics. Th
41
41
 
42
42
  It returns `pause()`, `resume()`, `fullscreen()`, `theme("light" | "dark")`, `compare(at)` (the
43
43
  before/after divider at a fraction of the box, or `null`), `stop()`, and two readings: `state`
44
- (`"loading"`, `"live"`, `"stopped"`) and `diagnostics`.
44
+ (`"loading"`, `"live"` from the plugin's first frame, `"stopped"`) and `diagnostics`.
45
45
 
46
46
  ## In a plugin folder
47
47
 
package/embed.js CHANGED
@@ -3,4 +3,4 @@
3
3
  * Required Notice: Copyright (c) 2026 Svetlozar Kostadinov
4
4
  * With an added permission to run it to develop and preview Overglaze plugins: see LICENSE in @overglaze/web
5
5
  */
6
- var B=Object.defineProperty;var n=(e,t)=>B(e,"name",{value:t,configurable:!0});import{Player as O}from"./player/player.js";import{ParamPanel as M}from"./player/panel.js";import{describe as N}from"./engine/descriptor.js";const R=new URL(".",import.meta.url).href,_="overglaze-embed",E="plugins",U=128,x=16,v=3e3,D={trace:"debug",debug:"debug",info:"info",log:"log",warn:"warn",error:"error"},C={unsupported:"This browser cannot run the plugin here",load:"The plugin failed to load",crash:"The plugin kept failing and was stopped",hang:"The plugin stopped responding and was stopped",lost:"The GPU device was lost",error:"The engine failed to start",cancelled:"The load was cancelled",missing:"There is no plugin here"},G={fallback:"A CPU adapter stands in for the GPU: the frames are right, their rate is not",features:"The GPU lacks what the cooked textures need, so they show as the fallback",slow:"The frame rate stays low here"},j={keys:n(()=>"The plugin listens for keys: they reach it here, and the Linux desktop delivers none","keys"),"import-meta":n(e=>e+" is read: here it is a data: URL, on the desktop the file's own","import-meta"),network:n(e=>e+" was loaded from the network: a module imported by URL, which the desktop refuses","network"),shader:n(e=>"The desktop's shader compiler refuses a shader, so it fails here too: "+e,"shader")},A=new WeakMap;let K=0;function y(e,t){const r=document.createElement(e);return t&&(r.className=t),r}n(y,"el");function W(){for(const e of["player/player.css","player/panel.css","embed.css"]){const t=new URL(e,R).href;if([...document.querySelectorAll("link[rel=stylesheet]")].some(o=>o.href===t))continue;const r=document.createElement("link");r.rel="stylesheet",r.href=t,document.head.append(r)}}n(W,"styles");function q(e){let t=String(e);for(;t.startsWith("./");)t=t.slice(2);return!t||t.startsWith("/")||t.includes("\\")||t.includes(":")?null:t.split("/").every(r=>r!==""&&r!=="."&&r!=="..")?t:null}n(q,"fileName");async function z(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e instanceof URL){const t=await fetch(e);if(!t.ok)throw new Error("HTTP "+t.status+" from "+e.href);return new Uint8Array(await t.arrayBuffer())}throw new Error("is neither text, bytes, a Blob nor a URL")}n(z,"fileBytes");async function H(e,t){const r=new Map;if(!e||typeof e!="object")return r;const o=e instanceof Map?[...e]:Object.entries(e);return await Promise.all(o.map(async([i,f])=>{const h=q(i);if(h===null){t("'"+i+"' is not a file name a plugin can hold, so it is left out");return}try{r.set(h,await z(f))}catch(u){t(h+" is left out: "+(u&&u.message?u.message:String(u)))}})),r}n(H,"gather");const V=n(()=>({read:n(()=>({local:null,params:null}),"read"),write(){}}),"memoryKeep");function S(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}n(S,"request");async function X(e){let t;try{const i=indexedDB.open(_,1);i.onupgradeneeded=()=>i.result.createObjectStore(E),t=await Promise.race([S(i),new Promise(f=>setTimeout(()=>f(null),v))])}catch{return null}if(!t)return null;const r=n(i=>t.transaction(E,i).objectStore(E),"store");let o;try{o=await S(r("readonly").get(e))||null}catch{return null}return{read:n(()=>({local:o&&o.local,params:o&&o.params}),"read"),write(i){try{i.local===null&&i.params===null?r("readwrite").delete(e):r("readwrite").put({local:i.local,params:i.params},e)}catch{}}}}n(X,"indexedKeep");class I{static{n(this,"Diagnostics")}constructor(t){this.root=t,this.lines=[],this.kinds=new Map,t.hidden=!0}add(t,r){if(this.lines.some(i=>i.text===r))return;const o=this.kinds.get(t)||{shown:0,over:0,overLine:null};if(this.kinds.set(t,o),o.shown>=x){o.over++;const i=o.over+" more like the line"+(x>1?"s":"")+" above, left out";o.overLine?(o.overLine.li.textContent=i,o.overLine.entry.text=i):o.overLine=this.#e(t,i);return}o.shown++,this.#e(t,r)}#e(t,r){const o={kind:t,text:r};this.lines.push(o);const i=y("li","og-diagnostic");return i.dataset.kind=t,i.textContent=r,this.root.append(i),this.root.hidden=!1,{li:i,entry:o}}}function Z(e,{files:t,entry:r,storage:o,panel:i=!1}={}){if(!(e instanceof Element))throw new TypeError("mount: the first argument must be an element");const f=A.get(e);f&&f.stop(),W(),e.classList.add("og-embed");const h=y("div","og-embed-box"),u=i?y("div","og-embed-panel"):null,b=y("ul","og-diagnostics");b.setAttribute("aria-live","polite"),e.replaceChildren(...[h,u,b].filter(Boolean));const c=new I(b);let p="loading",a=null,k=!1;const P={get state(){return p},get diagnostics(){return c.lines.map(l=>l.text)},pause:n(()=>a&&a.pause(),"pause"),resume:n(()=>a&&a.resume(),"resume"),fullscreen:n(()=>a&&a.fullscreen(),"fullscreen"),theme:n(l=>a&&a.setTheme(l),"theme"),compare:n(l=>a&&a.compare(l==null?null:Number(l)),"compare"),stop(){k=!0,p="stopped",a&&a.stop()}};A.set(e,P);const T=n(l=>{p="stopped",c.add("stopped",l)},"stopped");return(async()=>{const l=await H(t,s=>c.add("files",s)),w=N(l,{entry:r===void 0?void 0:String(r)});for(const s of w.notes)c.add("manifest",s);if(w.error){T("Nothing to run: "+w.error);return}const m=typeof o=="string"&&o&&o.length<=U?o:null;o!=null&&m===null&&c.add("storage","storage must be a name of 1 to "+U+" characters: nothing is kept");let L=V();if(m){const s=await X(m);s?L=s:c.add("storage","This page's origin keeps no storage, so the plugin's lasts as long as the page")}if(k)return;let g=null;u&&(g=new M(u,{write:n((s,d)=>a.session&&a.session.param(s,...d),"write"),reset:n(()=>a.session&&a.session.resetParams(),"reset")})),a=new O(h,{files:l,descriptor:w.descriptor,keep:L,folder:m||"embed-"+ ++K,desktops:new URL("desktops/",R).href,pictures:!1,desktop:"live",remember:m?"overglaze.desktop":null,persistParams:!0,on:{log:n((s,d)=>console[D[d]||"log"](s),"log"),stats:n(s=>{s.frames>0&&p==="loading"&&(p="live")},"stats"),held:n(()=>{p==="loading"&&(p="live")},"held"),desktop:n((s,d)=>{s!=="live"&&c.add("desktop","The live desktop failed, so a stand-in backdrop is shown in its place: "+d)},"desktop"),absent:n(s=>c.add("absent",s+" is not implemented by the web engine; the plugin touched it"),"absent"),gap:n((s,d)=>c.add(s,j[s](d)),"gap"),degraded:n((s,d)=>{s!=="unsupported"&&c.add("degraded",(G[s]||s)+(d?" ("+d+")":""))},"degraded"),stopped:n((s,d)=>{if(s==="stopped"){p="stopped";return}T((C[s]||"Stopped")+": "+d)},"stopped"),params:g?s=>g.model(s):void 0,paramValues:g?s=>g.values(s):void 0}}),!k&&await a.start()})().catch(l=>T("The engine failed to start: "+(l&&l.message?l.message:String(l)))),P}n(Z,"mount");export{Z as mount};
6
+ var B=Object.defineProperty;var n=(e,t)=>B(e,"name",{value:t,configurable:!0});import{Player as O}from"./player/player.js";import{ParamPanel as v}from"./player/panel.js";import{describe as M}from"./engine/descriptor.js";const R=new URL(".",import.meta.url).href,N="overglaze-embed",E="plugins",U=128,x=16,_=3e3,D={trace:"debug",debug:"debug",info:"info",log:"log",warn:"warn",error:"error"},C={unsupported:"This browser cannot run the plugin here",load:"The plugin failed to load",crash:"The plugin kept failing and was stopped",hang:"The plugin stopped responding and was stopped",lost:"The GPU device was lost",error:"The engine failed to start",cancelled:"The load was cancelled",missing:"There is no plugin here"},G={fallback:"A CPU adapter stands in for the GPU: the frames are right, their rate is not",features:"The GPU lacks what the cooked textures need, so they show as the fallback",slow:"The frame rate stays low here"},j={keys:n(()=>"The plugin listens for keys: they reach it here, and the Linux desktop delivers none","keys"),"import-meta":n(e=>e+" is read: here it is a data: URL, on the desktop the file's own","import-meta"),network:n(e=>e+" was loaded from the network: a module imported by URL, which the desktop refuses","network"),shader:n(e=>"The desktop's shader compiler refuses a shader, so it fails here too: "+e,"shader")},A=new WeakMap;let K=0;function y(e,t){const r=document.createElement(e);return t&&(r.className=t),r}n(y,"el");function W(){for(const e of["player/player.css","player/panel.css","embed.css"]){const t=new URL(e,R).href;if([...document.querySelectorAll("link[rel=stylesheet]")].some(o=>o.href===t))continue;const r=document.createElement("link");r.rel="stylesheet",r.href=t,document.head.append(r)}}n(W,"styles");function q(e){let t=String(e);for(;t.startsWith("./");)t=t.slice(2);return!t||t.startsWith("/")||t.includes("\\")||t.includes(":")?null:t.split("/").every(r=>r!==""&&r!=="."&&r!=="..")?t:null}n(q,"fileName");async function z(e){if(typeof e=="string")return new TextEncoder().encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e.slice(0));if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(e instanceof Blob)return new Uint8Array(await e.arrayBuffer());if(e instanceof URL){const t=await fetch(e);if(!t.ok)throw new Error("HTTP "+t.status+" from "+e.href);return new Uint8Array(await t.arrayBuffer())}throw new Error("is neither text, bytes, a Blob nor a URL")}n(z,"fileBytes");async function H(e,t){const r=new Map;if(!e||typeof e!="object")return r;const o=e instanceof Map?[...e]:Object.entries(e);return await Promise.all(o.map(async([i,f])=>{const h=q(i);if(h===null){t("'"+i+"' is not a file name a plugin can hold, so it is left out");return}try{r.set(h,await z(f))}catch(p){t(h+" is left out: "+(p&&p.message?p.message:String(p)))}})),r}n(H,"gather");const V=n(()=>({read:n(()=>({local:null,params:null}),"read"),write(){}}),"memoryKeep");function S(e){return new Promise((t,r)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>r(e.error)})}n(S,"request");async function X(e){let t;try{const i=indexedDB.open(N,1);i.onupgradeneeded=()=>i.result.createObjectStore(E),t=await Promise.race([S(i),new Promise(f=>setTimeout(()=>f(null),_))])}catch{return null}if(!t)return null;const r=n(i=>t.transaction(E,i).objectStore(E),"store");let o;try{o=await S(r("readonly").get(e))||null}catch{return null}return{read:n(()=>({local:o&&o.local,params:o&&o.params}),"read"),write(i){try{i.local===null&&i.params===null?r("readwrite").delete(e):r("readwrite").put({local:i.local,params:i.params},e)}catch{}}}}n(X,"indexedKeep");class I{static{n(this,"Diagnostics")}constructor(t){this.root=t,this.lines=[],this.kinds=new Map,t.hidden=!0}add(t,r){if(this.lines.some(i=>i.text===r))return;const o=this.kinds.get(t)||{shown:0,over:0,overLine:null};if(this.kinds.set(t,o),o.shown>=x){o.over++;const i=o.over+" more like the line"+(x>1?"s":"")+" above, left out";o.overLine?(o.overLine.li.textContent=i,o.overLine.entry.text=i):o.overLine=this.#e(t,i);return}o.shown++,this.#e(t,r)}#e(t,r){const o={kind:t,text:r};this.lines.push(o);const i=y("li","og-diagnostic");return i.dataset.kind=t,i.textContent=r,this.root.append(i),this.root.hidden=!1,{li:i,entry:o}}}function Z(e,{files:t,entry:r,storage:o,panel:i=!1}={}){if(!(e instanceof Element))throw new TypeError("mount: the first argument must be an element");const f=A.get(e);f&&f.stop(),W(),e.classList.add("og-embed");const h=y("div","og-embed-box"),p=i?y("div","og-embed-panel"):null,b=y("ul","og-diagnostics");b.setAttribute("aria-live","polite"),e.replaceChildren(...[h,p,b].filter(Boolean));const c=new I(b);let u="loading",a=null,k=!1;const P={get state(){return u},get diagnostics(){return c.lines.map(l=>l.text)},pause:n(()=>a&&a.pause(),"pause"),resume:n(()=>a&&a.resume(),"resume"),fullscreen:n(()=>a&&a.fullscreen(),"fullscreen"),theme:n(l=>a&&a.setTheme(l),"theme"),compare:n(l=>a&&a.compare(l==null?null:Number(l)),"compare"),stop(){k=!0,u="stopped",a&&a.stop()}};A.set(e,P);const T=n(l=>{u="stopped",c.add("stopped",l)},"stopped");return(async()=>{const l=await H(t,s=>c.add("files",s)),w=M(l,{entry:r===void 0?void 0:String(r)});for(const s of w.notes)c.add("manifest",s);if(w.error){T("Nothing to run: "+w.error);return}const m=typeof o=="string"&&o&&o.length<=U?o:null;o!=null&&m===null&&c.add("storage","storage must be a name of 1 to "+U+" characters: nothing is kept");let L=V();if(m){const s=await X(m);s?L=s:c.add("storage","This page's origin keeps no storage, so the plugin's lasts as long as the page")}if(k)return;let g=null;p&&(g=new v(p,{write:n((s,d)=>a.session&&a.session.param(s,...d),"write"),reset:n(()=>a.session&&a.session.resetParams(),"reset")})),a=new O(h,{files:l,descriptor:w.descriptor,keep:L,folder:m||"embed-"+ ++K,desktops:new URL("desktops/",R).href,pictures:!1,desktop:"live",remember:m?"overglaze.desktop":null,persistParams:!0,on:{log:n((s,d)=>console[D[d]||"log"](s),"log"),drawn:n(()=>{u==="loading"&&(u="live")},"drawn"),stats:n(s=>{s.frames>0&&u==="loading"&&(u="live")},"stats"),held:n(()=>{u==="loading"&&(u="live")},"held"),desktop:n((s,d)=>{s!=="live"&&c.add("desktop","The live desktop failed, so a stand-in backdrop is shown in its place: "+d)},"desktop"),absent:n(s=>c.add("absent",s+" is not implemented by the web engine; the plugin touched it"),"absent"),gap:n((s,d)=>c.add(s,j[s](d)),"gap"),degraded:n((s,d)=>{s!=="unsupported"&&c.add("degraded",(G[s]||s)+(d?" ("+d+")":""))},"degraded"),stopped:n((s,d)=>{if(s==="stopped"){u="stopped";return}T((C[s]||"Stopped")+": "+d)},"stopped"),params:g?s=>g.model(s):void 0,paramValues:g?s=>g.values(s):void 0}}),!k&&await a.start()})().catch(l=>T("The engine failed to start: "+(l&&l.message?l.message:String(l)))),P}n(Z,"mount");export{Z as mount};
package/engine/session.js CHANGED
@@ -6,4 +6,4 @@
6
6
  var R=Object.defineProperty;var c=(s,e)=>R(s,"name",{value:e,configurable:!0});import{StorageArea as m}from"./plugin-storage.js";import{MAX_FIELD_COMPONENTS as P,MAX_FIELDS as g,ParamStore as S}from"./param-store.js";import{keyEdge as j}from"./keys.js";import{cursorShape as b}from"./cursor.js";const A=250,D=2e3,u=50,E=25,F=100,H=5e3,W=1e3,U=1e3,w=8*1024,h=256,X=1024,K=32,G=256,V=new Set(["checkbox","combo","color","slider","drag"]),J=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End"]),Y=new Set(["trace","debug","info","log","warn","error"]),q={trace:"[T]",debug:"[D]",warn:"[W]",error:"[E]"},Q=new Set(["boot","evaluating","initializing","running","failed"]),$=new Set(["keys","import-meta","network","shader"]),Z=2048,ee=256,o=c((s,e)=>{const t=String(s);return t.length>e?t.slice(0,e)+" [... "+(t.length-e)+" more]":t},"text"),d=c(s=>typeof s=="number"&&isFinite(s)?s:0,"num"),te=new TextEncoder,se=new TextDecoder,ie=c((s,e)=>{const t=String(s);if(t.length*3<=e)return t;const i=te.encode(t);if(i.length<=e)return t;let r=e;for(;(i[r]&192)===128;)r--;return se.decode(i.subarray(0,r))+"... ["+(i.length-r)+" more bytes truncated]"},"clipMessage");let y={folder:null,area:null};function M(s){try{const e=localStorage.getItem(s);return e?JSON.parse(e):null}catch{return null}}c(M,"readJson");function re(s){const e={local:"overglaze.storage."+s,params:"overglaze.params."+s};return{read:c(()=>({local:M(e.local),params:M(e.params)}),"read"),write(t){try{for(const i of["local","params"])t[i]!==void 0&&(t[i]===null?localStorage.removeItem(e[i]):localStorage.setItem(e[i],JSON.stringify(t[i])))}catch{}}}}c(re,"localKeep");const k=c(s=>typeof s=="number"&&isFinite(s),"finite");function v(s,e){return!Array.isArray(s)||s.length!==e?null:s.map(t=>typeof t=="number"?t:NaN)}c(v,"numbers");function ae(s){if(!s||typeof s!="object"||typeof s.key!="string")return null;const e=s.comps;if(!Number.isInteger(e)||e<1||e>P)return null;const t=v(s.value,e),i=v(s.def,e);if(!t||!i)return null;const r={key:o(s.key,h),label:o(s.label,h),comps:e,int:s.int===!0,unsigned:s.unsigned===!0,bool:s.bool===!0,widget:V.has(s.widget)?s.widget:"drag",step:k(s.step)&&s.step>0?s.step:s.int===!0?1:.01,min:k(s.min)?s.min:void 0,max:k(s.max)?s.max:void 0,choices:Array.isArray(s.choices)?s.choices.slice(0,G).map(a=>o(a,h)):void 0,tooltip:s.tooltip===void 0?void 0:o(s.tooltip,X),hint:Array.isArray(s.hint)?s.hint.slice(0,K).map(a=>o(a,h)):void 0,group:s.group===void 0?void 0:o(s.group,h),def:i,value:t},n=r.widget;return(n==="combo"&&(e!==1||!r.choices||!r.choices.length)||n==="color"&&e<3||n==="checkbox"&&e!==1||n==="slider"&&(r.min===void 0||r.max===void 0))&&(r.widget="drag"),r}c(ae,"paramRow");function ne(s){const e=Array.isArray(s.rows)?s.rows.slice(0,g).map(ae).filter(Boolean):[];return{resettable:s.resettable===!0,rows:e}}c(ne,"paramModel");function oe(s){if(!Array.isArray(s))return[];const e=[];for(const t of s.slice(0,g)){if(!Array.isArray(t)||typeof t[0]!="string"||!Array.isArray(t[1]))continue;const i=Math.min(t[1].length,P);i<1||e.push([o(t[0],h),v(t[1].slice(0,i),i)])}return e}c(oe,"paramValues");const he=.02;function ce(){const s=new URL("worker.js",import.meta.url);return s.origin===self.origin?new Worker(s,{type:"module"}):new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(le(s.href)))}c(ce,"startWorker");function le(s){return['"use strict";',"const on = addEventListener.bind(self), off = removeEventListener.bind(self);","const fire = dispatchEvent.bind(self), Message = MessageEvent, later = setTimeout;","const held = [];","const hold = (e) => { held.push(e); e.stopImmediatePropagation(); };",'on("message", hold);',"import("+JSON.stringify(s)+").then(() => {",' off("message", hold);',' for (const e of held) fire(new Message("message", { data: e.data, ports: e.ports }));',"}, (err) => {",' off("message", hold);'," later(() => { throw err; });","});",""].join(`
7
7
  `)}c(le,"importer");async function f(s,e){const t={colorSpaceConversion:"none",premultiplyAlpha:"none"},i=await createImageBitmap(s,t);return i.width===e[0]&&i.height===e[1]?i:(i.close(),createImageBitmap(s,{...t,resizeWidth:e[0],resizeHeight:e[1],resizeQuality:"high"}))}c(f,"sceneBitmap");class me{static{c(this,"Session")}constructor({box:e,plugin:t,modules:i,files:r=null,descriptor:n=null,folder:a,keep:l=null,picture:x,scene:_,params:C,persistParams:T=!1,watchdog:I=!0,clock:L="wall",refreshHz:z=60,pointer:N=null,hold:B=!1,on:O}){this.box=e,this.pointerAt=N,this.hold=B,this.mode="opaque",this.resizer=null,this.cursorScale=0,this.watchdog=I,this.clock=L==="stepped"?"stepped":"wall",this.refreshHz=z,this.steps=new Map,this.stepId=0,this.plugin=t,this.modules=i,this.files=r instanceof Map?r:null,this.descriptor=n,this.folder=a,this.keep=l||re(a),this.picture=x,this.scene=_,this.persistParams=T===!0,this.local=new m(null),this.paramStore=new S(this.persistParams?null:C);const p=this.keep.read();p&&typeof p.then=="function"?this.saved=p:this.#o(p),this.on=O||{},this.package="",this.displayName="",this.gpuFeatures=[],this.worker=null,this.canvas=null,this.phase="boot",this.paused=!1,this.splitAt=null,this.stoppedWith=null,this.beating=!1,this.lastBeat=0,this.lastCheck=0,this.inPlugin=!1,this.pluginSince=0,this.armed=!1,this.timer=0,this.flushTimer=0,this.probes=new Map,this.probeId=0,this.pictureSent=0,this.pictureTaken=0,this.pictureWaiters=[],this.claim=[],y.folder!==a&&(y={folder:a,area:new m(null)}),this.session=y.area,this.onVisibility=()=>this.#c(),this.onPageHide=()=>this.#r()}#o(e){const t=e&&typeof e=="object"?e:{};this.local=new m(t.local&&typeof t.local=="object"?t.local:null),this.persistParams&&(this.paramStore=new S(t.params&&typeof t.params=="object"?t.params:null))}async start(){if(this.saved){let a=null;try{a=await this.saved}catch{}this.saved=null,this.#o(a)}let e=this.descriptor;if(!this.files){const a=await fetch(this.plugin+"overglaze-web.json");if(!a.ok){this.displayName=this.folder,this.#i(),this.#a("missing","there is no plugin '"+this.folder+"' here");return}e=await a.json()}if(this.package=o(e.package||"",h),this.displayName=o(e.displayName||this.package,h),this.gpuFeatures=Array.isArray(e.gpuFeatures)?e.gpuFeatures.slice(0,16).map(a=>o(a,h)):[],!("gpu"in navigator)){this.#i(),this.#a("unsupported","this browser has no WebGPU");return}this.canvas=this.#u(),this.#v(this.canvas);const t=await f(this.picture,this.scene);this.cursorScale=this.#n(this.scene);const i=await b(this.cursorScale),r=this.#b();this.resizer=new ResizeObserver(a=>this.#w(a[a.length-1]));try{this.resizer.observe(this.canvas,{box:"device-pixel-content-box"})}catch{this.resizer.observe(this.canvas)}const n=this.canvas.transferControlToOffscreen();this.worker=ce(),this.worker.onmessage=a=>this.#d(a.data),this.worker.onerror=a=>{a.preventDefault(),this.#s("error","the engine failed to start: "+o(a.message,h))},this.worker.postMessage({type:"start",canvas:n,picture:t,plugin:this.plugin,modules:this.modules,files:this.files?[...this.files]:void 0,descriptor:this.files?e:void 0,scene:this.scene,output:r,cursor:i.bitmap,hot:i.hot,pointer:this.pointerAt,hold:this.hold,beat:u,clock:this.clock,refreshHz:this.refreshHz,params:this.paramStore.toObject(),watchParams:typeof this.on.params=="function",storage:{local:this.local.toObject(),session:this.session.toObject()}},[n,t,i.bitmap]),document.addEventListener("visibilitychange",this.onVisibility),addEventListener("pagehide",this.onPageHide),this.timer=setInterval(()=>this.#m(),E),this.splitAt!==null&&this.#e({type:"split",at:this.splitAt}),this.paused?this.#e({type:"pause"}):document.hidden&&this.#c()}pause(){this.paused=!0,this.#e({type:"pause"}),this.armed=!1}resume(){this.paused=!1,document.hidden||this.#l()}async resize(e,t){if(this.scene=e,t&&(this.picture=t),!this.worker){this.stoppedWith&&this.#i();return}const i=await f(this.picture,e);this.cursorScale=this.#n(e);const r=await b(this.cursorScale);this.#e({type:"resize",scene:e,picture:i,cursor:r.bitmap,hot:r.hot},[i,r.bitmap])}split(e){this.splitAt=e===null?null:Number(e),this.#e({type:"split",at:this.splitAt})}async setPicture(e){if(this.picture=e,!this.worker){this.stoppedWith&&this.#i();return}const t=await f(e,this.scene);if(!this.worker){t.close();return}this.#e({type:"desktop",picture:t,id:++this.pictureSent},[t])}pictureIn(){if(!this.worker||this.pictureTaken>=this.pictureSent)return Promise.resolve();const e=this.pictureSent;return new Promise(t=>this.pictureWaiters.push({want:e,resolve:t}))}cancel(){this.worker&&(this.#e({type:"cancel"}),setTimeout(()=>this.#s("cancelled","the load was cancelled"),W))}stop(){this.#s("stopped","stopped")}storage(){return{local:this.local.toObject(),session:this.session.toObject()}}savedParams(){return this.paramStore.toObject()}param(e,...t){this.#e({type:"param",key:String(e),values:t.map(Number)})}resetParams(){this.#e({type:"param-reset"})}probe(){const e=++this.probeId;return new Promise(t=>{this.probes.set(e,t),this.#e({type:"probe",id:e})})}destroyDevice(){this.#e({type:"destroy-device"})}step(e,t=!1){if(this.clock!=="stepped"||!this.worker)return Promise.resolve(null);const i=++this.stepId;return new Promise(r=>{this.steps.set(i,r),this.#e({type:"step",id:i,t:Number(e),capture:!!t})})}runOn(e){this.clock!=="stepped"||!this.worker||(this.clock="wall",this.#e({type:"run",t:Number(e)}))}pointer(e,t){this.#e({type:"pointer",kind:"move",x:Number(e),y:Number(t),button:0,buttons:0,notches:0,t:0})}#d(e){if(!(!e||typeof e!="object"||!this.worker))switch(e.type){case"beat":{const t=performance.now();this.beating?this.armed&&t-this.lastBeat>2*u&&this.#t("log","[page] no heartbeat for "+Math.round(t-this.lastBeat)+" ms (at "+(t/1e3).toFixed(1)+" s)","info"):(this.beating=!0,this.armed=!this.paused&&!document.hidden),this.lastBeat=t;break}case"plugin":{const t=performance.now();e.running===!0?(this.inPlugin=!0,this.pluginSince=t):this.inPlugin&&(this.inPlugin=!1,this.armed&&t-this.pluginSince>2*u&&this.#t("log","[page] the plugin's frame took "+Math.round(t-this.pluginSince)+" ms (at "+(t/1e3).toFixed(1)+" s)","info"),this.lastBeat=t);break}case"phase":Q.has(e.phase)&&(this.phase=e.phase,this.#t("phase",e.phase));break;case"log":{const t=Y.has(e.level)?e.level:"info",i=(e.source==="engine"?"[engine ":"[js ")+this.package+"] ",r=q[t]||"[I]",n=ie(e.text,w).split(`
8
8
  `).map(a=>r+" "+i+a.replace(/\r$/,""));this.#t("log",n.join(`
9
- `),t);break}case"fault":this.#t("fault",o(e.where,h),o(e.message,w));break;case"absent-op":this.#t("absent",o(e.name,h));break;case"progress":this.#t("progress",d(e.fraction),o(e.label,h));break;case"storage":this.#f(e);break;case"params":this.#g(e);break;case"params-model":this.#t("params",ne(e));break;case"param-values":this.#t("paramValues",oe(e.values));break;case"ready":this.#t("ready",{adapter:o(e.adapter||"",h),fallback:e.fallback===!0,features:Array.isArray(e.features)?e.features.slice(0,64).map(t=>o(t,h)):[],canvasFormat:o(e.canvasFormat||"",h)});break;case"stats":this.#t("stats",{fps:d(e.fps),frames:d(e.frames),faults:d(e.faults),mode:o(e.mode,16)});break;case"mode":{const t=e.mode==="warp"||e.mode==="transparent"?e.mode:"opaque";if(t===this.mode)break;this.mode=t,this.canvas&&(this.canvas.style.cursor=t==="warp"?"none":""),this.#t("mode",t);break}case"held":if(this.paused)break;this.paused=!0,this.armed=!1,this.#t("held");break;case"globals":this.#t("globals",{stuck:Array.isArray(e.stuck)?e.stuck.slice(0,256).map(t=>o(t,h)):[],inherited:Array.isArray(e.inherited)?e.inherited.slice(0,256).map(t=>o(t,h)):[]});break;case"gap":$.has(e.kind)&&this.#t("gap",e.kind,o(e.detail===void 0?"":e.detail,Z));break;case"unsupported":this.#s("unsupported",o(e.message,h));break;case"disabled":this.#s(e.kind==="crash"?"crash":"load",o(e.message,w));break;case"lost":this.#s("lost","the GPU device was lost ("+o(e.reason,h)+"): "+o(e.message,h));break;case"claim":this.claim=Array.isArray(e.rects)?e.rects.slice(0,ee*4).map(Number).filter(t=>Number.isFinite(t)):[],this.claim.length%4&&(this.claim.length-=this.claim.length%4);break;case"desktop-in":Number.isInteger(e.id)&&e.id>this.pictureTaken&&e.id<=this.pictureSent&&(this.pictureTaken=e.id,this.#p());break;case"probe":{const t=this.probes.get(e.id);this.probes.delete(e.id),t&&t(e.result);break}case"stepped":{const t=this.steps.get(e.id);if(this.steps.delete(e.id),!t)break;const i=this.scene[0]*this.scene[1]*4;t(e.pixels instanceof ArrayBuffer&&e.pixels.byteLength===i?e.pixels:null);break}}}#f(e){const t=e.area==="local"?this.local:e.area==="session"?this.session:null;if(t){if(e.op==="set")t.set(String(e.key),String(e.value));else if(e.op==="remove")t.remove(String(e.key));else if(e.op==="clear")t.clear();else return;t===this.local&&this.#h()}}#g(e){if(e.op==="write"&&Array.isArray(e.entries))for(const t of e.entries.slice(0,g))Array.isArray(t)&&this.paramStore.set(String(t[0]),t[1]);else if(e.op==="forget")this.paramStore.forget(String(e.key));else if(e.op==="prune"&&Array.isArray(e.live))this.paramStore.prune(e.live.slice(0,g));else return;this.persistParams&&this.#h()}#h(){this.flushTimer||(this.flushTimer=setTimeout(()=>this.#r(),U))}#r(){clearTimeout(this.flushTimer),this.flushTimer=0,this.keep.write({local:this.local.length?this.local.toObject():null,params:this.persistParams?this.paramStore.size?this.paramStore.toObject():null:void 0})}#m(){const e=performance.now(),t=e-this.lastCheck,i=this.lastCheck&&t>E+F;if(this.lastCheck=e,!this.armed||!this.worker)return;if(i){this.#t("log","[page] the page itself was busy for "+Math.round(t)+" ms (at "+(e/1e3).toFixed(1)+" s)","info"),this.lastBeat=e,this.inPlugin&&(this.pluginSince=e);return}if(!this.watchdog)return;if(this.phase==="running"&&this.inPlugin){const l=e-this.pluginSince;l>A&&this.#s("hang","the plugin's frame ran "+Math.round(l)+" ms (budget "+A+" ms) and was stopped");return}const r=this.phase!=="running",n=(r?D:H)+u,a=e-this.lastBeat;a>n&&this.#s("hang",(r?"the plugin stopped responding during its load":"the engine stopped responding outside the plugin's frame")+" ("+Math.round(a)+" ms without a heartbeat, budget "+n+" ms) and was stopped")}#c(){document.hidden?(this.#e({type:"pause"}),this.armed=!1):this.paused||this.#l()}#l(){this.#e({type:"resume"}),this.lastBeat=performance.now(),this.armed=this.beating&&this.worker!==null}#s(e,t){if(this.worker){this.worker.terminate(),this.worker=null,this.armed=!1,this.resizer&&this.resizer.disconnect(),this.resizer=null;for(const i of this.steps.values())i(null);this.steps.clear(),this.pictureTaken=this.pictureSent,this.#p(),this.claim=[],clearInterval(this.timer),document.removeEventListener("visibilitychange",this.onVisibility),removeEventListener("pagehide",this.onPageHide),this.#r(),this.#i(),this.#a(e,t)}}claims(e,t){const i=this.claim;for(let r=0;r<i.length;r+=4)if(e>=i[r]&&e<i[r]+i[r+2]&&t>=i[r+1]&&t<i[r+1]+i[r+3])return!0;return!1}#p(){const e=this.pictureWaiters;this.pictureWaiters=e.filter(t=>t.want>this.pictureTaken);for(const t of e)t.want<=this.pictureTaken&&t.resolve()}#a(e,t){this.stoppedWith={reason:e,message:t},this.#t("stopped",e,t)}async#i(){const e=this.#u();try{const t=await f(this.picture,this.scene);e.getContext("2d").drawImage(t,0,0),t.close()}catch{}}#u(){const e=document.createElement("canvas");return e.width=this.scene[0],e.height=this.scene[1],e.tabIndex=0,this.box.replaceChildren(e),e}#b(){const e=this.canvas.getBoundingClientRect(),t=devicePixelRatio||1;return[Math.max(1,Math.round(e.width*t)),Math.max(1,Math.round(e.height*t))]}#w(e){if(!this.worker||!e)return;const t=e.devicePixelContentBoxSize&&e.devicePixelContentBoxSize[0];let i;if(t)i=[t.inlineSize,t.blockSize];else{const r=devicePixelRatio||1;i=[Math.round(e.contentRect.width*r),Math.round(e.contentRect.height*r)]}i[0]<1||i[1]<1||(this.#e({type:"output",size:i}),this.#y())}#n(e){const t=this.canvas?this.canvas.getBoundingClientRect().width:0;return t>0?e[0]/t:1}async#y(){const e=this.#n(this.scene);if(Math.abs(e-this.cursorScale)<=he*e)return;this.cursorScale=e;const t=await b(e);if(e!==this.cursorScale){t.bitmap.close();return}this.#e({type:"cursor",cursor:t.bitmap,hot:t.hot},[t.bitmap])}#k(){const e=document.fullscreenElement;return document.activeElement===this.canvas||!!(e&&e.contains(this.canvas))}#e(e,t){this.worker&&this.worker.postMessage(e,t||[])}#t(e,...t){const i=this.on[e];i&&i(...t)}#v(e){const t=c((r,n)=>Math.min(n,Math.max(0,r)),"clamp"),i=c((r,n,a)=>{const l=e.getBoundingClientRect();this.#e({type:"pointer",kind:r,x:t((n.clientX-l.left)/l.width*this.scene[0],this.scene[0]),y:t((n.clientY-l.top)/l.height*this.scene[1],this.scene[1]),button:n.button,buttons:n.buttons,ctrl:n.ctrlKey,shift:n.shiftKey,alt:n.altKey,meta:n.metaKey,t:n.timeStamp,notches:0,...a})},"send");e.addEventListener("pointermove",r=>i("move",r)),e.addEventListener("pointerdown",r=>{e.focus({preventScroll:!0});try{e.setPointerCapture(r.pointerId)}catch{}i("down",r)}),e.addEventListener("pointerup",r=>i("up",r)),e.addEventListener("pointerenter",()=>this.#e({type:"hover",over:!0})),e.addEventListener("pointerleave",()=>this.#e({type:"hover",over:!1})),e.addEventListener("wheel",r=>{if(!this.#k())return;r.preventDefault();const n=r.deltaMode===1?1/3:r.deltaMode===2?1:1/100;i("wheel",r,{notches:-r.deltaY*n})},{passive:!1});for(const r of["keydown","keyup"])e.addEventListener(r,n=>{const a=j(n);a&&(J.has(n.code)&&n.preventDefault(),this.#e({type:"key",key:a}))})}}export{me as Session,re as localKeep};
9
+ `),t);break}case"fault":this.#t("fault",o(e.where,h),o(e.message,w));break;case"absent-op":this.#t("absent",o(e.name,h));break;case"progress":this.#t("progress",d(e.fraction),o(e.label,h));break;case"storage":this.#f(e);break;case"params":this.#g(e);break;case"params-model":this.#t("params",ne(e));break;case"param-values":this.#t("paramValues",oe(e.values));break;case"ready":this.#t("ready",{adapter:o(e.adapter||"",h),fallback:e.fallback===!0,features:Array.isArray(e.features)?e.features.slice(0,64).map(t=>o(t,h)):[],canvasFormat:o(e.canvasFormat||"",h)});break;case"drawn":this.#t("drawn");break;case"stats":this.#t("stats",{fps:d(e.fps),frames:d(e.frames),faults:d(e.faults),mode:o(e.mode,16)});break;case"mode":{const t=e.mode==="warp"||e.mode==="transparent"?e.mode:"opaque";if(t===this.mode)break;this.mode=t,this.canvas&&(this.canvas.style.cursor=t==="warp"?"none":""),this.#t("mode",t);break}case"held":if(this.paused)break;this.paused=!0,this.armed=!1,this.#t("held");break;case"globals":this.#t("globals",{stuck:Array.isArray(e.stuck)?e.stuck.slice(0,256).map(t=>o(t,h)):[],inherited:Array.isArray(e.inherited)?e.inherited.slice(0,256).map(t=>o(t,h)):[]});break;case"gap":$.has(e.kind)&&this.#t("gap",e.kind,o(e.detail===void 0?"":e.detail,Z));break;case"unsupported":this.#s("unsupported",o(e.message,h));break;case"disabled":this.#s(e.kind==="crash"?"crash":"load",o(e.message,w));break;case"lost":this.#s("lost","the GPU device was lost ("+o(e.reason,h)+"): "+o(e.message,h));break;case"claim":this.claim=Array.isArray(e.rects)?e.rects.slice(0,ee*4).map(Number).filter(t=>Number.isFinite(t)):[],this.claim.length%4&&(this.claim.length-=this.claim.length%4);break;case"desktop-in":Number.isInteger(e.id)&&e.id>this.pictureTaken&&e.id<=this.pictureSent&&(this.pictureTaken=e.id,this.#p());break;case"probe":{const t=this.probes.get(e.id);this.probes.delete(e.id),t&&t(e.result);break}case"stepped":{const t=this.steps.get(e.id);if(this.steps.delete(e.id),!t)break;const i=this.scene[0]*this.scene[1]*4;t(e.pixels instanceof ArrayBuffer&&e.pixels.byteLength===i?e.pixels:null);break}}}#f(e){const t=e.area==="local"?this.local:e.area==="session"?this.session:null;if(t){if(e.op==="set")t.set(String(e.key),String(e.value));else if(e.op==="remove")t.remove(String(e.key));else if(e.op==="clear")t.clear();else return;t===this.local&&this.#h()}}#g(e){if(e.op==="write"&&Array.isArray(e.entries))for(const t of e.entries.slice(0,g))Array.isArray(t)&&this.paramStore.set(String(t[0]),t[1]);else if(e.op==="forget")this.paramStore.forget(String(e.key));else if(e.op==="prune"&&Array.isArray(e.live))this.paramStore.prune(e.live.slice(0,g));else return;this.persistParams&&this.#h()}#h(){this.flushTimer||(this.flushTimer=setTimeout(()=>this.#r(),U))}#r(){clearTimeout(this.flushTimer),this.flushTimer=0,this.keep.write({local:this.local.length?this.local.toObject():null,params:this.persistParams?this.paramStore.size?this.paramStore.toObject():null:void 0})}#m(){const e=performance.now(),t=e-this.lastCheck,i=this.lastCheck&&t>E+F;if(this.lastCheck=e,!this.armed||!this.worker)return;if(i){this.#t("log","[page] the page itself was busy for "+Math.round(t)+" ms (at "+(e/1e3).toFixed(1)+" s)","info"),this.lastBeat=e,this.inPlugin&&(this.pluginSince=e);return}if(!this.watchdog)return;if(this.phase==="running"&&this.inPlugin){const l=e-this.pluginSince;l>A&&this.#s("hang","the plugin's frame ran "+Math.round(l)+" ms (budget "+A+" ms) and was stopped");return}const r=this.phase!=="running",n=(r?D:H)+u,a=e-this.lastBeat;a>n&&this.#s("hang",(r?"the plugin stopped responding during its load":"the engine stopped responding outside the plugin's frame")+" ("+Math.round(a)+" ms without a heartbeat, budget "+n+" ms) and was stopped")}#c(){document.hidden?(this.#e({type:"pause"}),this.armed=!1):this.paused||this.#l()}#l(){this.#e({type:"resume"}),this.lastBeat=performance.now(),this.armed=this.beating&&this.worker!==null}#s(e,t){if(this.worker){this.worker.terminate(),this.worker=null,this.armed=!1,this.resizer&&this.resizer.disconnect(),this.resizer=null;for(const i of this.steps.values())i(null);this.steps.clear(),this.pictureTaken=this.pictureSent,this.#p(),this.claim=[],clearInterval(this.timer),document.removeEventListener("visibilitychange",this.onVisibility),removeEventListener("pagehide",this.onPageHide),this.#r(),this.#i(),this.#a(e,t)}}claims(e,t){const i=this.claim;for(let r=0;r<i.length;r+=4)if(e>=i[r]&&e<i[r]+i[r+2]&&t>=i[r+1]&&t<i[r+1]+i[r+3])return!0;return!1}#p(){const e=this.pictureWaiters;this.pictureWaiters=e.filter(t=>t.want>this.pictureTaken);for(const t of e)t.want<=this.pictureTaken&&t.resolve()}#a(e,t){this.stoppedWith={reason:e,message:t},this.#t("stopped",e,t)}async#i(){const e=this.#u();try{const t=await f(this.picture,this.scene);e.getContext("2d").drawImage(t,0,0),t.close()}catch{}}#u(){const e=document.createElement("canvas");return e.width=this.scene[0],e.height=this.scene[1],e.tabIndex=0,this.box.replaceChildren(e),e}#b(){const e=this.canvas.getBoundingClientRect(),t=devicePixelRatio||1;return[Math.max(1,Math.round(e.width*t)),Math.max(1,Math.round(e.height*t))]}#w(e){if(!this.worker||!e)return;const t=e.devicePixelContentBoxSize&&e.devicePixelContentBoxSize[0];let i;if(t)i=[t.inlineSize,t.blockSize];else{const r=devicePixelRatio||1;i=[Math.round(e.contentRect.width*r),Math.round(e.contentRect.height*r)]}i[0]<1||i[1]<1||(this.#e({type:"output",size:i}),this.#y())}#n(e){const t=this.canvas?this.canvas.getBoundingClientRect().width:0;return t>0?e[0]/t:1}async#y(){const e=this.#n(this.scene);if(Math.abs(e-this.cursorScale)<=he*e)return;this.cursorScale=e;const t=await b(e);if(e!==this.cursorScale){t.bitmap.close();return}this.#e({type:"cursor",cursor:t.bitmap,hot:t.hot},[t.bitmap])}#k(){const e=document.fullscreenElement;return document.activeElement===this.canvas||!!(e&&e.contains(this.canvas))}#e(e,t){this.worker&&this.worker.postMessage(e,t||[])}#t(e,...t){const i=this.on[e];i&&i(...t)}#v(e){const t=c((r,n)=>Math.min(n,Math.max(0,r)),"clamp"),i=c((r,n,a)=>{const l=e.getBoundingClientRect();this.#e({type:"pointer",kind:r,x:t((n.clientX-l.left)/l.width*this.scene[0],this.scene[0]),y:t((n.clientY-l.top)/l.height*this.scene[1],this.scene[1]),button:n.button,buttons:n.buttons,ctrl:n.ctrlKey,shift:n.shiftKey,alt:n.altKey,meta:n.metaKey,t:n.timeStamp,notches:0,...a})},"send");e.addEventListener("pointermove",r=>i("move",r)),e.addEventListener("pointerdown",r=>{e.focus({preventScroll:!0});try{e.setPointerCapture(r.pointerId)}catch{}i("down",r)}),e.addEventListener("pointerup",r=>i("up",r)),e.addEventListener("pointerenter",()=>this.#e({type:"hover",over:!0})),e.addEventListener("pointerleave",()=>this.#e({type:"hover",over:!1})),e.addEventListener("wheel",r=>{if(!this.#k())return;r.preventDefault();const n=r.deltaMode===1?1/3:r.deltaMode===2?1:1/100;i("wheel",r,{notches:-r.deltaY*n})},{passive:!1});for(const r of["keydown","keyup"])e.addEventListener(r,n=>{const a=j(n);a&&(J.has(n.code)&&n.preventDefault(),this.#e({type:"key",key:a}))})}}export{me as Session,re as localKeep};
package/engine/worker.js CHANGED
@@ -3,15 +3,15 @@
3
3
  * Required Notice: Copyright (c) 2026 Svetlozar Kostadinov
4
4
  * With an added permission to run it to develop and preview Overglaze plugins: see LICENSE in @overglaze/web
5
5
  */
6
- var Xe=Object.defineProperty;var i=(e,t)=>Xe(e,"name",{value:t,configurable:!0});import{attachOps as Je,natives as s}from"./core.js";import{ABSENT as Qe,createOps as Ke}from"./ops.js";import{domInputFrame as Ze,PointerTracker as $e,uniformValues as et}from"./uniforms.js";import{CookedTextures as tt}from"./tex.js";import{PluginFiles as rt}from"./files.js";import{dataUrl as nt,moduleGraph as it,PluginJs as at}from"./modules.js";import{checkShaders as ot,headline as st,Naga as lt}from"./shaders.js";import{StorageMirror as ut}from"./plugin-storage.js";import{ParamStore as ze}from"./param-store.js";import{contractWarning as ct}from"./descriptor.js";import{denyReadback as ft,pruneGlobals as pt,removeShadowed as dt}from"./globals.js";import{GOLDEN_GLOBALS as gt}from"./golden-globals.js";const u=s.postMessage,A=s.console,b=s.GPUTextureUsage,S=s.performanceNow,we=3e4,mt=1e3,n={capabilities:new Set,sceneSize:[1920,1080],sceneTex:null,desktopTex:null,published:!1,inputFrame:null,uniformValues:[],mode:"opaque",interactiveRects:[],inFrame:!1,params:new ze(null),auto:[],storage:null,files:null,textures:null,log(e,t){(A[e]||A.log).call(A,t),u({type:"log",level:e,text:t,source:"js"})},fault(e,t){_.report(e,t)},progress(e,t){m==="initializing"&&(Q=S(),u({type:"progress",fraction:e,label:t}))},paramsChanged(e){u({type:"params",...e})}};function d(e,t){(A[e]||A.log).call(A,t),u({type:"log",level:e,text:t,source:"engine"})}i(d,"engineLog");function T(e){return String(e)+(e&&e.stack?`
6
+ var Qe=Object.defineProperty;var i=(e,t)=>Qe(e,"name",{value:t,configurable:!0});import{attachOps as Ke,natives as s}from"./core.js";import{ABSENT as Ze,createOps as $e}from"./ops.js";import{domInputFrame as et,PointerTracker as tt,uniformValues as rt}from"./uniforms.js";import{CookedTextures as nt}from"./tex.js";import{PluginFiles as it}from"./files.js";import{dataUrl as at,moduleGraph as ot,PluginJs as st}from"./modules.js";import{checkShaders as lt,headline as ut,Naga as ct}from"./shaders.js";import{StorageMirror as ft}from"./plugin-storage.js";import{ParamStore as Ee}from"./param-store.js";import{contractWarning as pt}from"./descriptor.js";import{denyReadback as dt,pruneGlobals as gt,removeShadowed as mt}from"./globals.js";import{GOLDEN_GLOBALS as ht}from"./golden-globals.js";const u=s.postMessage,A=s.console,b=s.GPUTextureUsage,S=s.performanceNow,we=3e4,bt=1e3,n={capabilities:new Set,sceneSize:[1920,1080],sceneTex:null,desktopTex:null,published:!1,inputFrame:null,uniformValues:[],mode:"opaque",interactiveRects:[],inFrame:!1,params:new Ee(null),auto:[],storage:null,files:null,textures:null,log(e,t){(A[e]||A.log).call(A,t),u({type:"log",level:e,text:t,source:"js"})},fault(e,t){_.report(e,t)},progress(e,t){m==="initializing"&&(Q=S(),u({type:"progress",fraction:e,label:t}))},paramsChanged(e){u({type:"params",...e})}};function d(e,t){(A[e]||A.log).call(A,t),u({type:"log",level:e,text:t,source:"engine"})}i(d,"engineLog");function T(e){return String(e)+(e&&e.stack?`
7
7
  `+e.stack:"")}i(T,"errorText");const _={logged:!1,short:"",errorThisFrame:!1,streakStart:null,latched:null,count:0,report(e,t){this.count++,this.logged||(this.logged=!0,this.short=t.split(`
8
8
  `)[0],d("error","[script] plugin fault ("+e+"): "+t),u({type:"fault",where:e,message:t})),this.errorThisFrame=!0},loadFailure(e,t){this.count++,this.short||(this.short=t.split(`
9
- `)[0]),d("error","[script] plugin load failed ("+e+"): "+t),u({type:"fault",where:e,message:t}),this.latched||(this.latched={kind:"load",message:this.short})},boundary(e){this.errorThisFrame?this.streakStart===null?this.streakStart=e:!this.latched&&e-this.streakStart>=mt&&(this.latched={kind:"crash",message:this.short}):this.streakStart=null,this.errorThisFrame=!1}};Je(Ke(n),e=>{A.warn("[web] unimplemented op touched: "+e),u({type:"absent-op",name:e})});function Ee(e){m==="evaluating"?w("plugin evaluation",e):m==="initializing"?w("plugin init",e):_.report("event loop",e)}i(Ee,"eventLoopError");s.addEventListener("error",e=>{e.preventDefault(),Ee(e.error!==void 0?T(e.error):String(e.message))});s.addEventListener("unhandledrejection",e=>{e.preventDefault(),Ee(T(e.reason))});const xe=new Set;function J(e,t){const r=e+`
10
- `+t;xe.has(r)||(xe.add(r),u({type:"gap",kind:e,detail:t}))}i(J,"gap");const ht=new s.URL("../",import.meta.url).href;function bt(){if(typeof s.PerformanceObserver=="function")try{new s.PerformanceObserver(e=>{for(const t of e.getEntries()){const r=String(t.name);(r.startsWith("https:")||r.startsWith("http:"))&&!r.startsWith(ht)&&J("network",r)}}).observe({type:"resource",buffered:!0})}catch{}}i(bt,"watchNetwork");function vt(){const e=Object.getOwnPropertyDescriptor(globalThis,"addEventListener");if(!e||typeof e.value!="function")return;const t=e.value;Object.defineProperty(globalThis,"addEventListener",{...e,value:i(function(a,c,g){return(a==="keydown"||a==="keyup")&&J("keys",""),t.apply(this,arguments)},"addEventListener")})}i(vt,"watchKeyListeners");function yt(){for(const e of["navigator","self"])Object.defineProperty(globalThis,e,{value:globalThis[e],writable:!0,configurable:!0,enumerable:!0})}i(yt,"prepareGlobal");async function wt(){const e=await s.gpu.requestAdapter();if(!e)return null;const t=[];e.features.has("texture-compression-bc")&&t.push("texture-compression-bc");const r=await e.requestDevice({requiredFeatures:t});return globalThis.__device=r,{adapter:e,device:r}}i(wt,"createDevice");const Re=`@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4<f32> {
9
+ `)[0]),d("error","[script] plugin load failed ("+e+"): "+t),u({type:"fault",where:e,message:t}),this.latched||(this.latched={kind:"load",message:this.short})},boundary(e){this.errorThisFrame?this.streakStart===null?this.streakStart=e:!this.latched&&e-this.streakStart>=bt&&(this.latched={kind:"crash",message:this.short}):this.streakStart=null,this.errorThisFrame=!1}};Ke($e(n),e=>{A.warn("[web] unimplemented op touched: "+e),u({type:"absent-op",name:e})});function Re(e){m==="evaluating"?w("plugin evaluation",e):m==="initializing"?w("plugin init",e):_.report("event loop",e)}i(Re,"eventLoopError");s.addEventListener("error",e=>{e.preventDefault(),Re(e.error!==void 0?T(e.error):String(e.message))});s.addEventListener("unhandledrejection",e=>{e.preventDefault(),Re(T(e.reason))});const xe=new Set;function J(e,t){const r=e+`
10
+ `+t;xe.has(r)||(xe.add(r),u({type:"gap",kind:e,detail:t}))}i(J,"gap");const vt=new s.URL("../",import.meta.url).href;function yt(){if(typeof s.PerformanceObserver=="function")try{new s.PerformanceObserver(e=>{for(const t of e.getEntries()){const r=String(t.name);(r.startsWith("https:")||r.startsWith("http:"))&&!r.startsWith(vt)&&J("network",r)}}).observe({type:"resource",buffered:!0})}catch{}}i(yt,"watchNetwork");function wt(){const e=Object.getOwnPropertyDescriptor(globalThis,"addEventListener");if(!e||typeof e.value!="function")return;const t=e.value;Object.defineProperty(globalThis,"addEventListener",{...e,value:i(function(a,c,g){return(a==="keydown"||a==="keyup")&&J("keys",""),t.apply(this,arguments)},"addEventListener")})}i(wt,"watchKeyListeners");function xt(){for(const e of["navigator","self"])Object.defineProperty(globalThis,e,{value:globalThis[e],writable:!0,configurable:!0,enumerable:!0})}i(xt,"prepareGlobal");async function Tt(){const e=await s.gpu.requestAdapter();if(!e)return null;const t=[];e.features.has("texture-compression-bc")&&t.push("texture-compression-bc");const r=await e.requestDevice({requiredFeatures:t});return globalThis.__device=r,{adapter:e,device:r}}i(Tt,"createDevice");const Oe=`@vertex fn vs(@builtin(vertex_index) vi : u32) -> @builtin(position) vec4<f32> {
11
11
  var p = array<vec2<f32>, 3>(vec2<f32>(-1.,-1.), vec2<f32>(3.,-1.), vec2<f32>(-1.,3.));
12
12
  return vec4<f32>(p[vi], 0., 1.);
13
13
  }
14
- `,xt=Re+`@group(0) @binding(0) var src : texture_2d<f32>;
14
+ `,kt=Oe+`@group(0) @binding(0) var src : texture_2d<f32>;
15
15
  fn srgb_to_linear(c : vec3<f32>) -> vec3<f32> {
16
16
  let lo = c / 12.92;
17
17
  let hi = pow((c + 0.055) / 1.055, vec3<f32>(2.4));
@@ -21,7 +21,7 @@ fn srgb_to_linear(c : vec3<f32>) -> vec3<f32> {
21
21
  let c = textureLoad(src, vec2<i32>(frag.xy), 0);
22
22
  return vec4<f32>(srgb_to_linear(c.rgb), 1.0);
23
23
  }
24
- `,Tt=32,Oe=Re+`struct Box { scale : vec2<f32>, split : f32, pad : f32 };
24
+ `,_t=32,Ne=Oe+`struct Box { scale : vec2<f32>, split : f32, pad : f32 };
25
25
  @group(0) @binding(0) var scene : texture_2d<f32>;
26
26
  @group(0) @binding(1) var desk : texture_2d<f32>;
27
27
  @group(0) @binding(2) var<uniform> box : Box;
@@ -35,7 +35,7 @@ fn shown(p : vec2<i32>, before : bool) -> vec3<f32> {
35
35
  @fragment fn fs(@builtin(position) frag : vec4<f32>) -> @location(0) vec4<f32> {
36
36
  let size = vec2<i32>(textureDimensions(scene));
37
37
  let before = frag.x < box.split;
38
- let w = clamp(box.scale, vec2<f32>(1.0), vec2<f32>(`+Tt+`.0));
38
+ let w = clamp(box.scale, vec2<f32>(1.0), vec2<f32>(`+_t+`.0));
39
39
  let c = frag.xy * box.scale;
40
40
  let lo = c - 0.5 * w;
41
41
  let hi = c + 0.5 * w;
@@ -54,7 +54,7 @@ fn shown(p : vec2<i32>, before : bool) -> vec3<f32> {
54
54
  }
55
55
  return vec4<f32>(sum / weight, 1.0);
56
56
  }
57
- `,kt=`struct Quad { rect : vec4<f32> };
57
+ `,St=`struct Quad { rect : vec4<f32> };
58
58
  @group(0) @binding(0) var tex : texture_2d<f32>;
59
59
  @group(0) @binding(1) var samp : sampler;
60
60
  @group(0) @binding(2) var<uniform> q : Quad;
@@ -71,4 +71,4 @@ struct VsOut { @builtin(position) pos : vec4<f32>, @location(0) uv : vec2<f32> }
71
71
  @fragment fn fs(@location(0) uv : vec2<f32>) -> @location(0) vec4<f32> {
72
72
  return textureSample(tex, samp, uv);
73
73
  }
74
- `;function ne(e,t,r,a){const c=s.createShaderModule.call(e,{code:t,label:a});return e.createRenderPipeline({label:a,layout:"auto",vertex:{module:c,entryPoint:"vs"},fragment:{module:c,entryPoint:"fs",targets:[{format:r}]},primitive:{topology:"triangle-list"}})}i(ne,"fullscreenPipeline");let o=null,ie=null,z=null,G="",ae=null,F=null,Ne=null,M=0,ue=null,Y=null,ce=null;const _t=8192;let V=null;function Ae(e){const[t,r]=n.sceneSize,a=o.createTexture({label:"overglaze.picture",size:[t,r],format:"rgba8unorm",usage:b.TEXTURE_BINDING|b.COPY_DST|b.RENDER_ATTACHMENT});s.copyExternalImageToTexture.call(o.queue,{source:e},{texture:a},[t,r]),V&&V.destroy(),V=a,Fe()}i(Ae,"setPicture");function Fe(){const e=o.createCommandEncoder(),t=e.beginRenderPass({colorAttachments:[{view:n.desktopTex.createView(),loadOp:"clear",storeOp:"store"}]});t.setPipeline(ae),t.setBindGroup(0,o.createBindGroup({layout:ae.getBindGroupLayout(0),entries:[{binding:0,resource:V.createView()}]})),t.draw(3),t.end(),o.queue.submit([e.finish()]),l.baked=!1}i(Fe,"linearize");function Be(e,t){const r=[n.sceneTex,n.desktopTex],a=n.sceneSize;n.sceneSize=e,r[0]&&C.rescale(e[0]/a[0],e[1]/a[1]),n.desktopTex=o.createTexture({label:"overglaze.desktop",size:e,format:"rgba16float",usage:b.TEXTURE_BINDING|b.RENDER_ATTACHMENT|b.COPY_SRC}),Ae(t),n.sceneTex=o.createTexture({label:"overglaze.scene",size:e,format:"rgba16float",usage:b.RENDER_ATTACHMENT|b.TEXTURE_BINDING|b.COPY_DST|b.COPY_SRC}),M++,F&&Ge();for(const c of r)c&&c.destroy()}i(Be,"buildScene");function Ge(){Ne=o.createBindGroup({layout:F.getBindGroupLayout(0),entries:[{binding:0,resource:n.sceneTex.createView()},{binding:1,resource:n.desktopTex.createView()},{binding:2,resource:{buffer:ce}}]}),Ue()}i(Ge,"bindOutput");function Ue(){const[e,t]=n.sceneSize,[r,a]=ue||n.sceneSize;z.width!==r&&(z.width=r),z.height!==a&&(z.height=a);const c=Y===null?-1:Y*r;o.queue.writeBuffer(ce,0,new Float32Array([e/r,t/a,c,0]))}i(Ue,"fitOutput");function fe(e){return s.createBuffer.call(o,{label:e,size:16,usage:s.GPUBufferUsage.UNIFORM|s.GPUBufferUsage.COPY_DST})}i(fe,"uniformBuffer");const l={pipeline:null,sampler:null,quad:null,texture:null,bindGroup:null,size:[0,0],hot:[0,0],over:!1,baked:!1};function oe(e,t){if(!l.pipeline){const r=s.createShaderModule.call(o,{code:kt,label:"overglaze.cursor"});l.pipeline=o.createRenderPipeline({label:"overglaze.cursor",layout:"auto",vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:"rgba16float",blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}}),l.sampler=o.createSampler({magFilter:"linear",minFilter:"linear"}),l.quad=fe("overglaze.cursor.quad")}l.texture&&l.texture.destroy(),l.size=[e.width,e.height],l.hot=[Number(t[0])||0,Number(t[1])||0],l.texture=o.createTexture({label:"overglaze.cursor",size:l.size,format:"rgba8unorm-srgb",usage:b.TEXTURE_BINDING|b.COPY_DST|b.RENDER_ATTACHMENT}),s.copyExternalImageToTexture.call(o.queue,{source:e},{texture:l.texture},l.size),l.bindGroup=o.createBindGroup({layout:l.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:l.texture.createView()},{binding:1,resource:l.sampler},{binding:2,resource:{buffer:l.quad}}]})}i(oe,"setCursor");function St(){const e=n.mode==="warp"&&l.over&&l.texture!==null;if(!e&&!l.baked||(Fe(),!e))return;const[t,r]=n.sceneSize,[a,c]=C.position(),g=Math.round(a-l.hot[0]),v=Math.round(c-l.hot[1]),f=[g/t*2-1,1-(v+l.size[1])/r*2,(g+l.size[0])/t*2-1,1-v/r*2];o.queue.writeBuffer(l.quad,0,new Float32Array(f));const h=o.createCommandEncoder(),x=h.beginRenderPass({colorAttachments:[{view:n.desktopTex.createView(),loadOp:"load",storeOp:"store"}]});x.setPipeline(l.pipeline),x.setBindGroup(0,l.bindGroup),x.draw(6),x.end(),o.queue.submit([h.finish()]),l.baked=!0}i(St,"desktopLayer");let m="boot",Q=0,Te=0;function U(e){m=e,u({type:"phase",phase:e}),e==="running"&&Ie()}i(U,"setPhase");function w(e,t){_.loadFailure(e,t),Ce()}i(w,"failLoad");function Ce(){m!=="failed"&&(U("failed"),u({type:"disabled",kind:_.latched.kind,message:_.latched.message}))}i(Ce,"disable");function Pt(e){return"/plugin/"+e}i(Pt,"entryPath");async function zt(e){const t=String(e.entry),r=t.lastIndexOf("."),a=r<0?"":t.slice(r+1).toLowerCase();if(a==="wgsl"||a==="wasm"){d("info","[script] loading "+a.toUpperCase()+"-only plugin: "+t);let f;try{f=await n.files.read(Pt(t))}catch(h){w("plugin load",h.message);return}try{a==="wgsl"?globalThis.__ogRunWgsl(new s.TextDecoder().decode(f)):globalThis.__ogRunWasm(f)}catch(h){w("plugin load",T(h));return}d("info","[script] "+a.toUpperCase()+"-only plugin loaded"),U("running");return}const c="unsupported entry '"+t+"': not a module the engine runs";let g;if(e.modules){if(typeof e.module!="string"){w("plugin load",c);return}g=e.modules+e.module}else{let f;try{f=await Et(e)}catch(h){w("plugin load",T(h));return}if(f.kind!=="javascript"&&f.kind!=="typescript"){w("plugin load",c);return}d("info","[script] made "+f.modules+" module(s) from the plugin's files");for(const h of f.meta)for(const x of h.reads)J("import-meta",h.path+": import.meta"+(x?"."+x:""));g=f.url}d("info","[script] loading plugin module: "+t),U("evaluating");let v;try{v=await import(g)}catch(f){m==="evaluating"&&w("plugin evaluation",T(f));return}m==="evaluating"&&Ot(v)}i(zt,"beginSelection");let $=null,X=null;async function Et(e){if(!$){const a=await s.fetch(new s.URL("plugin-js.wasm",import.meta.url).href);if(!a.ok)throw new Error("plugin-js.wasm: HTTP "+a.status);$=await at.load(await a.arrayBuffer())}const t={};if(e.plugin)for(const[a,c]of Object.entries(e.packageImports||{}))t[a]=new s.URL(c,e.plugin).href;const r=n.files;return it({entry:String(e.entry),js:$,has:i(a=>r.has(a),"has"),read:i(a=>r.source(a),"read"),packages:t,lock:r.has("deno.lock"),url:nt})}i(Et,"sourceModules");async function Rt(){const e=await s.fetch(new s.URL("naga.wasm",import.meta.url).href);if(!e.ok)throw new Error("naga.wasm: HTTP "+e.status);return lt.load(await e.arrayBuffer())}i(Rt,"loadNaga");function Ot(e){const t=e.init;if(typeof t!="function"){d("info","[script] plugin loaded"),ke(),U("running");return}U("initializing"),Te=Q=S();let r;try{r=globalThis.__ogRunInit(t,n.sceneSize[0],n.sceneSize[1])}catch(a){w("plugin init",T(a));return}Promise.resolve(r).then(()=>{m==="initializing"&&(d("info","[script] plugin init(ctx) resolved after "+((S()-Te)/1e3).toFixed(2)+"s"),ke(),U("running"))},a=>{m==="initializing"&&w("plugin init",T(a))})}i(Ot,"startInit");function ke(){try{globalThis.__ogPruneParams&&globalThis.__ogPruneParams()}catch(e){d("warn","[script] parameter prune failed: "+String(e))}}i(ke,"pruneParams");function Nt(e){m!=="initializing"||e-Q<we||w("plugin init","stalled for "+we/1e3+"s with no progress reported (call ctx.progress() during long setup to keep the host informed)")}i(Nt,"pollLoad");function At(){if(m==="initializing")try{globalThis.__ogAbortInit&&globalThis.__ogAbortInit()}catch(e){d("warn","[script] init abort failed: "+String(e))}}i(At,"cancel");const C=new $e;let se=[],pe=0,N=!1,j=0,I=60,R=0,W=0,H=0,_e="",ee=n.interactiveRects,le=!1;function Ft(e){if(n.mode==="transparent"){e.beginRenderPass({colorAttachments:[{view:n.sceneTex.createView(),clearValue:[0,0,0,0],loadOp:"clear",storeOp:"store"}]}).end();return}e.copyTextureToTexture({texture:n.desktopTex},{texture:n.sceneTex},n.sceneSize)}i(Ft,"prepaint");function Bt(){if(m!=="running"){n.mode="opaque",n.interactiveRects.length&&(n.interactiveRects=[]);return}try{globalThis.__ogPollCompositor&&globalThis.__ogPollCompositor()}catch(e){d("error","[script] compositor poll failed: "+String(e))}}i(Bt,"pollCompositor");function Gt(){const e=C.sample(),t=C.drain(),r=se;if(se=[],m==="boot"||m==="failed"||!t.length&&!r.length&&e.movementX===0&&e.movementY===0)return e;n.inputFrame=Ze(e,t,r);try{globalThis.__ogDispatchInput&&globalThis.__ogDispatchInput()}catch(a){d("error","[script] input dispatch failed: "+String(a))}return e}i(Gt,"dispatchInput");function Le(e){if(!N)return;if(pe=ge(Le),j){const r=e-j;r>0&&r<250&&(I+=(1e3/r-I)*.05)}j=e;const t=de();R++,W++,e-H>=1e3&&(u({type:"stats",fps:W*1e3/(e-H),frames:R,faults:_.count,mode:n.mode}),W=0,H=e),le&&t&&(le=!1,je(),u({type:"held"}))}i(Le,"tick");function de(){const e=globalThis,[t,r]=n.sceneSize;Nt(S()),Bt(),n.mode!==_e&&(_e=n.mode,u({type:"mode",mode:n.mode})),n.interactiveRects!==ee&&(ee=n.interactiveRects,u({type:"claim",rects:Array.from(ee,Number)})),St();const a=o.createCommandEncoder();Ft(a),o.queue.submit([a.finish()]);const c=m==="running";c&&u({type:"plugin",running:!0});const g=Gt(),v=m==="running";if(v){n.published=!0,n.uniformValues=et({refreshHz:Math.round(I),input:g}),n.inFrame=!0;try{e.__ogFrame?e.__ogFrame(t,r,M):e.frame&&(e.__w=t,e.__h=r,e.frame())}catch(f){_.report("frame callback",T(f))}finally{n.inFrame=!1}_.boundary(S()),_.latched&&Ce()}return c&&u({type:"plugin",running:!1}),Ie(),qe(),v}i(de,"renderFrame");let E=null,Me=!1,Se=-1,te=new Map,re=!1;function Ut(e,t){if(!e||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0}i(Ut,"sameValues");function Ie(){if(!Me||E===null)return;if(E.presentationRevision()!==Se){const t=E.presentation();Se=t.revision,te=new Map(t.rows.map(r=>[r.key,r.value])),u({type:"params-model",resettable:t.resettable,rows:t.rows});return}const e=[];for(const[t,r]of E.presentationValues())Ut(te.get(t),r)||(te.set(t,r),e.push([t,r]));e.length&&u({type:"param-values",values:e})}i(Ie,"reportParams");function De(){N||k!==null||R===0||re||(re=!0,ge(()=>{re=!1,Ve()}))}i(De,"afterEdit");function Ct(e,t){E===null||!Array.isArray(t)||E.presentationWrite(e,t.map(Number))&&De()}i(Ct,"writeParam");function Lt(){E!==null&&(E.resetAll(),De())}i(Lt,"resetParams");function qe(){const e=o.createCommandEncoder(),t=e.beginRenderPass({colorAttachments:[{view:ie.getCurrentTexture().createView({format:G+"-srgb"}),loadOp:"clear",storeOp:"store"}]});t.setPipeline(F),t.setBindGroup(0,Ne),t.draw(3),t.end(),o.queue.submit([e.finish()])}i(qe,"present");function Pe(){Ue(),!N&&R>0&&qe()}i(Pe,"refit");function Ve(){N||k!==null||R===0||!F||(K-=1e3/Math.max(1,I),de(),R++)}i(Ve,"redraw");let k=null,B=null,K=0;function Mt(){return k!==null?k:(B===null?S():B)-K}i(Mt,"pluginNow");function It(e){if(k===null||!Number.isFinite(e))return;k=null;const t=S();K=t-e,L&&(B=t),me()}i(It,"runOn");let y=null;function Dt(){const[e,t]=n.sceneSize;if(y&&y.epoch===M)return y;if(y&&y.texture.destroy(),!y){const r=fe("overglaze.golden.box");o.queue.writeBuffer(r,0,new Float32Array([1,1,-1,0])),y={pipeline:ne(o,Oe,"rgba8unorm-srgb","overglaze.golden"),box:r}}return y.epoch=M,y.texture=o.createTexture({label:"overglaze.golden",size:[e,t],format:"rgba8unorm-srgb",usage:b.RENDER_ATTACHMENT|b.COPY_SRC}),y.bindGroup=o.createBindGroup({layout:y.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.sceneTex.createView()},{binding:1,resource:n.desktopTex.createView()},{binding:2,resource:{buffer:y.box}}]}),y}i(Dt,"goldenTarget");async function qt(){const[e,t]=n.sceneSize,r=Dt(),a=e*4,c=Math.ceil(a/256)*256,g=s.createBuffer.call(o,{label:"overglaze.golden.readback",size:c*t,usage:s.GPUBufferUsage.MAP_READ|s.GPUBufferUsage.COPY_DST}),v=o.createCommandEncoder(),f=v.beginRenderPass({colorAttachments:[{view:r.texture.createView(),loadOp:"clear",storeOp:"store"}]});f.setPipeline(r.pipeline),f.setBindGroup(0,r.bindGroup),f.draw(3),f.end(),v.copyTextureToBuffer({texture:r.texture},{buffer:g,bytesPerRow:c,rowsPerImage:t},[e,t]),o.queue.submit([v.finish()]),await g.mapAsync(s.GPUMapMode.READ);const h=new Uint8Array(g.getMappedRange()),x=new Uint8Array(a*t);for(let P=0;P<t;P++)x.set(h.subarray(P*c,P*c+a),P*a);return g.unmap(),g.destroy(),x.buffer}i(qt,"readOutput");async function Vt(e){if(k===null||!o)return;k=Number(e.t),de(),R++;const t=e.capture?await qt():null;u({type:"stepped",id:e.id,frame:R,pixels:t},t?[t]:[])}i(Vt,"step");const ge=s.requestAnimationFrame||(e=>s.setTimeout(()=>e(S()),16)),jt=s.cancelAnimationFrame||s.clearTimeout;let L=!1;function me(){N||L||k!==null||(N=!0,j=0,W=0,H=S(),pe=ge(Le))}i(me,"play");function je(){L=!0,B===null&&(B=S()),N&&(N=!1,jt(pe))}i(je,"pause");function Wt(){if(!L)return;L=!1;const e=S()-B;B=null,K+=e,Q+=e,_.streakStart=null,me()}i(Wt,"resume");async function Ht(e){const{canvas:t,picture:r,plugin:a,modules:c,scene:g,storage:v,params:f,beat:h,clock:x,refreshHz:P}=e,he=c?null:Rt().then(p=>({naga:p}),p=>({e:p}));bt(),u({type:"beat"}),s.setInterval(()=>u({type:"beat"}),h),z=t,ue=We(e.output),le=e.hold===!0,Array.isArray(e.pointer)&&C.place(Number(e.pointer[0])||0,Number(e.pointer[1])||0),yt(),dt(),x==="stepped"&&(k=0,Number.isFinite(P)&&P>0&&(I=P)),Object.defineProperty(s.performance,"now",{value:i(function(){return Mt()},"now"),writable:!0,configurable:!0}),await import("../host/bootstrap.js");const be=Array.isArray(e.files),O=be?e.descriptor:await(await s.fetch(a+"overglaze-web.json")).json(),ve=ct(O);ve&&d("warn",ve),n.capabilities=new Set(O.capabilities||[]),n.capabilities.size?d("info","[script] plugin capabilities granted: "+[...n.capabilities].join(", ")):d("info","[script] plugin capabilities: none declared"),n.capabilities.has("desktopCapture")&&ft(s.GPUDevice,s.GPUBufferUsage),n.storage=new ut(v,(p,Z,He,Ye)=>{u({type:"storage",area:p,op:Z,key:He,value:Ye})}),n.params=new ze(f),E=await import("../host/params.js"),Me=e.watchParams===!0;const D=await wt();if(!D){u({type:"unsupported",message:"no WebGPU adapter"});return}if(o=D.device,o.lost.then(p=>u({type:"lost",reason:String(p.reason),message:String(p.message)})),he){const p=await he;if(p.e){w("plugin load",T(p.e));return}X=ot(p.naga,Z=>J("shader",st(Z))),X.watch(o)}ae=ne(o,xt,"rgba16float","overglaze.linearize"),ce=fe("overglaze.box"),Be(g,r),r.close(),e.cursor&&(oe(e.cursor,e.hot||[0,0]),e.cursor.close()),n.files=new rt(be?new Map(e.files):a,O.files||[],o),n.textures=new tt(o,n.files,d),n.auto=[];for(const p of O.autoBindings||[])n.auto.push({name:p.name,entry:await n.textures.load(p.path)});n.auto.length&&d("info","[assets] auto-bindable in assets/: "+n.auto.map(p=>p.name).join(", "));try{globalThis.__ogInit(o)}catch(p){d("error","[script] @overglaze/api init failed: "+T(p))}(O.mode==="transparent"||O.mode==="warp")&&(globalThis.overglaze.mode=O.mode),k!==null&&await import("../host/seeded_random.js"),vt();const ye=pt(gt);u({type:"globals",stuck:ye.stuck,inherited:ye.inherited}),ie=z.getContext("webgpu"),G=s.gpu.getPreferredCanvasFormat(),ie.configure({device:o,format:G,viewFormats:[G+"-srgb"],alphaMode:"opaque"}),F=ne(o,Oe,G+"-srgb","overglaze.output"),Ge();const q=D.adapter.info||{};u({type:"ready",adapter:[q.vendor,q.architecture,q.description].filter(Boolean).join(" "),fallback:!!(q.isFallbackAdapter||D.adapter.isFallbackAdapter),features:[...o.features],canvasFormat:G,absentDeclared:Qe}),k===null&&me(),await zt({...O,plugin:a,modules:c})}i(Ht,"start");function We(e){if(!Array.isArray(e))return null;const t=i(r=>Math.min(_t,Math.max(1,Math.round(Number(r))||1)),"side");return[t(e[0]),t(e[1])]}i(We,"outputDims");function Yt(){const e=globalThis.gpu&&globalThis.gpu.builtinUniforms||{};return{frames:R,faults:_.count,phase:m,mode:n.mode,epoch:M,paused:L,scene:n.sceneSize.slice(),output:z?[z.width,z.height]:null,split:Y,cursor:{over:l.over,baked:l.baked,size:l.size.slice()},input:e.input?JSON.parse(JSON.stringify(e.input)):null,display:e.display?{...e.display}:null,resolution:e.resolution?JSON.parse(JSON.stringify(e.resolution)):null,time:e.time?{...e.time}:null,params:n.params.toObject(),shaders:X?{...X.counts}:null}}i(Yt,"probe");s.addEventListener("message",e=>{const t=e.data;switch(t.type){case"start":Ht(t).catch(r=>w("start",T(r)));break;case"pause":je();break;case"resume":Wt();break;case"resize":o&&Be(t.scene,t.picture),t.picture.close(),o&&t.cursor&&oe(t.cursor,t.hot||[0,0]),t.cursor&&t.cursor.close();break;case"desktop":o&&(Ae(t.picture),Ve()),t.picture.close(),Number.isInteger(t.id)&&u({type:"desktop-in",id:t.id});break;case"output":ue=We(t.size),F&&Pe();break;case"split":Y=t.at===null?null:Math.min(1,Math.max(0,Number(t.at)||0)),F&&Pe();break;case"cursor":o&&oe(t.cursor,t.hot||[0,0]),t.cursor.close();break;case"hover":l.over=t.over===!0;break;case"pointer":C.push(t);break;case"key":se.push(t.key);break;case"cancel":At();break;case"step":Vt(t).catch(r=>d("error","[web] step failed: "+T(r)));break;case"run":It(Number(t.t));break;case"param":Ct(String(t.key),t.values);break;case"param-reset":Lt();break;case"probe":u({type:"probe",id:t.id,result:Yt()});break;case"destroy-device":o&&o.destroy();break}});
74
+ `;function ne(e,t,r,a){const c=s.createShaderModule.call(e,{code:t,label:a});return e.createRenderPipeline({label:a,layout:"auto",vertex:{module:c,entryPoint:"vs"},fragment:{module:c,entryPoint:"fs",targets:[{format:r}]},primitive:{topology:"triangle-list"}})}i(ne,"fullscreenPipeline");let o=null,ie=null,z=null,G="",ae=null,F=null,Ae=null,M=0,ue=null,Y=null,ce=null;const Pt=8192;let V=null;function Fe(e){const[t,r]=n.sceneSize,a=o.createTexture({label:"overglaze.picture",size:[t,r],format:"rgba8unorm",usage:b.TEXTURE_BINDING|b.COPY_DST|b.RENDER_ATTACHMENT});s.copyExternalImageToTexture.call(o.queue,{source:e},{texture:a},[t,r]),V&&V.destroy(),V=a,Be()}i(Fe,"setPicture");function Be(){const e=o.createCommandEncoder(),t=e.beginRenderPass({colorAttachments:[{view:n.desktopTex.createView(),loadOp:"clear",storeOp:"store"}]});t.setPipeline(ae),t.setBindGroup(0,o.createBindGroup({layout:ae.getBindGroupLayout(0),entries:[{binding:0,resource:V.createView()}]})),t.draw(3),t.end(),o.queue.submit([e.finish()]),l.baked=!1}i(Be,"linearize");function Ge(e,t){const r=[n.sceneTex,n.desktopTex],a=n.sceneSize;n.sceneSize=e,r[0]&&C.rescale(e[0]/a[0],e[1]/a[1]),n.desktopTex=o.createTexture({label:"overglaze.desktop",size:e,format:"rgba16float",usage:b.TEXTURE_BINDING|b.RENDER_ATTACHMENT|b.COPY_SRC}),Fe(t),n.sceneTex=o.createTexture({label:"overglaze.scene",size:e,format:"rgba16float",usage:b.RENDER_ATTACHMENT|b.TEXTURE_BINDING|b.COPY_DST|b.COPY_SRC}),M++,F&&Ue();for(const c of r)c&&c.destroy()}i(Ge,"buildScene");function Ue(){Ae=o.createBindGroup({layout:F.getBindGroupLayout(0),entries:[{binding:0,resource:n.sceneTex.createView()},{binding:1,resource:n.desktopTex.createView()},{binding:2,resource:{buffer:ce}}]}),Ce()}i(Ue,"bindOutput");function Ce(){const[e,t]=n.sceneSize,[r,a]=ue||n.sceneSize;z.width!==r&&(z.width=r),z.height!==a&&(z.height=a);const c=Y===null?-1:Y*r;o.queue.writeBuffer(ce,0,new Float32Array([e/r,t/a,c,0]))}i(Ce,"fitOutput");function fe(e){return s.createBuffer.call(o,{label:e,size:16,usage:s.GPUBufferUsage.UNIFORM|s.GPUBufferUsage.COPY_DST})}i(fe,"uniformBuffer");const l={pipeline:null,sampler:null,quad:null,texture:null,bindGroup:null,size:[0,0],hot:[0,0],over:!1,baked:!1};function oe(e,t){if(!l.pipeline){const r=s.createShaderModule.call(o,{code:St,label:"overglaze.cursor"});l.pipeline=o.createRenderPipeline({label:"overglaze.cursor",layout:"auto",vertex:{module:r,entryPoint:"vs"},fragment:{module:r,entryPoint:"fs",targets:[{format:"rgba16float",blend:{color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}}}]},primitive:{topology:"triangle-list"}}),l.sampler=o.createSampler({magFilter:"linear",minFilter:"linear"}),l.quad=fe("overglaze.cursor.quad")}l.texture&&l.texture.destroy(),l.size=[e.width,e.height],l.hot=[Number(t[0])||0,Number(t[1])||0],l.texture=o.createTexture({label:"overglaze.cursor",size:l.size,format:"rgba8unorm-srgb",usage:b.TEXTURE_BINDING|b.COPY_DST|b.RENDER_ATTACHMENT}),s.copyExternalImageToTexture.call(o.queue,{source:e},{texture:l.texture},l.size),l.bindGroup=o.createBindGroup({layout:l.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:l.texture.createView()},{binding:1,resource:l.sampler},{binding:2,resource:{buffer:l.quad}}]})}i(oe,"setCursor");function zt(){const e=n.mode==="warp"&&l.over&&l.texture!==null;if(!e&&!l.baked||(Be(),!e))return;const[t,r]=n.sceneSize,[a,c]=C.position(),g=Math.round(a-l.hot[0]),v=Math.round(c-l.hot[1]),f=[g/t*2-1,1-(v+l.size[1])/r*2,(g+l.size[0])/t*2-1,1-v/r*2];o.queue.writeBuffer(l.quad,0,new Float32Array(f));const h=o.createCommandEncoder(),x=h.beginRenderPass({colorAttachments:[{view:n.desktopTex.createView(),loadOp:"load",storeOp:"store"}]});x.setPipeline(l.pipeline),x.setBindGroup(0,l.bindGroup),x.draw(6),x.end(),o.queue.submit([h.finish()]),l.baked=!0}i(zt,"desktopLayer");let m="boot",Q=0,Te=0;function U(e){m=e,u({type:"phase",phase:e}),e==="running"&&qe()}i(U,"setPhase");function w(e,t){_.loadFailure(e,t),Le()}i(w,"failLoad");function Le(){m!=="failed"&&(U("failed"),u({type:"disabled",kind:_.latched.kind,message:_.latched.message}))}i(Le,"disable");function Et(e){return"/plugin/"+e}i(Et,"entryPath");async function Rt(e){const t=String(e.entry),r=t.lastIndexOf("."),a=r<0?"":t.slice(r+1).toLowerCase();if(a==="wgsl"||a==="wasm"){d("info","[script] loading "+a.toUpperCase()+"-only plugin: "+t);let f;try{f=await n.files.read(Et(t))}catch(h){w("plugin load",h.message);return}try{a==="wgsl"?globalThis.__ogRunWgsl(new s.TextDecoder().decode(f)):globalThis.__ogRunWasm(f)}catch(h){w("plugin load",T(h));return}d("info","[script] "+a.toUpperCase()+"-only plugin loaded"),U("running");return}const c="unsupported entry '"+t+"': not a module the engine runs";let g;if(e.modules){if(typeof e.module!="string"){w("plugin load",c);return}g=e.modules+e.module}else{let f;try{f=await Ot(e)}catch(h){w("plugin load",T(h));return}if(f.kind!=="javascript"&&f.kind!=="typescript"){w("plugin load",c);return}d("info","[script] made "+f.modules+" module(s) from the plugin's files");for(const h of f.meta)for(const x of h.reads)J("import-meta",h.path+": import.meta"+(x?"."+x:""));g=f.url}d("info","[script] loading plugin module: "+t),U("evaluating");let v;try{v=await import(g)}catch(f){m==="evaluating"&&w("plugin evaluation",T(f));return}m==="evaluating"&&At(v)}i(Rt,"beginSelection");let $=null,X=null;async function Ot(e){if(!$){const a=await s.fetch(new s.URL("plugin-js.wasm",import.meta.url).href);if(!a.ok)throw new Error("plugin-js.wasm: HTTP "+a.status);$=await st.load(await a.arrayBuffer())}const t={};if(e.plugin)for(const[a,c]of Object.entries(e.packageImports||{}))t[a]=new s.URL(c,e.plugin).href;const r=n.files;return ot({entry:String(e.entry),js:$,has:i(a=>r.has(a),"has"),read:i(a=>r.source(a),"read"),packages:t,lock:r.has("deno.lock"),url:at})}i(Ot,"sourceModules");async function Nt(){const e=await s.fetch(new s.URL("naga.wasm",import.meta.url).href);if(!e.ok)throw new Error("naga.wasm: HTTP "+e.status);return ct.load(await e.arrayBuffer())}i(Nt,"loadNaga");function At(e){const t=e.init;if(typeof t!="function"){d("info","[script] plugin loaded"),ke(),U("running");return}U("initializing"),Te=Q=S();let r;try{r=globalThis.__ogRunInit(t,n.sceneSize[0],n.sceneSize[1])}catch(a){w("plugin init",T(a));return}Promise.resolve(r).then(()=>{m==="initializing"&&(d("info","[script] plugin init(ctx) resolved after "+((S()-Te)/1e3).toFixed(2)+"s"),ke(),U("running"))},a=>{m==="initializing"&&w("plugin init",T(a))})}i(At,"startInit");function ke(){try{globalThis.__ogPruneParams&&globalThis.__ogPruneParams()}catch(e){d("warn","[script] parameter prune failed: "+String(e))}}i(ke,"pruneParams");function Ft(e){m!=="initializing"||e-Q<we||w("plugin init","stalled for "+we/1e3+"s with no progress reported (call ctx.progress() during long setup to keep the host informed)")}i(Ft,"pollLoad");function Bt(){if(m==="initializing")try{globalThis.__ogAbortInit&&globalThis.__ogAbortInit()}catch(e){d("warn","[script] init abort failed: "+String(e))}}i(Bt,"cancel");const C=new tt;let se=[],pe=0,N=!1,j=0,D=60,R=0,W=0,H=0,_e=!1;function Me(e){!e||_e||(_e=!0,u({type:"drawn"}))}i(Me,"tellDrawn");let Se="",ee=n.interactiveRects,le=!1;function Gt(e){if(n.mode==="transparent"){e.beginRenderPass({colorAttachments:[{view:n.sceneTex.createView(),clearValue:[0,0,0,0],loadOp:"clear",storeOp:"store"}]}).end();return}e.copyTextureToTexture({texture:n.desktopTex},{texture:n.sceneTex},n.sceneSize)}i(Gt,"prepaint");function Ut(){if(m!=="running"){n.mode="opaque",n.interactiveRects.length&&(n.interactiveRects=[]);return}try{globalThis.__ogPollCompositor&&globalThis.__ogPollCompositor()}catch(e){d("error","[script] compositor poll failed: "+String(e))}}i(Ut,"pollCompositor");function Ct(){const e=C.sample(),t=C.drain(),r=se;if(se=[],m==="boot"||m==="failed"||!t.length&&!r.length&&e.movementX===0&&e.movementY===0)return e;n.inputFrame=et(e,t,r);try{globalThis.__ogDispatchInput&&globalThis.__ogDispatchInput()}catch(a){d("error","[script] input dispatch failed: "+String(a))}return e}i(Ct,"dispatchInput");function De(e){if(!N)return;if(pe=ge(De),j){const r=e-j;r>0&&r<250&&(D+=(1e3/r-D)*.05)}j=e;const t=de();Me(t),R++,W++,e-H>=1e3&&(u({type:"stats",fps:W*1e3/(e-H),frames:R,faults:_.count,mode:n.mode}),W=0,H=e),le&&t&&(le=!1,He(),u({type:"held"}))}i(De,"tick");function de(){const e=globalThis,[t,r]=n.sceneSize;Ft(S()),Ut(),n.mode!==Se&&(Se=n.mode,u({type:"mode",mode:n.mode})),n.interactiveRects!==ee&&(ee=n.interactiveRects,u({type:"claim",rects:Array.from(ee,Number)})),zt();const a=o.createCommandEncoder();Gt(a),o.queue.submit([a.finish()]);const c=m==="running";c&&u({type:"plugin",running:!0});const g=Ct(),v=m==="running";if(v){n.published=!0,n.uniformValues=rt({refreshHz:Math.round(D),input:g}),n.inFrame=!0;try{e.__ogFrame?e.__ogFrame(t,r,M):e.frame&&(e.__w=t,e.__h=r,e.frame())}catch(f){_.report("frame callback",T(f))}finally{n.inFrame=!1}_.boundary(S()),_.latched&&Le()}return c&&u({type:"plugin",running:!1}),qe(),je(),v}i(de,"renderFrame");let E=null,Ie=!1,Pe=-1,te=new Map,re=!1;function Lt(e,t){if(!e||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0}i(Lt,"sameValues");function qe(){if(!Ie||E===null)return;if(E.presentationRevision()!==Pe){const t=E.presentation();Pe=t.revision,te=new Map(t.rows.map(r=>[r.key,r.value])),u({type:"params-model",resettable:t.resettable,rows:t.rows});return}const e=[];for(const[t,r]of E.presentationValues())Lt(te.get(t),r)||(te.set(t,r),e.push([t,r]));e.length&&u({type:"param-values",values:e})}i(qe,"reportParams");function Ve(){N||k!==null||R===0||re||(re=!0,ge(()=>{re=!1,We()}))}i(Ve,"afterEdit");function Mt(e,t){E===null||!Array.isArray(t)||E.presentationWrite(e,t.map(Number))&&Ve()}i(Mt,"writeParam");function Dt(){E!==null&&(E.resetAll(),Ve())}i(Dt,"resetParams");function je(){const e=o.createCommandEncoder(),t=e.beginRenderPass({colorAttachments:[{view:ie.getCurrentTexture().createView({format:G+"-srgb"}),loadOp:"clear",storeOp:"store"}]});t.setPipeline(F),t.setBindGroup(0,Ae),t.draw(3),t.end(),o.queue.submit([e.finish()])}i(je,"present");function ze(){Ce(),!N&&R>0&&je()}i(ze,"refit");function We(){N||k!==null||R===0||!F||(K-=1e3/Math.max(1,D),de(),R++)}i(We,"redraw");let k=null,B=null,K=0;function It(){return k!==null?k:(B===null?S():B)-K}i(It,"pluginNow");function qt(e){if(k===null||!Number.isFinite(e))return;k=null;const t=S();K=t-e,L&&(B=t),me()}i(qt,"runOn");let y=null;function Vt(){const[e,t]=n.sceneSize;if(y&&y.epoch===M)return y;if(y&&y.texture.destroy(),!y){const r=fe("overglaze.golden.box");o.queue.writeBuffer(r,0,new Float32Array([1,1,-1,0])),y={pipeline:ne(o,Ne,"rgba8unorm-srgb","overglaze.golden"),box:r}}return y.epoch=M,y.texture=o.createTexture({label:"overglaze.golden",size:[e,t],format:"rgba8unorm-srgb",usage:b.RENDER_ATTACHMENT|b.COPY_SRC}),y.bindGroup=o.createBindGroup({layout:y.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.sceneTex.createView()},{binding:1,resource:n.desktopTex.createView()},{binding:2,resource:{buffer:y.box}}]}),y}i(Vt,"goldenTarget");async function jt(){const[e,t]=n.sceneSize,r=Vt(),a=e*4,c=Math.ceil(a/256)*256,g=s.createBuffer.call(o,{label:"overglaze.golden.readback",size:c*t,usage:s.GPUBufferUsage.MAP_READ|s.GPUBufferUsage.COPY_DST}),v=o.createCommandEncoder(),f=v.beginRenderPass({colorAttachments:[{view:r.texture.createView(),loadOp:"clear",storeOp:"store"}]});f.setPipeline(r.pipeline),f.setBindGroup(0,r.bindGroup),f.draw(3),f.end(),v.copyTextureToBuffer({texture:r.texture},{buffer:g,bytesPerRow:c,rowsPerImage:t},[e,t]),o.queue.submit([v.finish()]),await g.mapAsync(s.GPUMapMode.READ);const h=new Uint8Array(g.getMappedRange()),x=new Uint8Array(a*t);for(let P=0;P<t;P++)x.set(h.subarray(P*c,P*c+a),P*a);return g.unmap(),g.destroy(),x.buffer}i(jt,"readOutput");async function Wt(e){if(k===null||!o)return;k=Number(e.t),Me(de()),R++;const t=e.capture?await jt():null;u({type:"stepped",id:e.id,frame:R,pixels:t},t?[t]:[])}i(Wt,"step");const ge=s.requestAnimationFrame||(e=>s.setTimeout(()=>e(S()),16)),Ht=s.cancelAnimationFrame||s.clearTimeout;let L=!1;function me(){N||L||k!==null||(N=!0,j=0,W=0,H=S(),pe=ge(De))}i(me,"play");function He(){L=!0,B===null&&(B=S()),N&&(N=!1,Ht(pe))}i(He,"pause");function Yt(){if(!L)return;L=!1;const e=S()-B;B=null,K+=e,Q+=e,_.streakStart=null,me()}i(Yt,"resume");async function Xt(e){const{canvas:t,picture:r,plugin:a,modules:c,scene:g,storage:v,params:f,beat:h,clock:x,refreshHz:P}=e,he=c?null:Nt().then(p=>({naga:p}),p=>({e:p}));yt(),u({type:"beat"}),s.setInterval(()=>u({type:"beat"}),h),z=t,ue=Ye(e.output),le=e.hold===!0,Array.isArray(e.pointer)&&C.place(Number(e.pointer[0])||0,Number(e.pointer[1])||0),xt(),mt(),x==="stepped"&&(k=0,Number.isFinite(P)&&P>0&&(D=P)),Object.defineProperty(s.performance,"now",{value:i(function(){return It()},"now"),writable:!0,configurable:!0}),await import("../host/bootstrap.js");const be=Array.isArray(e.files),O=be?e.descriptor:await(await s.fetch(a+"overglaze-web.json")).json(),ve=pt(O);ve&&d("warn",ve),n.capabilities=new Set(O.capabilities||[]),n.capabilities.size?d("info","[script] plugin capabilities granted: "+[...n.capabilities].join(", ")):d("info","[script] plugin capabilities: none declared"),n.capabilities.has("desktopCapture")&&dt(s.GPUDevice,s.GPUBufferUsage),n.storage=new ft(v,(p,Z,Xe,Je)=>{u({type:"storage",area:p,op:Z,key:Xe,value:Je})}),n.params=new Ee(f),E=await import("../host/params.js"),Ie=e.watchParams===!0;const I=await Tt();if(!I){u({type:"unsupported",message:"no WebGPU adapter"});return}if(o=I.device,o.lost.then(p=>u({type:"lost",reason:String(p.reason),message:String(p.message)})),he){const p=await he;if(p.e){w("plugin load",T(p.e));return}X=lt(p.naga,Z=>J("shader",ut(Z))),X.watch(o)}ae=ne(o,kt,"rgba16float","overglaze.linearize"),ce=fe("overglaze.box"),Ge(g,r),r.close(),e.cursor&&(oe(e.cursor,e.hot||[0,0]),e.cursor.close()),n.files=new it(be?new Map(e.files):a,O.files||[],o),n.textures=new nt(o,n.files,d),n.auto=[];for(const p of O.autoBindings||[])n.auto.push({name:p.name,entry:await n.textures.load(p.path)});n.auto.length&&d("info","[assets] auto-bindable in assets/: "+n.auto.map(p=>p.name).join(", "));try{globalThis.__ogInit(o)}catch(p){d("error","[script] @overglaze/api init failed: "+T(p))}(O.mode==="transparent"||O.mode==="warp")&&(globalThis.overglaze.mode=O.mode),k!==null&&await import("../host/seeded_random.js"),wt();const ye=gt(ht);u({type:"globals",stuck:ye.stuck,inherited:ye.inherited}),ie=z.getContext("webgpu"),G=s.gpu.getPreferredCanvasFormat(),ie.configure({device:o,format:G,viewFormats:[G+"-srgb"],alphaMode:"opaque"}),F=ne(o,Ne,G+"-srgb","overglaze.output"),Ue();const q=I.adapter.info||{};u({type:"ready",adapter:[q.vendor,q.architecture,q.description].filter(Boolean).join(" "),fallback:!!(q.isFallbackAdapter||I.adapter.isFallbackAdapter),features:[...o.features],canvasFormat:G,absentDeclared:Ze}),k===null&&me(),await Rt({...O,plugin:a,modules:c})}i(Xt,"start");function Ye(e){if(!Array.isArray(e))return null;const t=i(r=>Math.min(Pt,Math.max(1,Math.round(Number(r))||1)),"side");return[t(e[0]),t(e[1])]}i(Ye,"outputDims");function Jt(){const e=globalThis.gpu&&globalThis.gpu.builtinUniforms||{};return{frames:R,faults:_.count,phase:m,mode:n.mode,epoch:M,paused:L,scene:n.sceneSize.slice(),output:z?[z.width,z.height]:null,split:Y,cursor:{over:l.over,baked:l.baked,size:l.size.slice()},input:e.input?JSON.parse(JSON.stringify(e.input)):null,display:e.display?{...e.display}:null,resolution:e.resolution?JSON.parse(JSON.stringify(e.resolution)):null,time:e.time?{...e.time}:null,params:n.params.toObject(),shaders:X?{...X.counts}:null}}i(Jt,"probe");s.addEventListener("message",e=>{const t=e.data;switch(t.type){case"start":Xt(t).catch(r=>w("start",T(r)));break;case"pause":He();break;case"resume":Yt();break;case"resize":o&&Ge(t.scene,t.picture),t.picture.close(),o&&t.cursor&&oe(t.cursor,t.hot||[0,0]),t.cursor&&t.cursor.close();break;case"desktop":o&&(Fe(t.picture),We()),t.picture.close(),Number.isInteger(t.id)&&u({type:"desktop-in",id:t.id});break;case"output":ue=Ye(t.size),F&&ze();break;case"split":Y=t.at===null?null:Math.min(1,Math.max(0,Number(t.at)||0)),F&&ze();break;case"cursor":o&&oe(t.cursor,t.hot||[0,0]),t.cursor.close();break;case"hover":l.over=t.over===!0;break;case"pointer":C.push(t);break;case"key":se.push(t.key);break;case"cancel":Bt();break;case"step":Wt(t).catch(r=>d("error","[web] step failed: "+T(r)));break;case"run":qt(Number(t.t));break;case"param":Mt(String(t.key),t.values);break;case"param-reset":Dt();break;case"probe":u({type:"probe",id:t.id,result:Jt()});break;case"destroy-device":o&&o.destroy();break}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@overglaze/web",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "The Overglaze web engine: an Overglaze plugin, run from its own files, live in a player's box on any page.",
5
5
  "type": "module",
6
6
  "main": "embed.js",