@combos-fun/engine 0.1.19 → 0.1.20
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/agent-skill.md +1 -1
- package/dist/engine.cjs.js +67 -3
- package/dist/engine.cjs.js.map +1 -1
- package/dist/engine.cjs.prod.js +1 -1
- package/dist/engine.d.ts +45 -6
- package/dist/engine.esm.js +64 -4
- package/dist/engine.esm.js.map +1 -1
- package/package.json +3 -3
- package/plugin-authoring.md +1 -1
package/dist/engine.cjs.prod.js
CHANGED
|
@@ -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 l(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 h="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]?.[h];n?.some(e=>e.prop[0]===t)&&u({systemName:o,componentName:h,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&&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 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&&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}=l(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 x{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}(),S={originTime:0,playbackRate:1};class _{constructor(e,t){e instanceof _&&(t=e,e={}),e=Object.assign({},S,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 _(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 T={autoStart:!0,frameRate:60};class O{constructor(e){e=Object.assign({},T,e),this._frameCount=0,this._frameDuration=1e3/e.frameRate,this.autoStart=e.autoStart,this.frameRate=e.frameRate,this.timeline=new _({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 k 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 v="0.1.19",w="combos-game:plugin-init-success",L="combos-game:ready",A="combos-game:set-playing",M="combos-game:state-changed";function j(e,t){if("undefined"!=typeof window&&window.parent&&window.parent!==window)try{window.parent.postMessage(e,t)}catch{}}function C(e,t="*"){j({type:w,systemName:e.systemName,engineVersion:v,...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{}},t)}function P(e,t="*"){j({type:L,engineVersion:v,...void 0===e?{}:{error:e instanceof Error?e.message:String(e)}},t)}function N(e,t="*"){j({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 G(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 V(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 F=e=>{if((e instanceof x||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(`${V(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=G(),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=G(a),this.ticker=new O({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){P(e,this.pluginInitNotifyTargetOrigin)}flushObservedComponents(){for(const e of this.systems)try{e.update?.()}catch(t){console.error(`${V(e.constructor)} update error`,t)}}notifyStateChanged(){N({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 k("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 x))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:V(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(`${V(r.constructor)} awake error`,e)}return this.systems.push(r),r}console.warn(`${V(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 x&&(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{F(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{F(t),t.update&&t.update(e)}catch(e){console.error(`${V(t.constructor)} update error`,e)}for(const t of this.systems)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`${V(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(`${V(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(`${V(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 W 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 z={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 K(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)]||z[t]||"png"}function Q(e,t,s){if("string"==typeof t){const r=t.trim();if(!r)throw se(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 se(s,e);return{...r,type:r.type||K(o,e),url:o}}function Z(e){if("string"!=typeof e)return;return e.trim()||void 0}function ee(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}}function te(e){return Z(e?.fallback?.url)}function se(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 re(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=function(e){return"SPRITE"===e||"SPRITE_ANIMATION"===e}(t)?function(e){const t={...e};return delete t.animation_json,null!=t.json?delete t.atlas_json:null!=t.atlas_json&&(t.json=t.atlas_json,delete t.atlas_json),t}(e):e,o={};for(const[e,t]of Object.entries(r))null!=t&&(o[e]=Q(e,t,s));if(0===Object.keys(o).length)throw new Error(`Resource "${s}" src has no loadable slots.`);return o}function oe(e,t){if(e&&"ktx2"!==e)return e;const s=t.split("?")[0].split("#")[0],r=s.lastIndexOf("."),o=r>=0?s.slice(r+1).toLowerCase():"";return"png"===o||"jpg"===o||"jpeg"===o||"webp"===o?o:"png"}function ne(e,t){e.image&&function(e,t){const s=ee(e);if(!s)return;if(t)return"ktx2"!==e.type&&e.url&&e.url!==s&&!te(e)&&(e.fallback={type:e.type,url:e.url}),e.type="ktx2",void(e.url=s);if("ktx2"!==e.type)return;const r=te(e);r&&(e.type=oe(e.fallback?.type,r),e.url=r)}(e.image,t)}const ae=["WEBGL_compressed_texture_astc","EXT_texture_compression_bptc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_etc"],ie=["texture-compression-astc","texture-compression-bc","texture-compression-etc2"];let ce=null;function pe(){return ce||(ce=async function(){return!!function(){if("undefined"==typeof document)return!1;const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return!1;const s=ae.some(e=>t.getExtension(e)),r=t.getExtension("WEBGL_lose_context");return r?.loseContext?.(),s}()||async function(){const e="undefined"==typeof navigator?void 0:navigator.gpu;if(!e?.requestAdapter)return!1;try{const t=await e.requestAdapter(),s=t?.features?.has;return!!s&&ie.some(e=>s.call(t.features,e))}catch{return!1}}()}()),ce}const me={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 le(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ue(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 he(e){const t={};if(!e||"object"!=typeof e)return t;for(const s of Object.keys(e)){const r=e[s];t[s]=Array.isArray(r)?r.map(e=>String(e)):[]}return t}function de(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=ue(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)}}}function fe(e){if(!e||"object"!=typeof e)return{frames:{},animations:{},meta:{scale:1}};const t=e;if(le(t.frames)){const e=he(t.animations);return function(e,t){const s=new Set;for(const e of Object.values(t))for(const t of e)s.add(t);for(const r of e){if(!r||s.has(r))continue;const e=r.lastIndexOf("/");if(e<=0)continue;const o=r.slice(0,e);t[o]||(t[o]=[]),t[o].push(r),s.add(r)}}(Object.keys(t.frames),e),{...t,frames:t.frames,animations:e,meta:{scale:1,...t.meta||{}}}}const s={},r=he(t.animations);if(Array.isArray(t.textures)){for(const e of t.textures)e&&"object"==typeof e&&Array.isArray(e.frames)&&de(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)?(de(t.frames,s,r),{frames:s,animations:r,meta:{scale:1,...t.meta||{}}}):{frames:{},animations:r,meta:{scale:1,...t.meta||{}}}}function ye(e){if(!e||"object"!=typeof e)return"insertion";return le(e.frames)?"lexical":"insertion"}var ge;exports.RESOURCE_TYPE=void 0,(ge=exports.RESOURCE_TYPE||(exports.RESOURCE_TYPE={})).IMAGE="IMAGE",ge.SPRITE="SPRITE",ge.SPRITE_ANIMATION="SPRITE_ANIMATION",ge.AUDIO="AUDIO",ge.VIDEO="VIDEO",ge.GLB="GLB",ge.MODEL="MODEL",ge.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 Ee={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 be 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:re(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 W({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={};s.forEach(e=>{this.promiseMap[e]=new Promise(t=>r[e]=t)}),this.beginLoad(s,r,t)}async beginLoad(e,t,s){let r=!1;try{r=await pe()}catch{r=!1}const o=this.getLoader(s);for(const n of e){const e=this.resourcesMap[n];if(e){try{for(const t of this.preProcessResourceHandlers)t(e);e.src=re(e.src,String(e.type),e.name),ne(e.src,r)}catch(e){console.error(e),t[n]?.({});continue}for(const r in e.src){const a=e.src[r].type;"data"===a?(e.data[r]=e.src[r].data,this.doComplete(n,t[n],s)):o.add({url:e.src[r].url,name:`${e.name}_${r}`,strategy:Ee[a],metadata:{key:r,name:e.name,resolves:t}})}}else t[n]?.({})}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(e=>!e.loading&&!xe.has(e));return t||(t=new s.Loader,this.loaders.push(t)),xe.add(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(()=>{xe.delete(t),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:{key:r,name:o,resolves:n}}=s,a=this.resourcesMap[o];if("image"===r&&function(e){if(!e||"ktx2"!==e.type)return!1;const t=te(e);return!(!t||t===e.url||(e.type=oe(e.fallback?.type,t),e.url=t,0))}(a?.src?.image)){const e=a.src.image,s=this.getLoader(t);return s.add({url:e.url,name:`${o}_image_fallback`,strategy:Ee[e.type],metadata:{key:r,name:o,resolves:n}}),void s.load()}if(this._destroy(o,!0),n[o]({}),t){const t={name:o,resource:this.resourcesMap[o],success:!1,errMsg:e};this.progress.onProgress(t)}}}const xe=new WeakSet,Re=new be;Re.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 Se(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function _e(e){return Math.round(2*e)/2}const Te={IDEProp:H,componentObserver:Y};console.log(`@combos-fun/engine version: ${v}`),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,_e(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,_e(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=w,exports.COMBOS_GAME_READY=L,exports.COMBOS_GAME_SET_PLAYING=A,exports.COMBOS_GAME_STATE_CHANGED=M,exports.Component=a,exports.DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES=I,exports.Game=U,exports.GameObject=E,exports.IDEProp=H,exports.RESOURCE_TYPE_STRATEGY=Ee,exports.Scene=k,exports.System=x,exports.applyCompressedImagePreference=ne,exports.componentObserver=Y,exports.compressedTextureUrl=ee,exports.decorators=Te,exports.gpuSupportsCompressedTexture=pe,exports.imageFallbackUrl=te,exports.isAllowedMessageOrigin=D,exports.mergeAllowedMessageOrigins=G,exports.normalizeResourceSrc=re,exports.normalizeSpritesheetData=fe,exports.parseSetPlayingMessage=X,exports.postParentGameReady=P,exports.postParentGameState=N,exports.postParentPluginInitSuccess=C,exports.readSpriteClipSheet=function(e,t=ye(e)){const s=fe(e),r=Object.keys(s.frames);"lexical"===t&&r.sort();const o=r.map(e=>({...s.frames[e],name:e})),n=new Map(o.map(e=>[e.name,e])),a={},i=s.animations||{};for(const e of Object.keys(i)){const s=i[e]||[],r="lexical"===t?[...s].sort():s,o=[];for(const e of r){const t=n.get(e);t&&o.push(t)}o.length&&(a[e]=o)}if(0===Object.keys(a).length)for(const e of o){const t=e.name.lastIndexOf("/");if(t<=0)continue;const s=e.name.slice(0,t);a[s]||(a[s]=[]),a[s].push(e)}return{frames:o,animations:a,meta:s.meta}},exports.resolveRenderQuality=function(e={},t={}){const s=Se(e.maxPixelRatio)?e.maxPixelRatio:2,r=Se(e.resolution)?e.resolution:Se(e.pixelRatio)?e.pixelRatio:void 0,o=function(e){return Se(e)?e:"undefined"!=typeof window&&Se(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.resolveSpriteClip=function(e,t,s){const r=String(s??"").trim();if(!r)return{frames:[...e],clip:"",missing:!1};const o=t[r];return o&&0!==o.length?{frames:[...o],clip:r,missing:!1}:{frames:[],clip:r,missing:!0}},exports.resource=Re,exports.resourceLoader=me,exports.shouldPauseRendering=function(e){return e&&"undefined"!=typeof document&&!0===document.hidden},exports.spriteClipKeyOrder=ye,exports.version=v;
|
|
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={},l={};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 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 h="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]?.[h];n?.some(e=>e.prop[0]===t)&&u({systemName:o,componentName:h,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&&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 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&&l[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 l[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 x=function(){let e=null;return e=Date.now?Date.now:()=>(new Date).getTime(),e}(),S={originTime:0,playbackRate:1};class _{constructor(e,t){e instanceof _&&(t=e,e={}),e=Object.assign({},S,e),t&&(this._parent=t),this._createTime=x(),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:x()-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 _(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 T{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 _({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 k 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 v="0.1.20",L="combos-game:plugin-init-success",w="combos-game:ready",M="combos-game:set-playing",A="combos-game:state-changed",C="combos-game:resource-progress",j="combos-game:resources-ready";let P="*";function N(e,t){if("undefined"!=typeof window&&window.parent&&window.parent!==window)try{window.parent.postMessage(e,t)}catch{}}function X(e,t="*"){N({type:L,systemName:e.systemName,engineVersion:v,...e.packageName?{packageName:e.packageName}:{},...e.packageVersion?{packageVersion:e.packageVersion}:{}},t)}function I(e,t="*"){N({type:w,engineVersion:v,...void 0===e?{}:{error:e instanceof Error?e.message:String(e)}},t)}function D(e,t=P){N({type:C,name:e.name,loaded:e.loaded,total:e.total,progress:e.progress,success:e.success,...e.success?{}:{error:e.error??"load failed"}},t)}function G(e,t=P){N({type:j,total:e.total,failed:e.failed},t)}function V(e,t="*"){N({type:A,playing:e.playing,started:e.started},t)}function B(e){if(!e||"object"!=typeof e)return null;const t=e;return t.type!==M||"boolean"!=typeof t.playing?null:t.playing}const $=["knoffice.tech","converge.ai"];function F(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 U(e){if(!e?.length)return[...$];if(e.includes("*"))return["*"];const t=new Set,s=[];for(const r of[...$,...e]){const e=r.trim();e&&!t.has(e)&&(t.add(e),s.push(e))}return s}function H(e){if("systemName"in e){const t=e.systemName;if("string"==typeof t)return t}return"UnknownSystem"}function Y(e){const t=e;return{packageName:"string"==typeof t.packageName?t.packageName:void 0,packageVersion:"string"==typeof t.packageVersion?t.packageVersion:void 0}}var q;exports.LOAD_SCENE_MODE=void 0,(q=exports.LOAD_SCENE_MODE||(exports.LOAD_SCENE_MODE={})).SINGLE="SINGLE",q.MULTI_CANVAS="MULTI_CANVAS";const W=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(`${H(e.constructor)} start error`,t)}}};class z 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=U(),this.onHostMessage=e=>{if(!F(e.origin,this.allowedMessageOrigins))return;const t=B(e.data);null!==t&&this.setPlaying(t)},this.pluginInitNotifyTargetOrigin=n,P=n||"*",this.allowedMessageOrigins=U(a),this.ticker=new T({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){I(e,this.pluginInitNotifyTargetOrigin)}flushObservedComponents(){for(const e of this.systems)try{e.update?.()}catch(t){console.error(`${H(e.constructor)} update error`,t)}}notifyStateChanged(){V({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 k("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)),X({systemName:H(r.constructor),...Y(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){l[s]=l[s]||[];const r=l[s];for(const o of e.observerInfo[s])-1===r.findIndex(e=>t.isEqual(e,o))&&l[s].push(o)}}(r.constructor);try{r.awake&&r.awake()}catch(e){console.error(`${H(r.constructor)} awake error`,e)}return this.systems.push(r),r}console.warn(`${H(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{W(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{W(t),t.update&&t.update(e)}catch(e){console.error(`${H(t.constructor)} update error`,e)}for(const t of this.systems)try{t.lateUpdate&&t.lateUpdate(e)}catch(e){console.error(`${H(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(`${H(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(`${H(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 J(e,t){e.constructor.IDEProps||(e.constructor.IDEProps=[]),e.constructor.IDEProps.push(t)}function K(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.failed=[],this.resource=e,this.resourceTotal=t,0===t&&(this.resource.emit(exports.LOAD_EVENT.COMPLETE,this),this.notifyResourcesReady())}onStart(){this.resource.emit(exports.LOAD_EVENT.START,this)}onProgress(e){if(this.resourceLoadedCount++,this.progress=Math.floor(this.resourceLoadedCount/this.resourceTotal*100)/100,e.success)this.resource.emit(exports.LOAD_EVENT.LOADED,this,e);else{const t=e.errMsg||"load failed";this.failed.push({name:e.name,error:t}),this.resource.emit(exports.LOAD_EVENT.ERROR,this,e)}this.resource.emit(exports.LOAD_EVENT.PROGRESS,this,e),D({name:e.name,loaded:this.resourceLoadedCount,total:this.resourceTotal,progress:this.progress,success:e.success,...e.success?{}:{error:e.errMsg||"load failed"}}),this.resourceLoadedCount===this.resourceTotal&&(this.resource.emit(exports.LOAD_EVENT.COMPLETE,this),this.notifyResourcesReady())}notifyResourcesReady(){G({total:this.resourceTotal,failed:this.failed.slice()})}}const ee={image:"png",json:"json",tex:"tex",ske:"ske",audio:"audio",video:"video",model:"glb",mtl:"mtl",bin:"bin",vertex:"vert",fragment:"frag"},te={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 se(e,t){return te[function(e){const t=e.split("?")[0].split("#")[0],s=t.lastIndexOf(".");return s<0?"":t.slice(s+1).toLowerCase()}(e)]||ee[t]||"png"}function re(e,t,s){if("string"==typeof t){const r=t.trim();if(!r)throw ie(s,e);return{type:se(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 ie(s,e);return{...r,type:r.type||se(o,e),url:o}}function oe(e){if("string"!=typeof e)return;return e.trim()||void 0}function ne(e){if(!e)return;if("ktx2"===e.type){const t=oe(e.url);if(t)return t}const t=oe(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=oe(e.url);if(t)return t}}function ae(e){return oe(e?.fallback?.url)}function ie(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 ce(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]:re(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=function(e){return"SPRITE"===e||"SPRITE_ANIMATION"===e}(t)?function(e){const t={...e};return delete t.animation_json,null!=t.json?delete t.atlas_json:null!=t.atlas_json&&(t.json=t.atlas_json,delete t.atlas_json),t}(e):e,o={};for(const[e,t]of Object.entries(r))null!=t&&(o[e]=re(e,t,s));if(0===Object.keys(o).length)throw new Error(`Resource "${s}" src has no loadable slots.`);return o}function pe(e,t){if(e&&"ktx2"!==e)return e;const s=t.split("?")[0].split("#")[0],r=s.lastIndexOf("."),o=r>=0?s.slice(r+1).toLowerCase():"";return"png"===o||"jpg"===o||"jpeg"===o||"webp"===o?o:"png"}function le(e,t){e.image&&function(e,t){const s=ne(e);if(!s)return;if(t)return"ktx2"!==e.type&&e.url&&e.url!==s&&!ae(e)&&(e.fallback={type:e.type,url:e.url}),e.type="ktx2",void(e.url=s);if("ktx2"!==e.type)return;const r=ae(e);r&&(e.type=pe(e.fallback?.type,r),e.url=r)}(e.image,t)}const me=["WEBGL_compressed_texture_astc","EXT_texture_compression_bptc","WEBGL_compressed_texture_s3tc","WEBGL_compressed_texture_etc"],ue=["texture-compression-astc","texture-compression-bc","texture-compression-etc2"];let he=null;function de(){return he||(he=async function(){return!!function(){if("undefined"==typeof document)return!1;const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return!1;const s=me.some(e=>t.getExtension(e)),r=t.getExtension("WEBGL_lose_context");return r?.loseContext?.(),s}()||async function(){const e="undefined"==typeof navigator?void 0:navigator.gpu;if(!e?.requestAdapter)return!1;try{const t=await e.requestAdapter(),s=t?.features?.has;return!!s&&ue.some(e=>s.call(t.features,e))}catch{return!1}}()}()),he}const fe={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 ye(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function ge(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 Ee(e){const t={};if(!e||"object"!=typeof e)return t;for(const s of Object.keys(e)){const r=e[s];t[s]=Array.isArray(r)?r.map(e=>String(e)):[]}return t}function be(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=ge(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)}}}function Re(e){if(!e||"object"!=typeof e)return{frames:{},animations:{},meta:{scale:1}};const t=e;if(ye(t.frames)){const e=Ee(t.animations);return function(e,t){const s=new Set;for(const e of Object.values(t))for(const t of e)s.add(t);for(const r of e){if(!r||s.has(r))continue;const e=r.lastIndexOf("/");if(e<=0)continue;const o=r.slice(0,e);t[o]||(t[o]=[]),t[o].push(r),s.add(r)}}(Object.keys(t.frames),e),{...t,frames:t.frames,animations:e,meta:{scale:1,...t.meta||{}}}}const s={},r=Ee(t.animations);if(Array.isArray(t.textures)){for(const e of t.textures)e&&"object"==typeof e&&Array.isArray(e.frames)&&be(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)?(be(t.frames,s,r),{frames:s,animations:r,meta:{scale:1,...t.meta||{}}}):{frames:{},animations:r,meta:{scale:1,...t.meta||{}}}}function xe(e){if(!e||"object"!=typeof e)return"insertion";return ye(e.frames)?"lexical":"insertion"}var Se;exports.RESOURCE_TYPE=void 0,(Se=exports.RESOURCE_TYPE||(exports.RESOURCE_TYPE={})).IMAGE="IMAGE",Se.SPRITE="SPRITE",Se.SPRITE_ANIMATION="SPRITE_ANIMATION",Se.AUDIO="AUDIO",Se.VIDEO="VIDEO",Se.GLB="GLB",Se.MODEL="MODEL",Se.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 _e={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 Oe 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:ce(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={};s.forEach(e=>{this.promiseMap[e]=new Promise(t=>r[e]=t)}),this.beginLoad(s,r,t)}async beginLoad(e,t,s){let r=!1;try{r=await de()}catch{r=!1}const o=this.getLoader(s);for(const n of e){const e=this.resourcesMap[n];if(e){try{for(const t of this.preProcessResourceHandlers)t(e);e.src=ce(e.src,String(e.type),e.name),le(e.src,r)}catch(e){console.error(e),t[n]?.({});continue}for(const r in e.src){const a=e.src[r].type;"data"===a?(e.data[r]=e.src[r].data,this.doComplete(n,t[n],s)):o.add({url:e.src[r].url,name:`${e.name}_${r}`,strategy:_e[a],metadata:{key:r,name:e.name,resolves:t}})}}else t[n]?.({})}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(e=>!e.loading&&!Te.has(e));return t||(t=new s.Loader,this.loaders.push(t)),Te.add(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(()=>{Te.delete(t),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:{key:r,name:o,resolves:n}}=s,a=this.resourcesMap[o];if("image"===r&&function(e){if(!e||"ktx2"!==e.type)return!1;const t=ae(e);return!(!t||t===e.url||(e.type=pe(e.fallback?.type,t),e.url=t,0))}(a?.src?.image)){const e=a.src.image,s=this.getLoader(t);return s.add({url:e.url,name:`${o}_image_fallback`,strategy:_e[e.type],metadata:{key:r,name:o,resolves:n}}),void s.load()}if(this._destroy(o,!0),n[o]({}),t){const t={name:o,resource:this.resourcesMap[o],success:!1,errMsg:e};this.progress.onProgress(t)}}}const Te=new WeakSet,ke=new Oe;ke.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 ve(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function Le(e){return Math.round(2*e)/2}const we={IDEProp:J,componentObserver:K};console.log(`@combos-fun/engine version: ${v}`),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,Le(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,Le(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_RESOURCES_READY=j,exports.COMBOS_GAME_RESOURCE_PROGRESS=C,exports.COMBOS_GAME_SET_PLAYING=M,exports.COMBOS_GAME_STATE_CHANGED=A,exports.Component=a,exports.DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES=$,exports.Game=z,exports.GameObject=E,exports.IDEProp=J,exports.RESOURCE_TYPE_STRATEGY=_e,exports.Scene=k,exports.System=R,exports.applyCompressedImagePreference=le,exports.componentObserver=K,exports.compressedTextureUrl=ne,exports.decorators=we,exports.gpuSupportsCompressedTexture=de,exports.imageFallbackUrl=ae,exports.isAllowedMessageOrigin=F,exports.mergeAllowedMessageOrigins=U,exports.normalizeResourceSrc=ce,exports.normalizeSpritesheetData=Re,exports.parseSetPlayingMessage=B,exports.postParentGameReady=I,exports.postParentGameState=V,exports.postParentPluginInitSuccess=X,exports.postParentResourceProgress=D,exports.postParentResourcesReady=G,exports.readSpriteClipSheet=function(e,t=xe(e)){const s=Re(e),r=Object.keys(s.frames);"lexical"===t&&r.sort();const o=r.map(e=>({...s.frames[e],name:e})),n=new Map(o.map(e=>[e.name,e])),a={},i=s.animations||{};for(const e of Object.keys(i)){const s=i[e]||[],r="lexical"===t?[...s].sort():s,o=[];for(const e of r){const t=n.get(e);t&&o.push(t)}o.length&&(a[e]=o)}if(0===Object.keys(a).length)for(const e of o){const t=e.name.lastIndexOf("/");if(t<=0)continue;const s=e.name.slice(0,t);a[s]||(a[s]=[]),a[s].push(e)}return{frames:o,animations:a,meta:s.meta}},exports.resolveRenderQuality=function(e={},t={}){const s=ve(e.maxPixelRatio)?e.maxPixelRatio:2,r=ve(e.resolution)?e.resolution:ve(e.pixelRatio)?e.pixelRatio:void 0,o=function(e){return ve(e)?e:"undefined"!=typeof window&&ve(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.resolveSpriteClip=function(e,t,s){const r=String(s??"").trim();if(!r)return{frames:[...e],clip:"",missing:!1};const o=t[r];return o&&0!==o.length?{frames:[...o],clip:r,missing:!1}:{frames:[],clip:r,missing:!0}},exports.resource=ke,exports.resourceLoader=fe,exports.shouldPauseRendering=function(e){return e&&"undefined"!=typeof document&&!0===document.hidden},exports.spriteClipKeyOrder=xe,exports.version=v;
|
package/dist/engine.d.ts
CHANGED
|
@@ -245,7 +245,8 @@ interface GameParams {
|
|
|
245
245
|
needScene?: boolean;
|
|
246
246
|
/**
|
|
247
247
|
* `postMessage` targetOrigin when notifying `window.parent` of lifecycle events
|
|
248
|
-
* (`combos-game:plugin-init-success`, `combos-game:ready`, `combos-game:state-changed
|
|
248
|
+
* (`combos-game:plugin-init-success`, `combos-game:ready`, `combos-game:state-changed`,
|
|
249
|
+
* `combos-game:resource-progress`, `combos-game:resources-ready`).
|
|
249
250
|
* Default `'*'`. Only used when `window.parent` exists and differs from `window`.
|
|
250
251
|
*/
|
|
251
252
|
pluginInitNotifyTargetOrigin?: string;
|
|
@@ -316,7 +317,7 @@ declare class Game extends EventEmitter {
|
|
|
316
317
|
systems: System[];
|
|
317
318
|
/**
|
|
318
319
|
* Passed to `postMessage` when reporting lifecycle events to `window.parent`
|
|
319
|
-
* (`plugin-init-success`, `ready`, `state-changed`).
|
|
320
|
+
* (`plugin-init-success`, `ready`, `state-changed`, `resource-progress`, `resources-ready`).
|
|
320
321
|
*/
|
|
321
322
|
pluginInitNotifyTargetOrigin: string;
|
|
322
323
|
/** Inbound `postMessage` origins allowed to send host commands. */
|
|
@@ -629,12 +630,14 @@ declare class Progress extends EventEmitter {
|
|
|
629
630
|
resourceTotal: number;
|
|
630
631
|
resourceLoadedCount: number;
|
|
631
632
|
resource: Resource;
|
|
633
|
+
private failed;
|
|
632
634
|
constructor({ resource, resourceTotal }: {
|
|
633
635
|
resource: any;
|
|
634
636
|
resourceTotal: any;
|
|
635
637
|
});
|
|
636
638
|
onStart(): void;
|
|
637
639
|
onProgress(param: EventParam): void;
|
|
640
|
+
private notifyResourcesReady;
|
|
638
641
|
}
|
|
639
642
|
|
|
640
643
|
declare const resourceLoader: {
|
|
@@ -992,7 +995,8 @@ interface CombosGamePluginInitSuccessInput {
|
|
|
992
995
|
/**
|
|
993
996
|
* iframe → parent: game bootstrap finished (all systems `init`/`awake`, optional
|
|
994
997
|
* scene load and `start`). Sent once, even when `autoStart` is `false`, so the host
|
|
995
|
-
* knows
|
|
998
|
+
* knows the scene graph is ready and it may pause / hold before play.
|
|
999
|
+
* Asset preload is a separate batch: {@link COMBOS_GAME_RESOURCES_READY}.
|
|
996
1000
|
*/
|
|
997
1001
|
declare const COMBOS_GAME_READY: "combos-game:ready";
|
|
998
1002
|
/**
|
|
@@ -1021,12 +1025,47 @@ interface CombosGameSetPlayingMessage {
|
|
|
1021
1025
|
type: typeof COMBOS_GAME_SET_PLAYING;
|
|
1022
1026
|
playing: boolean;
|
|
1023
1027
|
}
|
|
1028
|
+
/**
|
|
1029
|
+
* iframe → parent: one preload-batch resource settled (success or failure).
|
|
1030
|
+
* Lazy `getResource` loads do not emit this.
|
|
1031
|
+
*/
|
|
1032
|
+
declare const COMBOS_GAME_RESOURCE_PROGRESS: "combos-game:resource-progress";
|
|
1033
|
+
/**
|
|
1034
|
+
* iframe → parent: the current `preload()` batch reached `loaded === total`.
|
|
1035
|
+
* Sent once per batch. `failed.length === 0` means every item succeeded.
|
|
1036
|
+
* `total: 0` means that call had no `preload: true` resources.
|
|
1037
|
+
*/
|
|
1038
|
+
declare const COMBOS_GAME_RESOURCES_READY: "combos-game:resources-ready";
|
|
1039
|
+
interface CombosGameResourceProgressMessage {
|
|
1040
|
+
type: typeof COMBOS_GAME_RESOURCE_PROGRESS;
|
|
1041
|
+
name: string;
|
|
1042
|
+
loaded: number;
|
|
1043
|
+
total: number;
|
|
1044
|
+
/** 0–1, same rounding as the in-process loader progress. */
|
|
1045
|
+
progress: number;
|
|
1046
|
+
success: boolean;
|
|
1047
|
+
/** Present when `success` is false. */
|
|
1048
|
+
error?: string;
|
|
1049
|
+
}
|
|
1050
|
+
interface CombosGameResourceFailure {
|
|
1051
|
+
name: string;
|
|
1052
|
+
error: string;
|
|
1053
|
+
}
|
|
1054
|
+
interface CombosGameResourcesReadyMessage {
|
|
1055
|
+
type: typeof COMBOS_GAME_RESOURCES_READY;
|
|
1056
|
+
total: number;
|
|
1057
|
+
failed: CombosGameResourceFailure[];
|
|
1058
|
+
}
|
|
1024
1059
|
/**
|
|
1025
1060
|
* Notifies the embedding page that a system (plugin) finished async/sync `init`.
|
|
1026
1061
|
*/
|
|
1027
1062
|
declare function postParentPluginInitSuccess(input: CombosGamePluginInitSuccessInput, targetOrigin?: string): void;
|
|
1028
1063
|
/** Notifies the embedding page that game bootstrap finished. */
|
|
1029
1064
|
declare function postParentGameReady(error?: unknown, targetOrigin?: string): void;
|
|
1065
|
+
/** Notifies the embedding page that one preload-batch resource settled. */
|
|
1066
|
+
declare function postParentResourceProgress(input: Omit<CombosGameResourceProgressMessage, "type">, targetOrigin?: string): void;
|
|
1067
|
+
/** Notifies the embedding page that the current preload batch finished. */
|
|
1068
|
+
declare function postParentResourcesReady(input: Omit<CombosGameResourcesReadyMessage, "type">, targetOrigin?: string): void;
|
|
1030
1069
|
/** Notifies the embedding page of the current play/pause state. */
|
|
1031
1070
|
declare function postParentGameState(state: {
|
|
1032
1071
|
playing: boolean;
|
|
@@ -1053,7 +1092,7 @@ declare function isAllowedMessageOrigin(origin: string, allowed: readonly string
|
|
|
1053
1092
|
declare function mergeAllowedMessageOrigins(extra?: string[]): string[];
|
|
1054
1093
|
|
|
1055
1094
|
/** Generated at build from package.json */
|
|
1056
|
-
declare const version = "0.1.
|
|
1095
|
+
declare const version = "0.1.20";
|
|
1057
1096
|
|
|
1058
1097
|
/** Decorators util */
|
|
1059
1098
|
declare const decorators: {
|
|
@@ -1061,5 +1100,5 @@ declare const decorators: {
|
|
|
1061
1100
|
componentObserver: typeof componentObserver;
|
|
1062
1101
|
};
|
|
1063
1102
|
|
|
1064
|
-
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, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
1065
|
-
export type { CombosGamePluginInitSuccessMessage, CombosGameReadyMessage, CombosGameSetPlayingMessage, CombosGameStateChangedMessage, ObserverEvent as ComponentChanged, ComponentParams, GameParams, NormalizedSrcSlot, ObserverInfo, PixiSpritesheetData, PluginStruct, PowerPreference, PureObserverInfo, RenderQualityInput, ResolvedRenderQuality, ResourceBase, ResourceStruct, ShaderResourceInstance, SpriteClipFrame, SpriteClipKeyOrder, SpriteClipSheet, SystemConstructor, UpdateParams };
|
|
1103
|
+
export { AdaptivePixelRatio, COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_RESOURCES_READY, COMBOS_GAME_RESOURCE_PROGRESS, 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, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
1104
|
+
export type { CombosGamePluginInitSuccessMessage, CombosGameReadyMessage, CombosGameResourceFailure, CombosGameResourceProgressMessage, CombosGameResourcesReadyMessage, CombosGameSetPlayingMessage, CombosGameStateChangedMessage, ObserverEvent as ComponentChanged, ComponentParams, GameParams, NormalizedSrcSlot, ObserverInfo, PixiSpritesheetData, PluginStruct, PowerPreference, PureObserverInfo, RenderQualityInput, ResolvedRenderQuality, ResourceBase, ResourceStruct, ShaderResourceInstance, SpriteClipFrame, SpriteClipKeyOrder, SpriteClipSheet, SystemConstructor, UpdateParams };
|
package/dist/engine.esm.js
CHANGED
|
@@ -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.
|
|
888
|
+
const version = "0.1.20";
|
|
889
889
|
|
|
890
890
|
/**
|
|
891
891
|
* Sent to `window.parent` after each `System.init` completes during `Game.addSystem`
|
|
@@ -895,7 +895,8 @@ const COMBOS_GAME_PLUGIN_INIT_SUCCESS = "combos-game:plugin-init-success";
|
|
|
895
895
|
/**
|
|
896
896
|
* iframe → parent: game bootstrap finished (all systems `init`/`awake`, optional
|
|
897
897
|
* scene load and `start`). Sent once, even when `autoStart` is `false`, so the host
|
|
898
|
-
* knows
|
|
898
|
+
* knows the scene graph is ready and it may pause / hold before play.
|
|
899
|
+
* Asset preload is a separate batch: {@link COMBOS_GAME_RESOURCES_READY}.
|
|
899
900
|
*/
|
|
900
901
|
const COMBOS_GAME_READY = "combos-game:ready";
|
|
901
902
|
/**
|
|
@@ -907,6 +908,23 @@ const COMBOS_GAME_SET_PLAYING = "combos-game:set-playing";
|
|
|
907
908
|
* iframe → parent: current run state after a `start` / `pause` / `resume`.
|
|
908
909
|
*/
|
|
909
910
|
const COMBOS_GAME_STATE_CHANGED = "combos-game:state-changed";
|
|
911
|
+
/**
|
|
912
|
+
* iframe → parent: one preload-batch resource settled (success or failure).
|
|
913
|
+
* Lazy `getResource` loads do not emit this.
|
|
914
|
+
*/
|
|
915
|
+
const COMBOS_GAME_RESOURCE_PROGRESS = "combos-game:resource-progress";
|
|
916
|
+
/**
|
|
917
|
+
* iframe → parent: the current `preload()` batch reached `loaded === total`.
|
|
918
|
+
* Sent once per batch. `failed.length === 0` means every item succeeded.
|
|
919
|
+
* `total: 0` means that call had no `preload: true` resources.
|
|
920
|
+
*/
|
|
921
|
+
const COMBOS_GAME_RESOURCES_READY = "combos-game:resources-ready";
|
|
922
|
+
/** Shared with `Game.pluginInitNotifyTargetOrigin` so preload can post before or after `new Game`. */
|
|
923
|
+
let parentNotifyTargetOrigin = "*";
|
|
924
|
+
/** Called from `Game` so later preload batches use the same `targetOrigin` as lifecycle posts. */
|
|
925
|
+
function setParentNotifyTargetOrigin(targetOrigin) {
|
|
926
|
+
parentNotifyTargetOrigin = targetOrigin || "*";
|
|
927
|
+
}
|
|
910
928
|
function postToParent(payload, targetOrigin) {
|
|
911
929
|
if (typeof window === "undefined")
|
|
912
930
|
return;
|
|
@@ -943,6 +961,28 @@ function postParentGameReady(error, targetOrigin = "*") {
|
|
|
943
961
|
};
|
|
944
962
|
postToParent(payload, targetOrigin);
|
|
945
963
|
}
|
|
964
|
+
/** Notifies the embedding page that one preload-batch resource settled. */
|
|
965
|
+
function postParentResourceProgress(input, targetOrigin = parentNotifyTargetOrigin) {
|
|
966
|
+
const payload = {
|
|
967
|
+
type: COMBOS_GAME_RESOURCE_PROGRESS,
|
|
968
|
+
name: input.name,
|
|
969
|
+
loaded: input.loaded,
|
|
970
|
+
total: input.total,
|
|
971
|
+
progress: input.progress,
|
|
972
|
+
success: input.success,
|
|
973
|
+
...(input.success ? {} : { error: input.error ?? "load failed" }),
|
|
974
|
+
};
|
|
975
|
+
postToParent(payload, targetOrigin);
|
|
976
|
+
}
|
|
977
|
+
/** Notifies the embedding page that the current preload batch finished. */
|
|
978
|
+
function postParentResourcesReady(input, targetOrigin = parentNotifyTargetOrigin) {
|
|
979
|
+
const payload = {
|
|
980
|
+
type: COMBOS_GAME_RESOURCES_READY,
|
|
981
|
+
total: input.total,
|
|
982
|
+
failed: input.failed,
|
|
983
|
+
};
|
|
984
|
+
postToParent(payload, targetOrigin);
|
|
985
|
+
}
|
|
946
986
|
/** Notifies the embedding page of the current play/pause state. */
|
|
947
987
|
function postParentGameState(state, targetOrigin = "*") {
|
|
948
988
|
const payload = {
|
|
@@ -1151,7 +1191,7 @@ class Game extends EventEmitter {
|
|
|
1151
1191
|
this.systems = [];
|
|
1152
1192
|
/**
|
|
1153
1193
|
* Passed to `postMessage` when reporting lifecycle events to `window.parent`
|
|
1154
|
-
* (`plugin-init-success`, `ready`, `state-changed`).
|
|
1194
|
+
* (`plugin-init-success`, `ready`, `state-changed`, `resource-progress`, `resources-ready`).
|
|
1155
1195
|
*/
|
|
1156
1196
|
this.pluginInitNotifyTargetOrigin = "*";
|
|
1157
1197
|
/** Inbound `postMessage` origins allowed to send host commands. */
|
|
@@ -1166,6 +1206,7 @@ class Game extends EventEmitter {
|
|
|
1166
1206
|
this.setPlaying(playing);
|
|
1167
1207
|
};
|
|
1168
1208
|
this.pluginInitNotifyTargetOrigin = pluginInitNotifyTargetOrigin;
|
|
1209
|
+
setParentNotifyTargetOrigin(pluginInitNotifyTargetOrigin);
|
|
1169
1210
|
this.allowedMessageOrigins = mergeAllowedMessageOrigins(allowedMessageOrigins);
|
|
1170
1211
|
this.ticker = new Ticker({ autoStart: false, frameRate });
|
|
1171
1212
|
this.initTicker();
|
|
@@ -1528,10 +1569,12 @@ class Progress extends EventEmitter {
|
|
|
1528
1569
|
this.progress = 0;
|
|
1529
1570
|
this.resourceTotal = 0;
|
|
1530
1571
|
this.resourceLoadedCount = 0;
|
|
1572
|
+
this.failed = [];
|
|
1531
1573
|
this.resource = resource;
|
|
1532
1574
|
this.resourceTotal = resourceTotal;
|
|
1533
1575
|
if (resourceTotal === 0) {
|
|
1534
1576
|
this.resource.emit(LOAD_EVENT.COMPLETE, this);
|
|
1577
|
+
this.notifyResourcesReady();
|
|
1535
1578
|
}
|
|
1536
1579
|
}
|
|
1537
1580
|
onStart() {
|
|
@@ -1544,13 +1587,30 @@ class Progress extends EventEmitter {
|
|
|
1544
1587
|
this.resource.emit(LOAD_EVENT.LOADED, this, param);
|
|
1545
1588
|
}
|
|
1546
1589
|
else {
|
|
1590
|
+
const error = param.errMsg || 'load failed';
|
|
1591
|
+
this.failed.push({ name: param.name, error });
|
|
1547
1592
|
this.resource.emit(LOAD_EVENT.ERROR, this, param);
|
|
1548
1593
|
}
|
|
1549
1594
|
this.resource.emit(LOAD_EVENT.PROGRESS, this, param);
|
|
1595
|
+
postParentResourceProgress({
|
|
1596
|
+
name: param.name,
|
|
1597
|
+
loaded: this.resourceLoadedCount,
|
|
1598
|
+
total: this.resourceTotal,
|
|
1599
|
+
progress: this.progress,
|
|
1600
|
+
success: param.success,
|
|
1601
|
+
...(param.success ? {} : { error: param.errMsg || 'load failed' }),
|
|
1602
|
+
});
|
|
1550
1603
|
if (this.resourceLoadedCount === this.resourceTotal) {
|
|
1551
1604
|
this.resource.emit(LOAD_EVENT.COMPLETE, this);
|
|
1605
|
+
this.notifyResourcesReady();
|
|
1552
1606
|
}
|
|
1553
1607
|
}
|
|
1608
|
+
notifyResourcesReady() {
|
|
1609
|
+
postParentResourcesReady({
|
|
1610
|
+
total: this.resourceTotal,
|
|
1611
|
+
failed: this.failed.slice(),
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1554
1614
|
}
|
|
1555
1615
|
|
|
1556
1616
|
const SLOT_DEFAULT_TYPE = {
|
|
@@ -2476,5 +2536,5 @@ const decorators = {
|
|
|
2476
2536
|
};
|
|
2477
2537
|
console.log(`@combos-fun/engine version: ${version}`);
|
|
2478
2538
|
|
|
2479
|
-
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, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
2539
|
+
export { AdaptivePixelRatio, COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_RESOURCES_READY, COMBOS_GAME_RESOURCE_PROGRESS, 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, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
|
|
2480
2540
|
//# sourceMappingURL=engine.esm.js.map
|