@combos-fun/engine 0.1.13 → 0.1.14-beta.0

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.
@@ -1 +1 @@
1
- "use strict";var e=require("eventemitter3"),t=require("lodash-es"),s=require("resource-loader");function r(e){return e&&e.__esModule?e:{default:e}}var o,n=r(e);class a extends n.default{get game(){return this.gameObject?.scene?.game}constructor(e){super(),this.started=!1;const t=this.constructor;this.name=t.componentName,this.__componentDefaultParams=e}}exports.OBSERVER_TYPE=void 0,(o=exports.OBSERVER_TYPE||(exports.OBSERVER_TYPE={})).ADD="ADD",o.REMOVE="REMOVE",o.CHANGE="CHANGE";const i={},c={},p={},m={};function h(e,t){i[e.gameObject.id]||(i[e.gameObject.id]={});const s=i[e.gameObject.id],r=e.name+"_"+t.join(",");if(s[r])return s[r];const o=t.length-1;let n=e;for(let e=0;e<o;e++){if(void 0===n[t[e]]||null===n[t[e]])return{property:void 0,key:void 0};n=n[t[e]]}return s[r]={property:n,key:t[o]},s[r]}function u({systemName:e,componentName:t,component:s,prop:r,type:o,gameObject:n}){c[e]?.componentObserver?.add({component:s,prop:r,type:o,componentName:t,gameObject:n})}const l="GameObject";function d(e,t,s=exports.OBSERVER_TYPE.CHANGE){if(!e)return;const r={prop:[t],deep:!1};for(const o in p){const n=p[o]?.[l];n?.some(e=>e.prop[0]===t)&&u({systemName:o,componentName:l,component:void 0,gameObject:e,prop:r,type:s})}}function y({obj:e,key:s,prop:r,component:o,componentName:n}){if(void 0!==e)if(s in e){if(Object.defineProperty(e,`_${s}`,{enumerable:!1,writable:!0,value:e[s]}),r.deep&&t.isObject(e[s]))for(const t of Object.keys(e[s]))y({obj:e[s],key:t,prop:r,component:o,componentName:n});Object.defineProperty(e,s,{enumerable:!0,set(a){e[`_${s}`]!==a&&(e[`_${s}`]=a,function({prop:e,component:s,componentName:r}){for(const o in p){const n=(p[o]||{})[r];n&&(n.findIndex(s=>t.isEqual(s,e))>-1&&u({systemName:o,componentName:r,component:s,prop:e,type:exports.OBSERVER_TYPE.CHANGE}))}}({prop:r,component:o,componentName:n}))},get:()=>e[`_${s}`]})}else console.error(`prop ${s} not in component: ${n}, Can not observer`)}function f(e,t=e.name){for(const s in p){(p[s]||{})[t]&&c[s]?.componentObserver?.add({component:e,type:exports.OBSERVER_TYPE.REMOVE,componentName:t})}!function(e){e.gameObject&&delete i[e.gameObject.id]}(e)}let g=0;class E{constructor(e){this._parent=null,this._componentCache={},this.children=[],this.inScene=!1,this.components=[],this.destroyed=!1,this._name=e,this.id=++g}get parent(){return this._parent}get name(){return this._name}set scene(e){if(this._scene===e)return;const t=this._scene;this._scene=e;for(const t of this.children)t.scene=e;e?e.addGameObject(this):t&&t.removeGameObject(this)}get scene(){return this._scene}addChild(e){if(e&&e!==this){if(!(e instanceof E))throw new Error("addChild only receive GameObject");if(this.destroyed)throw new Error(`gameObject '${this.name}' has been destroy`);if(e.parent===this){const t=this.children.indexOf(e);return t>-1&&this.children.splice(t,1),void this.children.push(e)}e.parent&&e.parent.removeChild(e),e._parent=this,this.children.push(e),e.scene=this.scene,d(e,"parent",exports.OBSERVER_TYPE.CHANGE)}}removeChild(e){if(!(e instanceof E&&e.parent&&e.parent===this))return e;const t=this.children.indexOf(e);return t>-1&&this.children.splice(t,1),e._parent=null,e.scene=null,d(e,"parent",exports.OBSERVER_TYPE.CHANGE),e}addComponent(e,t){if(this.destroyed)return;const s=function(e){return e instanceof a?e.name:e instanceof Function?e.componentName:void 0}(e);if(this._componentCache[s])return;let r;if(e instanceof Function)r=new e(t);else{if(!(e instanceof a))throw new Error("addComponent recieve Component and Component Constructor");r=e}if(r.gameObject)throw new Error(`component has been added on gameObject ${r.gameObject.name}`);return r.gameObject=this,r.init&&r.init(r.__componentDefaultParams),function(e,t=e.name){for(const s in p)(p[s]||{})[t]&&c[s]?.componentObserver?.add({component:e,type:exports.OBSERVER_TYPE.ADD,componentName:t})}(r,r.name),function(e,t=e.name){if(t&&m[t]){if(!(e&&(s=e,s&&s.constructor&&"componentName"in s.constructor)))throw new Error("component param must be an instance of Component");var s;if(!e.gameObject||!e.gameObject.id)throw new Error("component should be add to a gameObject");for(const s of m[t]){const{property:r,key:o}=h(e,s.prop);y({obj:r,key:o,prop:s,component:e,componentName:t})}}}(r,r.name),this.components.push(r),this._componentCache[s]=r,r.awake&&r.awake(),r}removeComponent(e){let t;return"string"==typeof e?t=e:e instanceof a?t=e.name:e.componentName&&(t=e.componentName),this._removeComponent(t)}_removeComponent(e){const t=this.components.findIndex(({name:t})=>t===e);if(-1===t)return;const s=this.components.splice(t,1)[0];return delete this._componentCache[e],delete s.__componentDefaultParams,s.onDestroy&&s.onDestroy(),f(s,e),s.gameObject=void 0,s}getComponent(e){let t;return"string"==typeof e?t=e:e instanceof a?t=e.name:e.componentName&&(t=e.componentName),void 0!==this._componentCache[t]?this._componentCache[t]:void 0}remove(){if(this.parent)return this.parent.removeChild(this)}destroy(){if(this.destroyed)console.error("Cannot destroy gameObject that have already been destroyed.");else{Array.from(this.children).forEach(e=>{e.destroy()}),this.remove(),this.children.length=0;for(const e in this._componentCache)this._removeComponent(e);this.components.length=0,this.destroyed=!0}}}class b{constructor(){this.events=[]}add({component:e,prop:s,type:r,componentName:o,gameObject:n}){const a=n??e?.gameObject;if(r===exports.OBSERVER_TYPE.REMOVE){const t=t=>e?t.component===e:t.gameObject===a&&t.componentName===o;if(this.events.find(e=>t(e)&&e.type===exports.OBSERVER_TYPE.ADD))return void(this.events=this.events.filter(e=>!t(e)));this.events=this.events.filter(e=>!t(e))}const i=this.events.findIndex(n=>n.gameObject===a&&n.component===e&&n.componentName===o&&t.isEqual(n.prop,s)&&n.type===r);i>-1&&this.events.splice(i,1),this.events.push({gameObject:a,component:e,prop:s,type:r,componentName:o})}getChanged(){return this.events}get changed(){return this.events}clear(){const e=this.events;return this.events=[],e}}class S{constructor(e){this.started=!1,this.componentObserver=new b,this.__systemDefaultParams=e;const t=this.constructor;this.name=t.systemName}destroy(){this.componentObserver=null,this.__systemDefaultParams=null,this.onDestroy?.()}}const R=function(){let e=null;return e=Date.now?Date.now:()=>(new Date).getTime(),e}(),T={originTime:0,playbackRate:1};class O{constructor(e,t){e instanceof O&&(t=e,e={}),e=Object.assign({},T,e),t&&(this._parent=t),this._createTime=R(),this._timeMark=[{globalTime:this.globalTime,localTime:-e.originTime,entropy:-e.originTime,playbackRate:e.playbackRate,globalEntropy:0}],this._parent&&(this._timeMark[0].globalEntropy=this._parent.entropy),this._playbackRate=e.playbackRate}get globalTime(){return this.parent?this.parent.currentTime:R()-this._createTime}get parent(){return this._parent}get lastTimeMark(){return this._timeMark[this._timeMark.length-1]}markTime({time:e=this.currentTime,entropy:t=this.entropy,playbackRate:s=this.playbackRate}={}){const r={globalTime:this.globalTime,localTime:e,entropy:t,playbackRate:s,globalEntropy:this.globalEntropy};this._timeMark.push(r)}get currentTime(){const{localTime:e,globalTime:t}=this.lastTimeMark;return e+(this.globalTime-t)*this.playbackRate}set currentTime(e){this.markTime({time:e})}get globalEntropy(){return this._parent?this._parent.entropy:this.globalTime}get entropy(){const{entropy:e,globalEntropy:t}=this.lastTimeMark;return e+Math.abs((this.globalEntropy-t)*this.playbackRate)}set entropy(e){if(this.entropy>e){const t=this.seekTimeMark(e);this._timeMark.length=t+1}this.markTime({entropy:e})}fork(e){return new O(e,this)}seekGlobalTime(e){const t=this.seekTimeMark(e),s=this._timeMark[t],{entropy:r,playbackRate:o,globalTime:n}=s;return n+(e-r)/Math.abs(o)}seekLocalTime(e){const t=this.seekTimeMark(e),s=this._timeMark[t],{localTime:r,entropy:o,playbackRate:n}=s;return n>0?r+(e-o):r-(e-o)}seekTimeMark(e){const t=this._timeMark;let s=0,r=t.length-1;if(e<=t[s].entropy)return s;if(e>=t[r].entropy)return r;let o=Math.floor((s+r)/2);for(;o>s&&o<r;){if(e===t[o].entropy)return o;e<t[o].entropy?r=o:e>t[o].entropy&&(s=o),o=Math.floor((s+r)/2)}return s}get playbackRate(){return this._playbackRate}set playbackRate(e){e!==this.playbackRate&&(this.markTime({playbackRate:e}),this._playbackRate=e)}get paused(){if(0===this.playbackRate)return!0;let e=this.parent;for(;e;){if(0===e.playbackRate)return!0;e=e.parent}return!1}}const _={autoStart:!0,frameRate:60};class x{constructor(e){e=Object.assign({},_,e),this._frameCount=0,this._frameDuration=1e3/e.frameRate,this.autoStart=e.autoStart,this.frameRate=e.frameRate,this.timeline=new O({originTime:0,playbackRate:1}),this._lastFrameTime=this.timeline.currentTime,this._tickers=new Set,this._requestId=null,this._ticker=()=>{this._started&&(this._requestId=requestAnimationFrame(this._ticker),this.update())},this.autoStart&&this.start()}update(){const e=this.timeline.currentTime,t=e-this._lastFrameTime;if(t>=this._frameDuration){const s=e-t%this._frameDuration,r=s-this._lastFrameTime;this._lastFrameTime=s;const o={deltaTime:r,delta:r,time:s,currentTime:s,frameCount:++this._frameCount,fps:Math.round(1e3/r)};for(const e of this._tickers)"function"==typeof e&&e(o)}}add(e){this._tickers.add(e)}remove(e){this._tickers.delete(e)}start(){this._started||(this._started=!0,this.timeline.playbackRate=1,this._requestId=requestAnimationFrame(this._ticker))}pause(){this._started=!1,this.timeline.playbackRate=0}setPlaybackRate(e){this.timeline.playbackRate=e}}class L extends E{constructor(e){super(e),this.gameObjects=[],this.scene=this}addGameObject(e){this.gameObjects.push(e),e.inScene||(e.inScene=!0,d(e,"inScene",exports.OBSERVER_TYPE.CHANGE))}removeGameObject(e){const t=this.gameObjects.indexOf(e);-1!==t&&(e.inScene&&(e.inScene=!1,d(e,"inScene",exports.OBSERVER_TYPE.CHANGE)),this.gameObjects.splice(t,1))}destroy(){this.scene=null,super.destroy(),this.gameObjects=null,this.canvas=null}}const k="0.1.13",v="combos-game:plugin-init-success",w="combos-game:ready",A="combos-game:set-playing",M="combos-game:state-changed";function C(e,t){if("undefined"!=typeof window&&window.parent&&window.parent!==window)try{window.parent.postMessage(e,t)}catch{}}function N(e,t="*"){C({type:v,systemName:e.systemName,engineVersion:k,...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{}},t)}function j(e,t="*"){C({type:w,engineVersion:k,...void 0===e?{}:{error:e instanceof Error?e.message:String(e)}},t)}function P(e,t="*"){C({type:M,playing:e.playing,started:e.started},t)}function X(e){if(!e||"object"!=typeof e)return null;const t=e;return t.type!==A||"boolean"!=typeof t.playing?null:t.playing}const I=["knoffice.tech","converge.ai"];function D(e,t){if(t.includes("*"))return!0;if(0===t.length)return!1;let s;try{s=new URL(e)}catch{return!1}const r=e.toLowerCase(),o=s.hostname.toLowerCase();for(const e of t){const t=e.trim();if(!t)continue;if(t.includes("://")){if(r===t.toLowerCase())return!0;continue}const s=t.toLowerCase().replace(/^\./,"");if(o===s||o.endsWith(`.${s}`))return!0}return!1}function V(e){if(!e?.length)return[...I];if(e.includes("*"))return["*"];const t=new Set,s=[];for(const r of[...I,...e]){const e=r.trim();e&&!t.has(e)&&(t.add(e),s.push(e))}return s}function G(e){if("systemName"in e){const t=e.systemName;if("string"==typeof t)return t}return"UnknownSystem"}function $(e){const t=e;return{packageName:"string"==typeof t.packageName?t.packageName:void 0,packageVersion:"string"==typeof t.packageVersion?t.packageVersion:void 0}}var B;exports.LOAD_SCENE_MODE=void 0,(B=exports.LOAD_SCENE_MODE||(exports.LOAD_SCENE_MODE={})).SINGLE="SINGLE",B.MULTI_CANVAS="MULTI_CANVAS";const U=e=>{if((e instanceof S||e instanceof a)&&!e.started){e.started=!0;try{e.start&&e.start()}catch(t){e instanceof a?console.error(`${function(e){if("componentName"in e){const t=e.componentName;if("string"==typeof t)return t}return"UnknownComponent"}(e.constructor)} start error`,t):console.error(`${G(e.constructor)} start error`,t)}}};class H extends n.default{constructor({systems:e,frameRate:t=60,autoStart:s=!0,needScene:r=!0,onSystemsBootstrapComplete:o,pluginInitNotifyTargetOrigin:n="*",allowedMessageOrigins:a}={}){if(super(),this.playing=!1,this.started=!1,this.multiScenes=[],this.systems=[],this.pluginInitNotifyTargetOrigin="*",this.allowedMessageOrigins=V(),this.onHostMessage=e=>{if(!D(e.origin,this.allowedMessageOrigins))return;const t=X(e.data);null!==t&&this.setPlaying(t)},this.pluginInitNotifyTargetOrigin=n,this.allowedMessageOrigins=V(a),this.ticker=new x({autoStart:!1,frameRate:t}),this.initTicker(),"undefined"!=typeof window&&window.addEventListener("message",this.onHostMessage),e&&e.length){const t=[...e];this.bootstrapSystemsAndMaybeStart(t,r,s,o)}else o?.(this),this.notifyReady()}setPlaying(e){e?this.started?this.resume():this.start():this.pause()}notifyReady(e){j(e,this.pluginInitNotifyTargetOrigin)}flushObservedComponents(){for(const e of this.systems)try{e.update?.()}catch(t){console.error(`${G(e.constructor)} update error`,t)}}notifyStateChanged(){P({playing:this.playing,started:this.started},this.pluginInitNotifyTargetOrigin)}async bootstrapSystemsAndMaybeStart(e,t,s,r){let o;try{for(const t of e)await this.addSystem(t);t&&this.loadScene({scene:new L("scene")})}catch(e){o=e,console.error("Game bootstrap failed",e)}try{await Promise.resolve(r?.(this,o))}catch(e){o=o??e,console.error("onSystemsBootstrapComplete failed",e)}if(!o)try{this.flushObservedComponents();for(const e of this.systems)await Promise.resolve(e.beforeReady?.())}catch(e){o=e,console.error("Game beforeReady failed",e)}!o&&s&&this.start(),this.notifyReady(o)}get scene(){return this._scene}set scene(e){this._scene=e}get gameObjects(){return(e=>{const t=e?.scene?.gameObjects||[],s=e?.multiScenes.map(({gameObjects:e})=>e);let r=[];for(const e of s)r=[...r,...e];return[...t,...r]})(this)}async addSystem(e,s){let r;if(e instanceof Function)r=new e(s);else{if(!(e instanceof S))return void console.warn("can only add System");r=e}if(!this.systems.find(e=>e.constructor===r.constructor)){r.game=this,r.init&&await Promise.resolve(r.init(r.__systemDefaultParams)),N({systemName:G(r.constructor),...$(r.constructor)},this.pluginInitNotifyTargetOrigin),function(e,t){p[t.systemName]=t.observerInfo,c[t.systemName]=e}(r,r.constructor),function(e){const s=[];e instanceof Array?s.push(...e):s.push(e);for(const e of s)for(const s in e.observerInfo){m[s]=m[s]||[];const r=m[s];for(const o of e.observerInfo[s])-1===r.findIndex(e=>t.isEqual(e,o))&&m[s].push(o)}}(r.constructor);try{r.awake&&r.awake()}catch(e){console.error(`${G(r.constructor)} awake error`,e)}return this.systems.push(r),r}console.warn(`${G(r.constructor)} System has been added`)}removeSystem(e){if(!e)return;let t=-1;"string"==typeof e?t=this.systems.findIndex(t=>t.name===e):e instanceof Function?t=this.systems.findIndex(t=>t.constructor===e):e instanceof S&&(t=this.systems.findIndex(t=>t===e)),t>-1&&(this.systems[t].destroy&&this.systems[t].destroy(),this.systems.splice(t,1))}getSystem(e){return this.systems.find(t=>"string"==typeof e?t.name===e:t instanceof e)}pause(){this.playing&&(this.playing=!1,this.ticker.pause(),this.triggerPause(),this.notifyStateChanged())}start(){this.playing||(this.playing=!0,this.started=!0,this.ticker.start(),this.notifyStateChanged())}resume(){this.playing||(this.playing=!0,this.ticker.start(),this.triggerResume(),this.notifyStateChanged())}initTicker(){this.ticker.add(e=>{this.scene&&((e,t=[])=>{for(const s of t)for(const t of s.components)try{U(t),t.update&&t.update(e)}catch(e){console.error(`gameObject: ${s.name} ${t.name} update error`,e)}for(const s of t)for(const t of s.components)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`gameObject: ${s.name} ${t.name} lateUpdate error`,e)}})(e,this.gameObjects);for(const t of this.systems)try{U(t),t.update&&t.update(e)}catch(e){console.error(`${G(t.constructor)} update error`,e)}for(const t of this.systems)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`${G(t.constructor)} lateUpdate error`,e)}})}triggerResume(){(e=>{for(const t of e)for(const e of t.components)try{e.onResume&&e.onResume()}catch(s){console.error(`gameObject: ${t.name}, ${e.name}, onResume error`,s)}})(this.gameObjects);for(const e of this.systems)try{e.onResume&&e.onResume()}catch(t){console.error(`${G(e.constructor)}, onResume error`,t)}}triggerPause(){(e=>{for(const t of e)for(const e of t.components)try{e.onPause&&e.onPause()}catch(s){console.error(`gameObject: ${t.name}, ${e.name}, onPause error`,s)}})(this.gameObjects);for(const e of this.systems)try{e.onPause&&e.onPause()}catch(t){console.error(`${G(e.constructor)}, onPause error`,t)}}destroySystems(){for(const e of[...this.systems])this.removeSystem(e);this.systems.length=0}destroy(){"undefined"!=typeof window&&window.removeEventListener("message",this.onHostMessage),this.removeAllListeners(),this.pause(),this.scene.destroy(),this.destroySystems(),this.ticker=null,this.scene=null,this.canvas=null,this.multiScenes=null}loadScene({scene:e,mode:t=exports.LOAD_SCENE_MODE.SINGLE,params:s={}}){if(e){switch(e.game=this,t){case exports.LOAD_SCENE_MODE.SINGLE:this.scene=e;break;case exports.LOAD_SCENE_MODE.MULTI_CANVAS:this.multiScenes.push(e)}this.emit("sceneChanged",{scene:e,mode:t,params:s})}}}function Y(e,t){e.constructor.IDEProps||(e.constructor.IDEProps=[]),e.constructor.IDEProps.push(t)}function F(e={}){return function(t){if(!t.observerInfo){for(const t in e)for(const s in e[t]){let r;"string"==typeof e[t][s]&&(e[t][s]=[e[t][s]]),Array.isArray(e[t][s])&&(r={prop:e[t][s],deep:!1},e[t][s]=r),r=e[t][s],"string"==typeof r.prop&&(r.prop=[r.prop])}t.observerInfo=e}}}var q;exports.LOAD_EVENT=void 0,(q=exports.LOAD_EVENT||(exports.LOAD_EVENT={})).START="start",q.PROGRESS="progress",q.LOADED="loaded",q.COMPLETE="complete",q.ERROR="error";class z extends n.default{constructor({resource:e,resourceTotal:t}){super(),this.progress=0,this.resourceTotal=0,this.resourceLoadedCount=0,this.resource=e,this.resourceTotal=t,0===t&&this.resource.emit(exports.LOAD_EVENT.COMPLETE,this)}onStart(){this.resource.emit(exports.LOAD_EVENT.START,this)}onProgress(e){this.resourceLoadedCount++,this.progress=Math.floor(this.resourceLoadedCount/this.resourceTotal*100)/100,e.success?this.resource.emit(exports.LOAD_EVENT.LOADED,this,e):this.resource.emit(exports.LOAD_EVENT.ERROR,this,e),this.resource.emit(exports.LOAD_EVENT.PROGRESS,this,e),this.resourceLoadedCount===this.resourceTotal&&this.resource.emit(exports.LOAD_EVENT.COMPLETE,this)}}const J={image:"png",json:"json",tex:"tex",ske:"ske",audio:"audio",video:"video",model:"glb",mtl:"mtl",bin:"bin",vertex:"vert",fragment:"frag"},W={png:"png",jpg:"jpg",jpeg:"jpeg",webp:"webp",json:"json",tex:"tex",ske:"ske",mp3:"audio",wav:"audio",aac:"audio",ogg:"audio",mp4:"video",webm:"video",glb:"glb",gltf:"gltf",fbx:"fbx",obj:"obj",mtl:"mtl",stl:"stl",dae:"dae",ply:"ply",bin:"bin",vert:"vert",frag:"frag",glsl:"glsl"};function K(e,t){return W[function(e){const t=e.split("?")[0].split("#")[0],s=t.lastIndexOf(".");return s<0?"":t.slice(s+1).toLowerCase()}(e)]||J[t]||"png"}function Q(e,t,s){if("string"==typeof t){const r=t.trim();if(!r)throw Z(s,e);return{type:K(r,e),url:r}}if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Resource "${s}" src.${e} must be a url string or { type, url }.`);const r=t;if("data"===r.type)return r;const o="string"==typeof r.url?r.url.trim():"";if(!o)throw Z(s,e);return{...r,type:r.type||K(o,e),url:o}}function Z(e,t){return new Error(`Resource "${e}" src.${t}.url is required. Use { type, url } (e.g. { type: "webp", url: "https://..." }). A flat path string is also accepted and will be normalized.`)}function ee(e,t,s="(unnamed)"){if(null==e)throw new Error(`Resource "${s}" src is required.`);if("string"==typeof e){const r=function(e){return"AUDIO"===e?"audio":"VIDEO"===e?"video":"MODEL"===e||"GLB"===e?"model":"SHADER"===e?"fragment":"image"}(t);return{[r]:Q(r,e,s)}}if("object"!=typeof e||Array.isArray(e))throw new Error(`Resource "${s}" src must be a url string or a slot object.`);const r={};for(const[t,o]of Object.entries(e))null!=o&&(r[t]=Q(t,o,s));if(0===Object.keys(r).length)throw new Error(`Resource "${s}" src has no loadable slots.`);return r}const te={AbstractLoadStrategy:s.AbstractLoadStrategy,AudioLoadStrategy:s.AudioLoadStrategy,ImageLoadStrategy:s.ImageLoadStrategy,XhrResponseType:s.XhrResponseType,MediaElementLoadStrategy:s.MediaElementLoadStrategy,VideoLoadStrategy:s.VideoLoadStrategy,XhrLoadStrategy:s.XhrLoadStrategy,Loader:s.Loader,Resource:s.Resource,ResourceType:s.ResourceType,ResourceState:s.ResourceState};function se(e){const t=e.frame;return t&&"object"==typeof t?{...e,frame:t,rotated:Boolean(e.rotated),trimmed:Boolean(e.trimmed),spriteSourceSize:e.spriteSourceSize,sourceSize:e.sourceSize}:null}function re(e,t,s){for(const r of e){if(!r||"object"!=typeof r)continue;const e=r,o=String(e.filename||e.name||"");if(!o)continue;const n=se(e);if(!n)continue;t[o]=n;const a=o.lastIndexOf("/");if(a>0){const e=o.slice(0,a);s[e]||(s[e]=[]),s[e].includes(o)||s[e].push(o)}}}var oe;exports.RESOURCE_TYPE=void 0,(oe=exports.RESOURCE_TYPE||(exports.RESOURCE_TYPE={})).IMAGE="IMAGE",oe.SPRITE="SPRITE",oe.SPRITE_ANIMATION="SPRITE_ANIMATION",oe.AUDIO="AUDIO",oe.VIDEO="VIDEO",oe.GLB="GLB",oe.MODEL="MODEL",oe.SHADER="SHADER",s.XhrLoadStrategy.setExtensionXhrType("json",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("tex",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("ske",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("mp3",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("wav",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("aac",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("ogg",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("glb",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("gltf",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("fbx",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("stl",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("ply",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("bin",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("obj",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("mtl",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("dae",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("vert",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("frag",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("glsl",s.XhrResponseType.Text);const ne={png:s.ImageLoadStrategy,jpg:s.ImageLoadStrategy,jpeg:s.ImageLoadStrategy,webp:s.ImageLoadStrategy,json:s.XhrLoadStrategy,tex:s.XhrLoadStrategy,ske:s.XhrLoadStrategy,audio:s.XhrLoadStrategy,video:s.VideoLoadStrategy,glb:s.XhrLoadStrategy,gltf:s.XhrLoadStrategy,fbx:s.XhrLoadStrategy,obj:s.XhrLoadStrategy,mtl:s.XhrLoadStrategy,stl:s.XhrLoadStrategy,dae:s.XhrLoadStrategy,ply:s.XhrLoadStrategy,bin:s.XhrLoadStrategy,vert:s.XhrLoadStrategy,frag:s.XhrLoadStrategy,glsl:s.XhrLoadStrategy};class ae extends n.default{constructor(e){super(),this.timeout=6e3,this.preProcessResourceHandlers=[],this.resourcesMap={},this.makeInstanceFunctions={},this.destroyInstanceFunctions={},this.promiseMap={},this.loaders=[],e&&"number"==typeof e.timeout&&(this.timeout=e.timeout)}loadConfig(e){this.addResource(e),this.preload()}loadSingle(e){return this.addResource([e]),this.getResource(e.name)}addResource(e){if(!e||e.length<1)console.warn("no resources");else for(const t of e)this.resourcesMap[t.name]?console.warn(t.name+" was already added"):this.resourcesMap[t.name]={...t,src:ee(t.src,String(t.type),t.name),data:{}}}addPreProcessResourceHandler(e){this.preProcessResourceHandlers.push(e)}removePreProcessResourceHandler(e){this.preProcessResourceHandlers.splice(this.preProcessResourceHandlers.indexOf(e),1)}preload(){const e=[];for(const t in this.resourcesMap){const s=this.resourcesMap[t];!s.preload||s.complete||this.promiseMap[t]||e.push(s.name)}this.progress=new z({resource:this,resourceTotal:e.length}),this.loadResource({names:e,preload:!0})}async getResource(e){return this.loadResource({names:[e]}),this.promiseMap[e]||Promise.resolve({})}async instance(e){const t=this.resourcesMap[e];return this.makeInstanceFunctions[t.type]&&await this.makeInstanceFunctions[t.type](t)}async destroy(e){await this._destroy(e)}async _destroy(e,t=!1){const s=this.resourcesMap[e];if(s){if(!t)try{this.destroyInstanceFunctions[s.type]&&await this.destroyInstanceFunctions[s.type](s)}catch(e){console.warn(`destroy resource ${s.name} error with '${e.message}'`)}delete this.promiseMap[e],s.data={},s.complete=!1,s.instance=void 0}}registerResourceType(e,t=e){if(exports.RESOURCE_TYPE[e])throw new Error(`The type ${e} already exists in RESOURCE_TYPE`);exports.RESOURCE_TYPE[e]=t}registerInstance(e,t){this.makeInstanceFunctions[e]=t}registerDestroy(e,t){this.destroyInstanceFunctions[e]=t}loadResource({names:e=[],preload:t=!1}){const s=e.filter(e=>!this.promiseMap[e]&&this.resourcesMap[e]);if(!s.length)return;const r={},o=this.getLoader(t);s.forEach(e=>{this.promiseMap[e]=new Promise(t=>r[e]=t);const s=this.resourcesMap[e];for(const e of this.preProcessResourceHandlers)e(s);s.src=ee(s.src,String(s.type),s.name);for(const n in s.src){const a=s.src[n].type;"data"===a?(s.data[n]=s.src[n].data,this.doComplete(e,r[e],t)):o.add({url:s.src[n].url,name:`${s.name}_${n}`,strategy:ne[a],metadata:{key:n,name:s.name,resolves:r}})}}),o.load()}async doComplete(e,t,s=!1){const r=this.resourcesMap[e],o={name:e,resource:this.resourcesMap[e],success:!0};if(this.checkAllLoaded(e))try{r.instance=await this.instance(e),r.complete=!0,s&&this.progress.onProgress(o),t(r)}catch(e){console.error(e),r.complete=!1,s&&(o.errMsg=e.message,o.success=!1,this.progress.onProgress(o)),t({})}}checkAllLoaded(e){const t=this.resourcesMap[e];return Array.from(Object.keys(t.src)).every(e=>t.data[e])}getLoader(e=!1){let t=this.loaders.find(({loading:e})=>!e);return t||(t=new s.Loader,this.loaders.push(t)),e&&t.onStart.once(()=>{this.progress.onStart()}),t.onLoad.add((t,s)=>{this.onLoad({preload:e,resource:s})}),t.onError.add((t,s,r)=>{this.onError({errMsg:t,resource:r,preload:e})}),t.onComplete.once(()=>{t.onLoad.detachAll(),t.onError.detachAll(),t.reset()}),t}async onLoad({preload:e=!1,resource:t}){const{metadata:{key:s,name:r,resolves:o},data:n}=t;this.resourcesMap[r].data[s]=n,this.doComplete(r,o[r],e)}async onError({errMsg:e,preload:t=!1,resource:s}){const{metadata:{name:r,resolves:o}}=s;if(this._destroy(r,!0),o[r]({}),t){const t={name:r,resource:this.resourcesMap[r],success:!1,errMsg:e};this.progress.onProgress(t)}}}const ie=new ae;ie.registerInstance(exports.RESOURCE_TYPE.SHADER,e=>({vertex:"string"==typeof e.data?.vertex?e.data.vertex:"",fragment:"string"==typeof e.data?.fragment?e.data.fragment:""}));const ce={IDEProp:Y,componentObserver:F};console.log(`@combos-fun/engine version: ${k}`),exports.COMBOS_GAME_PLUGIN_INIT_SUCCESS=v,exports.COMBOS_GAME_READY=w,exports.COMBOS_GAME_SET_PLAYING=A,exports.COMBOS_GAME_STATE_CHANGED=M,exports.Component=a,exports.DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES=I,exports.Game=H,exports.GameObject=E,exports.IDEProp=Y,exports.RESOURCE_TYPE_STRATEGY=ne,exports.Scene=L,exports.System=S,exports.componentObserver=F,exports.decorators=ce,exports.isAllowedMessageOrigin=D,exports.mergeAllowedMessageOrigins=V,exports.normalizeResourceSrc=ee,exports.normalizeSpritesheetData=function(e){if(!e||"object"!=typeof e)return{frames:{},animations:{},meta:{scale:1}};const t=e;if(function(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}(t.frames))return{...t,frames:t.frames,animations:{...t.animations||{}},meta:{scale:1,...t.meta||{}}};const s={},r={...t.animations||{}};if(Array.isArray(t.textures)){for(const e of t.textures)e&&"object"==typeof e&&Array.isArray(e.frames)&&re(e.frames,s,r);const e=t.textures[0]||{},o=e.scale??t.meta?.scale??1;return{frames:s,animations:r,meta:{scale:"number"==typeof o||"string"==typeof o?o:1,image:"string"==typeof e.image?e.image:void 0,size:e.size,format:e.format,...t.meta||{}}}}return Array.isArray(t.frames)?(re(t.frames,s,r),{frames:s,animations:r,meta:{scale:1,...t.meta||{}}}):{frames:{},animations:r,meta:{scale:1,...t.meta||{}}}},exports.parseSetPlayingMessage=X,exports.postParentGameReady=j,exports.postParentGameState=P,exports.postParentPluginInitSuccess=N,exports.resource=ie,exports.resourceLoader=te,exports.version=k;
1
+ "use strict";var e=require("eventemitter3"),t=require("lodash-es"),s=require("resource-loader");function r(e){return e&&e.__esModule?e:{default:e}}var o,n=r(e);class a extends n.default{get game(){return this.gameObject?.scene?.game}constructor(e){super(),this.started=!1;const t=this.constructor;this.name=t.componentName,this.__componentDefaultParams=e}}exports.OBSERVER_TYPE=void 0,(o=exports.OBSERVER_TYPE||(exports.OBSERVER_TYPE={})).ADD="ADD",o.REMOVE="REMOVE",o.CHANGE="CHANGE";const i={},c={},p={},h={};function m(e,t){i[e.gameObject.id]||(i[e.gameObject.id]={});const s=i[e.gameObject.id],r=e.name+"_"+t.join(",");if(s[r])return s[r];const o=t.length-1;let n=e;for(let e=0;e<o;e++){if(void 0===n[t[e]]||null===n[t[e]])return{property:void 0,key:void 0};n=n[t[e]]}return s[r]={property:n,key:t[o]},s[r]}function l({systemName:e,componentName:t,component:s,prop:r,type:o,gameObject:n}){c[e]?.componentObserver?.add({component:s,prop:r,type:o,componentName:t,gameObject:n})}const u="GameObject";function d(e,t,s=exports.OBSERVER_TYPE.CHANGE){if(!e)return;const r={prop:[t],deep:!1};for(const o in p){const n=p[o]?.[u];n?.some(e=>e.prop[0]===t)&&l({systemName:o,componentName:u,component:void 0,gameObject:e,prop:r,type:s})}}function f({obj:e,key:s,prop:r,component:o,componentName:n}){if(void 0!==e)if(s in e){if(Object.defineProperty(e,`_${s}`,{enumerable:!1,writable:!0,value:e[s]}),r.deep&&t.isObject(e[s]))for(const t of Object.keys(e[s]))f({obj:e[s],key:t,prop:r,component:o,componentName:n});Object.defineProperty(e,s,{enumerable:!0,set(a){e[`_${s}`]!==a&&(e[`_${s}`]=a,function({prop:e,component:s,componentName:r}){for(const o in p){const n=(p[o]||{})[r];n&&(n.findIndex(s=>t.isEqual(s,e))>-1&&l({systemName:o,componentName:r,component:s,prop:e,type:exports.OBSERVER_TYPE.CHANGE}))}}({prop:r,component:o,componentName:n}))},get:()=>e[`_${s}`]})}else console.error(`prop ${s} not in component: ${n}, Can not observer`)}function y(e,t=e.name){for(const s in p){(p[s]||{})[t]&&c[s]?.componentObserver?.add({component:e,type:exports.OBSERVER_TYPE.REMOVE,componentName:t})}!function(e){e.gameObject&&delete i[e.gameObject.id]}(e)}let g=0;class E{constructor(e){this._parent=null,this._componentCache={},this.children=[],this.inScene=!1,this.components=[],this.destroyed=!1,this._name=e,this.id=++g}get parent(){return this._parent}get name(){return this._name}set scene(e){if(this._scene===e)return;const t=this._scene;this._scene=e;for(const t of this.children)t.scene=e;e?e.addGameObject(this):t&&t.removeGameObject(this)}get scene(){return this._scene}addChild(e){if(e&&e!==this){if(!(e instanceof E))throw new Error("addChild only receive GameObject");if(this.destroyed)throw new Error(`gameObject '${this.name}' has been destroy`);if(e.parent===this){const t=this.children.indexOf(e);return t>-1&&this.children.splice(t,1),void this.children.push(e)}e.parent&&e.parent.removeChild(e),e._parent=this,this.children.push(e),e.scene=this.scene,d(e,"parent",exports.OBSERVER_TYPE.CHANGE)}}removeChild(e){if(!(e instanceof E&&e.parent&&e.parent===this))return e;const t=this.children.indexOf(e);return t>-1&&this.children.splice(t,1),e._parent=null,e.scene=null,d(e,"parent",exports.OBSERVER_TYPE.CHANGE),e}addComponent(e,t){if(this.destroyed)return;const s=function(e){return e instanceof a?e.name:e instanceof Function?e.componentName:void 0}(e);if(this._componentCache[s])return;let r;if(e instanceof Function)r=new e(t);else{if(!(e instanceof a))throw new Error("addComponent recieve Component and Component Constructor");r=e}if(r.gameObject)throw new Error(`component has been added on gameObject ${r.gameObject.name}`);return r.gameObject=this,r.init&&r.init(r.__componentDefaultParams),function(e,t=e.name){for(const s in p)(p[s]||{})[t]&&c[s]?.componentObserver?.add({component:e,type:exports.OBSERVER_TYPE.ADD,componentName:t})}(r,r.name),function(e,t=e.name){if(t&&h[t]){if(!(e&&(s=e,s&&s.constructor&&"componentName"in s.constructor)))throw new Error("component param must be an instance of Component");var s;if(!e.gameObject||!e.gameObject.id)throw new Error("component should be add to a gameObject");for(const s of h[t]){const{property:r,key:o}=m(e,s.prop);f({obj:r,key:o,prop:s,component:e,componentName:t})}}}(r,r.name),this.components.push(r),this._componentCache[s]=r,r.awake&&r.awake(),r}removeComponent(e){let t;return"string"==typeof e?t=e:e instanceof a?t=e.name:e.componentName&&(t=e.componentName),this._removeComponent(t)}_removeComponent(e){const t=this.components.findIndex(({name:t})=>t===e);if(-1===t)return;const s=this.components.splice(t,1)[0];return delete this._componentCache[e],delete s.__componentDefaultParams,s.onDestroy&&s.onDestroy(),y(s,e),s.gameObject=void 0,s}getComponent(e){let t;return"string"==typeof e?t=e:e instanceof a?t=e.name:e.componentName&&(t=e.componentName),void 0!==this._componentCache[t]?this._componentCache[t]:void 0}remove(){if(this.parent)return this.parent.removeChild(this)}destroy(){if(this.destroyed)console.error("Cannot destroy gameObject that have already been destroyed.");else{Array.from(this.children).forEach(e=>{e.destroy()}),this.remove(),this.children.length=0;for(const e in this._componentCache)this._removeComponent(e);this.components.length=0,this.destroyed=!0}}}class b{constructor(){this.events=[]}add({component:e,prop:s,type:r,componentName:o,gameObject:n}){const a=n??e?.gameObject;if(r===exports.OBSERVER_TYPE.REMOVE){const t=t=>e?t.component===e:t.gameObject===a&&t.componentName===o;if(this.events.find(e=>t(e)&&e.type===exports.OBSERVER_TYPE.ADD))return void(this.events=this.events.filter(e=>!t(e)));this.events=this.events.filter(e=>!t(e))}const i=this.events.findIndex(n=>n.gameObject===a&&n.component===e&&n.componentName===o&&t.isEqual(n.prop,s)&&n.type===r);i>-1&&this.events.splice(i,1),this.events.push({gameObject:a,component:e,prop:s,type:r,componentName:o})}getChanged(){return this.events}get changed(){return this.events}clear(){const e=this.events;return this.events=[],e}}class R{constructor(e){this.started=!1,this.componentObserver=new b,this.__systemDefaultParams=e;const t=this.constructor;this.name=t.systemName}destroy(){this.componentObserver=null,this.__systemDefaultParams=null,this.onDestroy?.()}}const S=function(){let e=null;return e=Date.now?Date.now:()=>(new Date).getTime(),e}(),x={originTime:0,playbackRate:1};class T{constructor(e,t){e instanceof T&&(t=e,e={}),e=Object.assign({},x,e),t&&(this._parent=t),this._createTime=S(),this._timeMark=[{globalTime:this.globalTime,localTime:-e.originTime,entropy:-e.originTime,playbackRate:e.playbackRate,globalEntropy:0}],this._parent&&(this._timeMark[0].globalEntropy=this._parent.entropy),this._playbackRate=e.playbackRate}get globalTime(){return this.parent?this.parent.currentTime:S()-this._createTime}get parent(){return this._parent}get lastTimeMark(){return this._timeMark[this._timeMark.length-1]}markTime({time:e=this.currentTime,entropy:t=this.entropy,playbackRate:s=this.playbackRate}={}){const r={globalTime:this.globalTime,localTime:e,entropy:t,playbackRate:s,globalEntropy:this.globalEntropy};this._timeMark.push(r)}get currentTime(){const{localTime:e,globalTime:t}=this.lastTimeMark;return e+(this.globalTime-t)*this.playbackRate}set currentTime(e){this.markTime({time:e})}get globalEntropy(){return this._parent?this._parent.entropy:this.globalTime}get entropy(){const{entropy:e,globalEntropy:t}=this.lastTimeMark;return e+Math.abs((this.globalEntropy-t)*this.playbackRate)}set entropy(e){if(this.entropy>e){const t=this.seekTimeMark(e);this._timeMark.length=t+1}this.markTime({entropy:e})}fork(e){return new T(e,this)}seekGlobalTime(e){const t=this.seekTimeMark(e),s=this._timeMark[t],{entropy:r,playbackRate:o,globalTime:n}=s;return n+(e-r)/Math.abs(o)}seekLocalTime(e){const t=this.seekTimeMark(e),s=this._timeMark[t],{localTime:r,entropy:o,playbackRate:n}=s;return n>0?r+(e-o):r-(e-o)}seekTimeMark(e){const t=this._timeMark;let s=0,r=t.length-1;if(e<=t[s].entropy)return s;if(e>=t[r].entropy)return r;let o=Math.floor((s+r)/2);for(;o>s&&o<r;){if(e===t[o].entropy)return o;e<t[o].entropy?r=o:e>t[o].entropy&&(s=o),o=Math.floor((s+r)/2)}return s}get playbackRate(){return this._playbackRate}set playbackRate(e){e!==this.playbackRate&&(this.markTime({playbackRate:e}),this._playbackRate=e)}get paused(){if(0===this.playbackRate)return!0;let e=this.parent;for(;e;){if(0===e.playbackRate)return!0;e=e.parent}return!1}}const O={autoStart:!0,frameRate:60};class _{constructor(e){e=Object.assign({},O,e),this._frameCount=0,this._frameDuration=1e3/e.frameRate,this.autoStart=e.autoStart,this.frameRate=e.frameRate,this.timeline=new T({originTime:0,playbackRate:1}),this._lastFrameTime=this.timeline.currentTime,this._tickers=new Set,this._requestId=null,this._ticker=()=>{this._started&&(this._requestId=requestAnimationFrame(this._ticker),this.update())},this.autoStart&&this.start()}update(){const e=this.timeline.currentTime,t=e-this._lastFrameTime;if(t>=this._frameDuration){const s=e-t%this._frameDuration,r=s-this._lastFrameTime;this._lastFrameTime=s;const o={deltaTime:r,delta:r,time:s,currentTime:s,frameCount:++this._frameCount,fps:Math.round(1e3/r)};for(const e of this._tickers)"function"==typeof e&&e(o)}}add(e){this._tickers.add(e)}remove(e){this._tickers.delete(e)}start(){this._started||(this._started=!0,this.timeline.playbackRate=1,this._requestId=requestAnimationFrame(this._ticker))}pause(){this._started=!1,this.timeline.playbackRate=0}setPlaybackRate(e){this.timeline.playbackRate=e}}class v extends E{constructor(e){super(e),this.gameObjects=[],this.scene=this}addGameObject(e){this.gameObjects.push(e),e.inScene||(e.inScene=!0,d(e,"inScene",exports.OBSERVER_TYPE.CHANGE))}removeGameObject(e){const t=this.gameObjects.indexOf(e);-1!==t&&(e.inScene&&(e.inScene=!1,d(e,"inScene",exports.OBSERVER_TYPE.CHANGE)),this.gameObjects.splice(t,1))}destroy(){this.scene=null,super.destroy(),this.gameObjects=null,this.canvas=null}}const k="0.1.14-beta.0",L="combos-game:plugin-init-success",w="combos-game:ready",M="combos-game:set-playing",A="combos-game:state-changed";function P(e,t){if("undefined"!=typeof window&&window.parent&&window.parent!==window)try{window.parent.postMessage(e,t)}catch{}}function C(e,t="*"){P({type:L,systemName:e.systemName,engineVersion:k,...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{}},t)}function N(e,t="*"){P({type:w,engineVersion:k,...void 0===e?{}:{error:e instanceof Error?e.message:String(e)}},t)}function j(e,t="*"){P({type:A,playing:e.playing,started:e.started},t)}function X(e){if(!e||"object"!=typeof e)return null;const t=e;return t.type!==M||"boolean"!=typeof t.playing?null:t.playing}const D=["knoffice.tech","converge.ai"];function I(e,t){if(t.includes("*"))return!0;if(0===t.length)return!1;let s;try{s=new URL(e)}catch{return!1}const r=e.toLowerCase(),o=s.hostname.toLowerCase();for(const e of t){const t=e.trim();if(!t)continue;if(t.includes("://")){if(r===t.toLowerCase())return!0;continue}const s=t.toLowerCase().replace(/^\./,"");if(o===s||o.endsWith(`.${s}`))return!0}return!1}function V(e){if(!e?.length)return[...D];if(e.includes("*"))return["*"];const t=new Set,s=[];for(const r of[...D,...e]){const e=r.trim();e&&!t.has(e)&&(t.add(e),s.push(e))}return s}function G(e){if("systemName"in e){const t=e.systemName;if("string"==typeof t)return t}return"UnknownSystem"}function $(e){const t=e;return{packageName:"string"==typeof t.packageName?t.packageName:void 0,packageVersion:"string"==typeof t.packageVersion?t.packageVersion:void 0}}var F;exports.LOAD_SCENE_MODE=void 0,(F=exports.LOAD_SCENE_MODE||(exports.LOAD_SCENE_MODE={})).SINGLE="SINGLE",F.MULTI_CANVAS="MULTI_CANVAS";const B=e=>{if((e instanceof R||e instanceof a)&&!e.started){e.started=!0;try{e.start&&e.start()}catch(t){e instanceof a?console.error(`${function(e){if("componentName"in e){const t=e.componentName;if("string"==typeof t)return t}return"UnknownComponent"}(e.constructor)} start error`,t):console.error(`${G(e.constructor)} start error`,t)}}};class U extends n.default{constructor({systems:e,frameRate:t=60,autoStart:s=!0,needScene:r=!0,onSystemsBootstrapComplete:o,pluginInitNotifyTargetOrigin:n="*",allowedMessageOrigins:a}={}){if(super(),this.playing=!1,this.started=!1,this.multiScenes=[],this.systems=[],this.pluginInitNotifyTargetOrigin="*",this.allowedMessageOrigins=V(),this.onHostMessage=e=>{if(!I(e.origin,this.allowedMessageOrigins))return;const t=X(e.data);null!==t&&this.setPlaying(t)},this.pluginInitNotifyTargetOrigin=n,this.allowedMessageOrigins=V(a),this.ticker=new _({autoStart:!1,frameRate:t}),this.initTicker(),"undefined"!=typeof window&&window.addEventListener("message",this.onHostMessage),e&&e.length){const t=[...e];this.bootstrapSystemsAndMaybeStart(t,r,s,o)}else o?.(this),this.notifyReady()}setPlaying(e){e?this.started?this.resume():this.start():this.pause()}notifyReady(e){N(e,this.pluginInitNotifyTargetOrigin)}flushObservedComponents(){for(const e of this.systems)try{e.update?.()}catch(t){console.error(`${G(e.constructor)} update error`,t)}}notifyStateChanged(){j({playing:this.playing,started:this.started},this.pluginInitNotifyTargetOrigin)}async bootstrapSystemsAndMaybeStart(e,t,s,r){let o;try{for(const t of e)await this.addSystem(t);t&&this.loadScene({scene:new v("scene")})}catch(e){o=e,console.error("Game bootstrap failed",e)}try{await Promise.resolve(r?.(this,o))}catch(e){o=o??e,console.error("onSystemsBootstrapComplete failed",e)}if(!o)try{this.flushObservedComponents();for(const e of this.systems)await Promise.resolve(e.beforeReady?.())}catch(e){o=e,console.error("Game beforeReady failed",e)}!o&&s&&this.start(),this.notifyReady(o)}get scene(){return this._scene}set scene(e){this._scene=e}get gameObjects(){return(e=>{const t=e?.scene?.gameObjects||[],s=e?.multiScenes.map(({gameObjects:e})=>e);let r=[];for(const e of s)r=[...r,...e];return[...t,...r]})(this)}async addSystem(e,s){let r;if(e instanceof Function)r=new e(s);else{if(!(e instanceof R))return void console.warn("can only add System");r=e}if(!this.systems.find(e=>e.constructor===r.constructor)){r.game=this,r.init&&await Promise.resolve(r.init(r.__systemDefaultParams)),C({systemName:G(r.constructor),...$(r.constructor)},this.pluginInitNotifyTargetOrigin),function(e,t){p[t.systemName]=t.observerInfo,c[t.systemName]=e}(r,r.constructor),function(e){const s=[];e instanceof Array?s.push(...e):s.push(e);for(const e of s)for(const s in e.observerInfo){h[s]=h[s]||[];const r=h[s];for(const o of e.observerInfo[s])-1===r.findIndex(e=>t.isEqual(e,o))&&h[s].push(o)}}(r.constructor);try{r.awake&&r.awake()}catch(e){console.error(`${G(r.constructor)} awake error`,e)}return this.systems.push(r),r}console.warn(`${G(r.constructor)} System has been added`)}removeSystem(e){if(!e)return;let t=-1;"string"==typeof e?t=this.systems.findIndex(t=>t.name===e):e instanceof Function?t=this.systems.findIndex(t=>t.constructor===e):e instanceof R&&(t=this.systems.findIndex(t=>t===e)),t>-1&&(this.systems[t].destroy&&this.systems[t].destroy(),this.systems.splice(t,1))}getSystem(e){return this.systems.find(t=>"string"==typeof e?t.name===e:t instanceof e)}pause(){this.playing&&(this.playing=!1,this.ticker.pause(),this.triggerPause(),this.notifyStateChanged())}start(){this.playing||(this.playing=!0,this.started=!0,this.ticker.start(),this.notifyStateChanged())}resume(){this.playing||(this.playing=!0,this.ticker.start(),this.triggerResume(),this.notifyStateChanged())}initTicker(){this.ticker.add(e=>{this.scene&&((e,t=[])=>{for(const s of t)for(const t of s.components)try{B(t),t.update&&t.update(e)}catch(e){console.error(`gameObject: ${s.name} ${t.name} update error`,e)}for(const s of t)for(const t of s.components)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`gameObject: ${s.name} ${t.name} lateUpdate error`,e)}})(e,this.gameObjects);for(const t of this.systems)try{B(t),t.update&&t.update(e)}catch(e){console.error(`${G(t.constructor)} update error`,e)}for(const t of this.systems)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`${G(t.constructor)} lateUpdate error`,e)}})}triggerResume(){(e=>{for(const t of e)for(const e of t.components)try{e.onResume&&e.onResume()}catch(s){console.error(`gameObject: ${t.name}, ${e.name}, onResume error`,s)}})(this.gameObjects);for(const e of this.systems)try{e.onResume&&e.onResume()}catch(t){console.error(`${G(e.constructor)}, onResume error`,t)}}triggerPause(){(e=>{for(const t of e)for(const e of t.components)try{e.onPause&&e.onPause()}catch(s){console.error(`gameObject: ${t.name}, ${e.name}, onPause error`,s)}})(this.gameObjects);for(const e of this.systems)try{e.onPause&&e.onPause()}catch(t){console.error(`${G(e.constructor)}, onPause error`,t)}}destroySystems(){for(const e of[...this.systems])this.removeSystem(e);this.systems.length=0}destroy(){"undefined"!=typeof window&&window.removeEventListener("message",this.onHostMessage),this.removeAllListeners(),this.pause(),this.scene.destroy(),this.destroySystems(),this.ticker=null,this.scene=null,this.canvas=null,this.multiScenes=null}loadScene({scene:e,mode:t=exports.LOAD_SCENE_MODE.SINGLE,params:s={}}){if(e){switch(e.game=this,t){case exports.LOAD_SCENE_MODE.SINGLE:this.scene=e;break;case exports.LOAD_SCENE_MODE.MULTI_CANVAS:this.multiScenes.push(e)}this.emit("sceneChanged",{scene:e,mode:t,params:s})}}}function H(e,t){e.constructor.IDEProps||(e.constructor.IDEProps=[]),e.constructor.IDEProps.push(t)}function Y(e={}){return function(t){if(!t.observerInfo){for(const t in e)for(const s in e[t]){let r;"string"==typeof e[t][s]&&(e[t][s]=[e[t][s]]),Array.isArray(e[t][s])&&(r={prop:e[t][s],deep:!1},e[t][s]=r),r=e[t][s],"string"==typeof r.prop&&(r.prop=[r.prop])}t.observerInfo=e}}}var q;exports.LOAD_EVENT=void 0,(q=exports.LOAD_EVENT||(exports.LOAD_EVENT={})).START="start",q.PROGRESS="progress",q.LOADED="loaded",q.COMPLETE="complete",q.ERROR="error";class z extends n.default{constructor({resource:e,resourceTotal:t}){super(),this.progress=0,this.resourceTotal=0,this.resourceLoadedCount=0,this.resource=e,this.resourceTotal=t,0===t&&this.resource.emit(exports.LOAD_EVENT.COMPLETE,this)}onStart(){this.resource.emit(exports.LOAD_EVENT.START,this)}onProgress(e){this.resourceLoadedCount++,this.progress=Math.floor(this.resourceLoadedCount/this.resourceTotal*100)/100,e.success?this.resource.emit(exports.LOAD_EVENT.LOADED,this,e):this.resource.emit(exports.LOAD_EVENT.ERROR,this,e),this.resource.emit(exports.LOAD_EVENT.PROGRESS,this,e),this.resourceLoadedCount===this.resourceTotal&&this.resource.emit(exports.LOAD_EVENT.COMPLETE,this)}}const W={image:"png",json:"json",tex:"tex",ske:"ske",audio:"audio",video:"video",model:"glb",mtl:"mtl",bin:"bin",vertex:"vert",fragment:"frag"},J={png:"png",jpg:"jpg",jpeg:"jpeg",webp:"webp",ktx2:"ktx2",json:"json",tex:"tex",ske:"ske",mp3:"audio",wav:"audio",aac:"audio",ogg:"audio",mp4:"video",webm:"video",glb:"glb",gltf:"gltf",fbx:"fbx",obj:"obj",mtl:"mtl",stl:"stl",dae:"dae",ply:"ply",bin:"bin",vert:"vert",frag:"frag",glsl:"glsl"};function Q(e,t){return J[function(e){const t=e.split("?")[0].split("#")[0],s=t.lastIndexOf(".");return s<0?"":t.slice(s+1).toLowerCase()}(e)]||W[t]||"png"}function K(e,t,s){if("string"==typeof t){const r=t.trim();if(!r)throw ee(s,e);return{type:Q(r,e),url:r}}if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(`Resource "${s}" src.${e} must be a url string or { type, url }.`);const r=t;if("data"===r.type)return r;const o="string"==typeof r.url?r.url.trim():"";if(!o)throw ee(s,e);return{...r,type:r.type||Q(o,e),url:o}}function Z(e){if("string"!=typeof e)return;return e.trim()||void 0}function ee(e,t){return new Error(`Resource "${e}" src.${t}.url is required. Use { type, url } (e.g. { type: "webp", url: "https://..." }). A flat path string is also accepted and will be normalized.`)}function te(e,t,s="(unnamed)"){if(null==e)throw new Error(`Resource "${s}" src is required.`);if("string"==typeof e){const r=function(e){return"AUDIO"===e?"audio":"VIDEO"===e?"video":"MODEL"===e||"GLB"===e?"model":"SHADER"===e?"fragment":"image"}(t);return{[r]:K(r,e,s)}}if("object"!=typeof e||Array.isArray(e))throw new Error(`Resource "${s}" src must be a url string or a slot object.`);const r={};for(const[t,o]of Object.entries(e))null!=o&&(r[t]=K(t,o,s));if(0===Object.keys(r).length)throw new Error(`Resource "${s}" src has no loadable slots.`);return r}const se={AbstractLoadStrategy:s.AbstractLoadStrategy,AudioLoadStrategy:s.AudioLoadStrategy,ImageLoadStrategy:s.ImageLoadStrategy,XhrResponseType:s.XhrResponseType,MediaElementLoadStrategy:s.MediaElementLoadStrategy,VideoLoadStrategy:s.VideoLoadStrategy,XhrLoadStrategy:s.XhrLoadStrategy,Loader:s.Loader,Resource:s.Resource,ResourceType:s.ResourceType,ResourceState:s.ResourceState};function re(e){const t=e.frame;return t&&"object"==typeof t?{...e,frame:t,rotated:Boolean(e.rotated),trimmed:Boolean(e.trimmed),spriteSourceSize:e.spriteSourceSize,sourceSize:e.sourceSize}:null}function oe(e,t,s){for(const r of e){if(!r||"object"!=typeof r)continue;const e=r,o=String(e.filename||e.name||"");if(!o)continue;const n=re(e);if(!n)continue;t[o]=n;const a=o.lastIndexOf("/");if(a>0){const e=o.slice(0,a);s[e]||(s[e]=[]),s[e].includes(o)||s[e].push(o)}}}var ne;exports.RESOURCE_TYPE=void 0,(ne=exports.RESOURCE_TYPE||(exports.RESOURCE_TYPE={})).IMAGE="IMAGE",ne.SPRITE="SPRITE",ne.SPRITE_ANIMATION="SPRITE_ANIMATION",ne.AUDIO="AUDIO",ne.VIDEO="VIDEO",ne.GLB="GLB",ne.MODEL="MODEL",ne.SHADER="SHADER",s.XhrLoadStrategy.setExtensionXhrType("json",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("tex",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("ske",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("mp3",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("wav",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("aac",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("ogg",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("glb",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("gltf",s.XhrResponseType.Json),s.XhrLoadStrategy.setExtensionXhrType("fbx",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("stl",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("ply",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("bin",s.XhrResponseType.Buffer),s.XhrLoadStrategy.setExtensionXhrType("obj",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("mtl",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("dae",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("vert",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("frag",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("glsl",s.XhrResponseType.Text),s.XhrLoadStrategy.setExtensionXhrType("ktx2",s.XhrResponseType.Buffer);const ae={png:s.ImageLoadStrategy,jpg:s.ImageLoadStrategy,jpeg:s.ImageLoadStrategy,webp:s.ImageLoadStrategy,ktx2:s.XhrLoadStrategy,json:s.XhrLoadStrategy,tex:s.XhrLoadStrategy,ske:s.XhrLoadStrategy,audio:s.XhrLoadStrategy,video:s.VideoLoadStrategy,glb:s.XhrLoadStrategy,gltf:s.XhrLoadStrategy,fbx:s.XhrLoadStrategy,obj:s.XhrLoadStrategy,mtl:s.XhrLoadStrategy,stl:s.XhrLoadStrategy,dae:s.XhrLoadStrategy,ply:s.XhrLoadStrategy,bin:s.XhrLoadStrategy,vert:s.XhrLoadStrategy,frag:s.XhrLoadStrategy,glsl:s.XhrLoadStrategy};class ie extends n.default{constructor(e){super(),this.timeout=6e3,this.preProcessResourceHandlers=[],this.resourcesMap={},this.makeInstanceFunctions={},this.destroyInstanceFunctions={},this.promiseMap={},this.loaders=[],e&&"number"==typeof e.timeout&&(this.timeout=e.timeout)}loadConfig(e){this.addResource(e),this.preload()}loadSingle(e){return this.addResource([e]),this.getResource(e.name)}addResource(e){if(!e||e.length<1)console.warn("no resources");else for(const t of e)this.resourcesMap[t.name]?console.warn(t.name+" was already added"):this.resourcesMap[t.name]={...t,src:te(t.src,String(t.type),t.name),data:{}}}addPreProcessResourceHandler(e){this.preProcessResourceHandlers.push(e)}removePreProcessResourceHandler(e){this.preProcessResourceHandlers.splice(this.preProcessResourceHandlers.indexOf(e),1)}preload(){const e=[];for(const t in this.resourcesMap){const s=this.resourcesMap[t];!s.preload||s.complete||this.promiseMap[t]||e.push(s.name)}this.progress=new z({resource:this,resourceTotal:e.length}),this.loadResource({names:e,preload:!0})}async getResource(e){return this.loadResource({names:[e]}),this.promiseMap[e]||Promise.resolve({})}async instance(e){const t=this.resourcesMap[e];return this.makeInstanceFunctions[t.type]&&await this.makeInstanceFunctions[t.type](t)}async destroy(e){await this._destroy(e)}async _destroy(e,t=!1){const s=this.resourcesMap[e];if(s){if(!t)try{this.destroyInstanceFunctions[s.type]&&await this.destroyInstanceFunctions[s.type](s)}catch(e){console.warn(`destroy resource ${s.name} error with '${e.message}'`)}delete this.promiseMap[e],s.data={},s.complete=!1,s.instance=void 0}}registerResourceType(e,t=e){if(exports.RESOURCE_TYPE[e])throw new Error(`The type ${e} already exists in RESOURCE_TYPE`);exports.RESOURCE_TYPE[e]=t}registerInstance(e,t){this.makeInstanceFunctions[e]=t}registerDestroy(e,t){this.destroyInstanceFunctions[e]=t}loadResource({names:e=[],preload:t=!1}){const s=e.filter(e=>!this.promiseMap[e]&&this.resourcesMap[e]);if(!s.length)return;const r={},o=this.getLoader(t);s.forEach(e=>{this.promiseMap[e]=new Promise(t=>r[e]=t);const s=this.resourcesMap[e];for(const e of this.preProcessResourceHandlers)e(s);s.src=te(s.src,String(s.type),s.name);for(const n in s.src){const a=s.src[n].type;"data"===a?(s.data[n]=s.src[n].data,this.doComplete(e,r[e],t)):o.add({url:s.src[n].url,name:`${s.name}_${n}`,strategy:ae[a],metadata:{key:n,name:s.name,resolves:r}})}}),o.load()}async doComplete(e,t,s=!1){const r=this.resourcesMap[e],o={name:e,resource:this.resourcesMap[e],success:!0};if(this.checkAllLoaded(e))try{r.instance=await this.instance(e),r.complete=!0,s&&this.progress.onProgress(o),t(r)}catch(e){console.error(e),r.complete=!1,s&&(o.errMsg=e.message,o.success=!1,this.progress.onProgress(o)),t({})}}checkAllLoaded(e){const t=this.resourcesMap[e];return Array.from(Object.keys(t.src)).every(e=>t.data[e])}getLoader(e=!1){let t=this.loaders.find(({loading:e})=>!e);return t||(t=new s.Loader,this.loaders.push(t)),e&&t.onStart.once(()=>{this.progress.onStart()}),t.onLoad.add((t,s)=>{this.onLoad({preload:e,resource:s})}),t.onError.add((t,s,r)=>{this.onError({errMsg:t,resource:r,preload:e})}),t.onComplete.once(()=>{t.onLoad.detachAll(),t.onError.detachAll(),t.reset()}),t}async onLoad({preload:e=!1,resource:t}){const{metadata:{key:s,name:r,resolves:o},data:n}=t;this.resourcesMap[r].data[s]=n,this.doComplete(r,o[r],e)}async onError({errMsg:e,preload:t=!1,resource:s}){const{metadata:{name:r,resolves:o}}=s;if(this._destroy(r,!0),o[r]({}),t){const t={name:r,resource:this.resourcesMap[r],success:!1,errMsg:e};this.progress.onProgress(t)}}}const ce=new ie;ce.registerInstance(exports.RESOURCE_TYPE.SHADER,e=>({vertex:"string"==typeof e.data?.vertex?e.data.vertex:"",fragment:"string"==typeof e.data?.fragment?e.data.fragment:""}));function pe(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function he(e){return Math.round(2*e)/2}const me={IDEProp:H,componentObserver:Y};console.log(`@combos-fun/engine version: ${k}`),exports.AdaptivePixelRatio=class{constructor(e){this.elapsedMs=0,this.slowFrames=0,this.fastFrames=0,this.pixelRatio=e.pixelRatio,this.ceiling=e.ceiling,this.enabled=e.enabled}sample(e){if(!this.enabled)return null;if(!(e>0&&Number.isFinite(e)))return null;if(this.elapsedMs+=e,this.elapsedMs<3e3)return null;if(e>20){if(this.fastFrames=0,this.slowFrames+=1,this.slowFrames>=30&&this.pixelRatio>1){this.slowFrames=0;const e=Math.max(1,he(this.pixelRatio-.5));if(e<this.pixelRatio)return this.pixelRatio=e,e}return null}if(e<12){if(this.slowFrames=0,this.fastFrames+=1,this.fastFrames>=120&&this.pixelRatio<this.ceiling){this.fastFrames=0;const e=Math.min(this.ceiling,he(this.pixelRatio+.5));if(e>this.pixelRatio)return this.pixelRatio=e,e}return null}return this.slowFrames=0,this.fastFrames=0,null}},exports.COMBOS_GAME_PLUGIN_INIT_SUCCESS=L,exports.COMBOS_GAME_READY=w,exports.COMBOS_GAME_SET_PLAYING=M,exports.COMBOS_GAME_STATE_CHANGED=A,exports.Component=a,exports.DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES=D,exports.Game=U,exports.GameObject=E,exports.IDEProp=H,exports.RESOURCE_TYPE_STRATEGY=ae,exports.Scene=v,exports.System=R,exports.componentObserver=Y,exports.compressedTextureUrl=function(e){if(!e)return;if("ktx2"===e.type){const t=Z(e.url);if(t)return t}const t=Z(e.ktx2);if(t)return t;const s=Array.isArray(e.texture)?e.texture:e.texture?[e.texture]:[];for(const e of s){if("ktx2"!==e?.type)continue;const t=Z(e.url);if(t)return t}},exports.decorators=me,exports.imageFallbackUrl=function(e){return Z(e?.fallback?.url)},exports.isAllowedMessageOrigin=I,exports.mergeAllowedMessageOrigins=V,exports.normalizeResourceSrc=te,exports.normalizeSpritesheetData=function(e){if(!e||"object"!=typeof e)return{frames:{},animations:{},meta:{scale:1}};const t=e;if(function(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}(t.frames))return{...t,frames:t.frames,animations:{...t.animations||{}},meta:{scale:1,...t.meta||{}}};const s={},r={...t.animations||{}};if(Array.isArray(t.textures)){for(const e of t.textures)e&&"object"==typeof e&&Array.isArray(e.frames)&&oe(e.frames,s,r);const e=t.textures[0]||{},o=e.scale??t.meta?.scale??1;return{frames:s,animations:r,meta:{scale:"number"==typeof o||"string"==typeof o?o:1,image:"string"==typeof e.image?e.image:void 0,size:e.size,format:e.format,...t.meta||{}}}}return Array.isArray(t.frames)?(oe(t.frames,s,r),{frames:s,animations:r,meta:{scale:1,...t.meta||{}}}):{frames:{},animations:r,meta:{scale:1,...t.meta||{}}}},exports.parseSetPlayingMessage=X,exports.postParentGameReady=N,exports.postParentGameState=j,exports.postParentPluginInitSuccess=C,exports.resolveRenderQuality=function(e={},t={}){const s=pe(e.maxPixelRatio)?e.maxPixelRatio:2,r=pe(e.resolution)?e.resolution:pe(e.pixelRatio)?e.pixelRatio:void 0,o=function(e){return pe(e)?e:"undefined"!=typeof window&&pe(window.devicePixelRatio)?window.devicePixelRatio:1}(e.devicePixelRatio??t.devicePixelRatio),n=r??Math.min(o,s);return{pixelRatio:n,pixelRatioCeiling:n,antialias:"boolean"==typeof e.antialias?e.antialias:n<2,pauseWhenHidden:"boolean"!=typeof e.pauseWhenHidden||e.pauseWhenHidden,adaptivePixelRatio:"boolean"==typeof e.adaptivePixelRatio?e.adaptivePixelRatio:t.adaptivePixelRatio??!1,powerPreference:e.powerPreference??"high-performance",autoDensity:"boolean"!=typeof e.autoDensity||e.autoDensity,explicitPixelRatio:null!=r}},exports.resource=ce,exports.resourceLoader=se,exports.shouldPauseRendering=function(e){return e&&"undefined"!=typeof document&&!0===document.hidden},exports.version=k;
package/dist/engine.d.ts CHANGED
@@ -283,13 +283,19 @@ interface LoadSceneParams {
283
283
  antialias?: boolean;
284
284
  preserveDrawingBuffer?: boolean;
285
285
  resolution?: number;
286
+ pixelRatio?: number;
287
+ maxPixelRatio?: number;
286
288
  backgroundColor?: number;
287
289
  clearBeforeRender?: boolean;
288
290
  roundPixels?: boolean;
289
291
  forceFXAA?: boolean;
290
292
  legacy?: boolean;
291
293
  autoResize?: boolean;
292
- powerPreference?: "high-performance";
294
+ autoDensity?: boolean;
295
+ pauseWhenHidden?: boolean;
296
+ adaptivePixelRatio?: boolean;
297
+ preference?: "webgl" | "webgpu" | "canvas" | Array<"webgl" | "webgpu" | "canvas">;
298
+ powerPreference?: "default" | "high-performance" | "low-power";
293
299
  };
294
300
  }
295
301
  declare class Game extends EventEmitter {
@@ -678,7 +684,18 @@ interface NormalizedSrcSlot {
678
684
  height: number;
679
685
  };
680
686
  }>;
687
+ /** Optional Basis Universal companion. The image slot still loads for fallback. */
688
+ ktx2?: string;
689
+ /** Used when a `.ktx2` slot cannot be transcoded to a GPU compressed format. */
690
+ fallback?: {
691
+ type?: string;
692
+ url: string;
693
+ };
681
694
  }
695
+ /** KTX2 URL for one image slot: the slot itself, `ktx2`, or a `texture` entry. */
696
+ declare function compressedTextureUrl(slot?: NormalizedSrcSlot | null): string | undefined;
697
+ /** Raster URL used when KTX2 transcode has no compressed GPU target. */
698
+ declare function imageFallbackUrl(slot?: NormalizedSrcSlot | null): string | undefined;
682
699
  /**
683
700
  * Accept the documented `{ type, url }` slots, plus the common guesses
684
701
  * `src: "file.png"` and `src: { image: "a.webp", json: "a.json" }`.
@@ -745,6 +762,11 @@ interface SrcBase {
745
762
  data?: any;
746
763
  size?: Size2;
747
764
  texture?: TextureBase[] | TextureBase;
765
+ ktx2?: string;
766
+ fallback?: {
767
+ type?: string;
768
+ url: string;
769
+ };
748
770
  }
749
771
  interface Size2 {
750
772
  width: number;
@@ -853,6 +875,66 @@ interface ShaderResourceInstance {
853
875
  fragment: string;
854
876
  }
855
877
 
878
+ /** WebGL / WebGPU power hint. Omitted values resolve to `high-performance`. */
879
+ type PowerPreference = 'default' | 'high-performance' | 'low-power';
880
+ /**
881
+ * Caller-facing render options. Explicit `resolution` or `pixelRatio` is used
882
+ * as given. The pixel-ratio cap applies only when both are omitted.
883
+ */
884
+ interface RenderQualityInput {
885
+ resolution?: number;
886
+ pixelRatio?: number;
887
+ /** Cap used only when `resolution` and `pixelRatio` are omitted. Default 2. */
888
+ maxPixelRatio?: number;
889
+ antialias?: boolean;
890
+ /** Skip the GPU draw while `document.hidden`. Default true. */
891
+ pauseWhenHidden?: boolean;
892
+ /** Raise or lower pixel ratio from frame time. Default comes from the caller profile. */
893
+ adaptivePixelRatio?: boolean;
894
+ powerPreference?: PowerPreference;
895
+ /** Keep the CSS canvas size at `width` / `height` when resolution is not 1. Default true. */
896
+ autoDensity?: boolean;
897
+ /** Test seam. Production reads `window.devicePixelRatio`. */
898
+ devicePixelRatio?: number;
899
+ }
900
+ interface RenderQualityDefaults {
901
+ /** Used when `adaptivePixelRatio` is omitted. 2D leaves this false; 3D sets true. */
902
+ adaptivePixelRatio?: boolean;
903
+ devicePixelRatio?: number;
904
+ }
905
+ interface ResolvedRenderQuality {
906
+ pixelRatio: number;
907
+ /** Highest ratio adaptive sampling may return to. */
908
+ pixelRatioCeiling: number;
909
+ antialias: boolean;
910
+ pauseWhenHidden: boolean;
911
+ adaptivePixelRatio: boolean;
912
+ powerPreference: PowerPreference;
913
+ autoDensity: boolean;
914
+ explicitPixelRatio: boolean;
915
+ }
916
+ declare function resolveRenderQuality(input?: RenderQualityInput, defaults?: RenderQualityDefaults): ResolvedRenderQuality;
917
+ declare function shouldPauseRendering(pauseWhenHidden: boolean): boolean;
918
+ /**
919
+ * After a warmup, a run of slow frames steps the pixel ratio down by 0.5
920
+ * (floor 1). A longer run of fast frames steps it back up toward the ceiling.
921
+ */
922
+ declare class AdaptivePixelRatio {
923
+ pixelRatio: number;
924
+ readonly ceiling: number;
925
+ readonly enabled: boolean;
926
+ private elapsedMs;
927
+ private slowFrames;
928
+ private fastFrames;
929
+ constructor(options: {
930
+ pixelRatio: number;
931
+ ceiling: number;
932
+ enabled: boolean;
933
+ });
934
+ /** Returns the new ratio when it changes, otherwise null. */
935
+ sample(deltaMs: number): number | null;
936
+ }
937
+
856
938
  /**
857
939
  * Sent to `window.parent` after each `System.init` completes during `Game.addSystem`
858
940
  * (when running inside an iframe and parent differs from self).
@@ -938,7 +1020,7 @@ declare function isAllowedMessageOrigin(origin: string, allowed: readonly string
938
1020
  declare function mergeAllowedMessageOrigins(extra?: string[]): string[];
939
1021
 
940
1022
  /** Generated at build from package.json */
941
- declare const version = "0.1.13";
1023
+ declare const version = "0.1.14-beta.0";
942
1024
 
943
1025
  /** Decorators util */
944
1026
  declare const decorators: {
@@ -946,5 +1028,5 @@ declare const decorators: {
946
1028
  componentObserver: typeof componentObserver;
947
1029
  };
948
1030
 
949
- export { COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, componentObserver, decorators, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, resource, resourceLoader, version };
950
- export type { CombosGamePluginInitSuccessMessage, CombosGameReadyMessage, CombosGameSetPlayingMessage, CombosGameStateChangedMessage, ObserverEvent as ComponentChanged, ComponentParams, GameParams, NormalizedSrcSlot, ObserverInfo, PixiSpritesheetData, PluginStruct, PureObserverInfo, ResourceBase, ResourceStruct, ShaderResourceInstance, SystemConstructor, UpdateParams };
1031
+ export { AdaptivePixelRatio, COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, componentObserver, compressedTextureUrl, decorators, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, resolveRenderQuality, resource, resourceLoader, shouldPauseRendering, version };
1032
+ export type { CombosGamePluginInitSuccessMessage, CombosGameReadyMessage, CombosGameSetPlayingMessage, CombosGameStateChangedMessage, ObserverEvent as ComponentChanged, ComponentParams, GameParams, NormalizedSrcSlot, ObserverInfo, PixiSpritesheetData, PluginStruct, PowerPreference, PureObserverInfo, RenderQualityInput, ResolvedRenderQuality, ResourceBase, ResourceStruct, ShaderResourceInstance, SystemConstructor, UpdateParams };
@@ -885,7 +885,7 @@ class Scene extends GameObject {
885
885
  }
886
886
 
887
887
  /** Generated at build from package.json */
888
- const version = "0.1.13";
888
+ const version = "0.1.14-beta.0";
889
889
 
890
890
  /**
891
891
  * Sent to `window.parent` after each `System.init` completes during `Game.addSystem`
@@ -1571,6 +1571,7 @@ const EXT_TO_TYPE = {
1571
1571
  jpg: 'jpg',
1572
1572
  jpeg: 'jpeg',
1573
1573
  webp: 'webp',
1574
+ ktx2: 'ktx2',
1574
1575
  json: 'json',
1575
1576
  tex: 'tex',
1576
1577
  ske: 'ske',
@@ -1639,6 +1640,38 @@ function wrapSlot(slot, value, resourceName) {
1639
1640
  url,
1640
1641
  };
1641
1642
  }
1643
+ function nonemptyUrl(url) {
1644
+ if (typeof url !== 'string')
1645
+ return undefined;
1646
+ const trimmed = url.trim();
1647
+ return trimmed || undefined;
1648
+ }
1649
+ /** KTX2 URL for one image slot: the slot itself, `ktx2`, or a `texture` entry. */
1650
+ function compressedTextureUrl(slot) {
1651
+ if (!slot)
1652
+ return undefined;
1653
+ if (slot.type === 'ktx2') {
1654
+ const own = nonemptyUrl(slot.url);
1655
+ if (own)
1656
+ return own;
1657
+ }
1658
+ const companion = nonemptyUrl(slot.ktx2);
1659
+ if (companion)
1660
+ return companion;
1661
+ const textures = Array.isArray(slot.texture) ? slot.texture : slot.texture ? [slot.texture] : [];
1662
+ for (const item of textures) {
1663
+ if (item?.type !== 'ktx2')
1664
+ continue;
1665
+ const url = nonemptyUrl(item.url);
1666
+ if (url)
1667
+ return url;
1668
+ }
1669
+ return undefined;
1670
+ }
1671
+ /** Raster URL used when KTX2 transcode has no compressed GPU target. */
1672
+ function imageFallbackUrl(slot) {
1673
+ return nonemptyUrl(slot?.fallback?.url);
1674
+ }
1642
1675
  function missingUrlError(resourceName, slot) {
1643
1676
  return new Error(`Resource "${resourceName}" src.${slot}.url is required. ` +
1644
1677
  `Use { type, url } (e.g. { type: "webp", url: "https://..." }). ` +
@@ -1812,11 +1845,13 @@ XhrLoadStrategy.setExtensionXhrType('dae', XhrResponseType.Text);
1812
1845
  XhrLoadStrategy.setExtensionXhrType('vert', XhrResponseType.Text);
1813
1846
  XhrLoadStrategy.setExtensionXhrType('frag', XhrResponseType.Text);
1814
1847
  XhrLoadStrategy.setExtensionXhrType('glsl', XhrResponseType.Text);
1848
+ XhrLoadStrategy.setExtensionXhrType('ktx2', XhrResponseType.Buffer);
1815
1849
  const RESOURCE_TYPE_STRATEGY = {
1816
1850
  png: ImageLoadStrategy,
1817
1851
  jpg: ImageLoadStrategy,
1818
1852
  jpeg: ImageLoadStrategy,
1819
1853
  webp: ImageLoadStrategy,
1854
+ ktx2: XhrLoadStrategy,
1820
1855
  json: XhrLoadStrategy,
1821
1856
  tex: XhrLoadStrategy,
1822
1857
  ske: XhrLoadStrategy,
@@ -2080,6 +2115,107 @@ resource.registerInstance(RESOURCE_TYPE.SHADER, (res) => ({
2080
2115
  fragment: typeof res.data?.fragment === 'string' ? res.data.fragment : '',
2081
2116
  }));
2082
2117
 
2118
+ const DEFAULT_MAX_PIXEL_RATIO = 2;
2119
+ const ADAPTIVE_WARMUP_MS = 3000;
2120
+ const ADAPTIVE_SLOW_FRAME_MS = 20;
2121
+ const ADAPTIVE_FAST_FRAME_MS = 12;
2122
+ const ADAPTIVE_SLOW_FRAME_COUNT = 30;
2123
+ const ADAPTIVE_FAST_FRAME_COUNT = 120;
2124
+ const ADAPTIVE_STEP = 0.5;
2125
+ const MIN_PIXEL_RATIO = 1;
2126
+ function isPositive(value) {
2127
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
2128
+ }
2129
+ function roundToHalf(value) {
2130
+ return Math.round(value * 2) / 2;
2131
+ }
2132
+ function readDevicePixelRatio(devicePixelRatio) {
2133
+ if (isPositive(devicePixelRatio))
2134
+ return devicePixelRatio;
2135
+ if (typeof window !== 'undefined' && isPositive(window.devicePixelRatio)) {
2136
+ return window.devicePixelRatio;
2137
+ }
2138
+ return 1;
2139
+ }
2140
+ function resolveRenderQuality(input = {}, defaults = {}) {
2141
+ const maxPixelRatio = isPositive(input.maxPixelRatio) ? input.maxPixelRatio : DEFAULT_MAX_PIXEL_RATIO;
2142
+ const explicit = isPositive(input.resolution)
2143
+ ? input.resolution
2144
+ : isPositive(input.pixelRatio)
2145
+ ? input.pixelRatio
2146
+ : undefined;
2147
+ const devicePixelRatio = readDevicePixelRatio(input.devicePixelRatio ?? defaults.devicePixelRatio);
2148
+ const pixelRatio = explicit ?? Math.min(devicePixelRatio, maxPixelRatio);
2149
+ return {
2150
+ pixelRatio,
2151
+ pixelRatioCeiling: pixelRatio,
2152
+ antialias: typeof input.antialias === 'boolean' ? input.antialias : pixelRatio < 2,
2153
+ pauseWhenHidden: typeof input.pauseWhenHidden === 'boolean' ? input.pauseWhenHidden : true,
2154
+ adaptivePixelRatio: typeof input.adaptivePixelRatio === 'boolean'
2155
+ ? input.adaptivePixelRatio
2156
+ : defaults.adaptivePixelRatio ?? false,
2157
+ powerPreference: input.powerPreference ?? 'high-performance',
2158
+ autoDensity: typeof input.autoDensity === 'boolean' ? input.autoDensity : true,
2159
+ explicitPixelRatio: explicit != null,
2160
+ };
2161
+ }
2162
+ function shouldPauseRendering(pauseWhenHidden) {
2163
+ return pauseWhenHidden && typeof document !== 'undefined' && document.hidden === true;
2164
+ }
2165
+ /**
2166
+ * After a warmup, a run of slow frames steps the pixel ratio down by 0.5
2167
+ * (floor 1). A longer run of fast frames steps it back up toward the ceiling.
2168
+ */
2169
+ class AdaptivePixelRatio {
2170
+ constructor(options) {
2171
+ this.elapsedMs = 0;
2172
+ this.slowFrames = 0;
2173
+ this.fastFrames = 0;
2174
+ this.pixelRatio = options.pixelRatio;
2175
+ this.ceiling = options.ceiling;
2176
+ this.enabled = options.enabled;
2177
+ }
2178
+ /** Returns the new ratio when it changes, otherwise null. */
2179
+ sample(deltaMs) {
2180
+ if (!this.enabled)
2181
+ return null;
2182
+ if (!(deltaMs > 0) || !Number.isFinite(deltaMs))
2183
+ return null;
2184
+ this.elapsedMs += deltaMs;
2185
+ if (this.elapsedMs < ADAPTIVE_WARMUP_MS)
2186
+ return null;
2187
+ if (deltaMs > ADAPTIVE_SLOW_FRAME_MS) {
2188
+ this.fastFrames = 0;
2189
+ this.slowFrames += 1;
2190
+ if (this.slowFrames >= ADAPTIVE_SLOW_FRAME_COUNT && this.pixelRatio > MIN_PIXEL_RATIO) {
2191
+ this.slowFrames = 0;
2192
+ const next = Math.max(MIN_PIXEL_RATIO, roundToHalf(this.pixelRatio - ADAPTIVE_STEP));
2193
+ if (next < this.pixelRatio) {
2194
+ this.pixelRatio = next;
2195
+ return next;
2196
+ }
2197
+ }
2198
+ return null;
2199
+ }
2200
+ if (deltaMs < ADAPTIVE_FAST_FRAME_MS) {
2201
+ this.slowFrames = 0;
2202
+ this.fastFrames += 1;
2203
+ if (this.fastFrames >= ADAPTIVE_FAST_FRAME_COUNT && this.pixelRatio < this.ceiling) {
2204
+ this.fastFrames = 0;
2205
+ const next = Math.min(this.ceiling, roundToHalf(this.pixelRatio + ADAPTIVE_STEP));
2206
+ if (next > this.pixelRatio) {
2207
+ this.pixelRatio = next;
2208
+ return next;
2209
+ }
2210
+ }
2211
+ return null;
2212
+ }
2213
+ this.slowFrames = 0;
2214
+ this.fastFrames = 0;
2215
+ return null;
2216
+ }
2217
+ }
2218
+
2083
2219
  /** Decorators util */
2084
2220
  const decorators = {
2085
2221
  IDEProp,
@@ -2087,5 +2223,5 @@ const decorators = {
2087
2223
  };
2088
2224
  console.log(`@combos-fun/engine version: ${version}`);
2089
2225
 
2090
- export { COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, componentObserver, decorators, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, resource, resourceLoader, version };
2226
+ export { AdaptivePixelRatio, COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, componentObserver, compressedTextureUrl, decorators, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, resolveRenderQuality, resource, resourceLoader, shouldPauseRendering, version };
2091
2227
  //# sourceMappingURL=engine.esm.js.map