@combos-fun/engine 0.1.24 → 0.1.26

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.
@@ -757,6 +757,139 @@ class Timeline {
757
757
  }
758
758
  }
759
759
 
760
+ const runtimeNow = () => globalThis.performance?.now() ?? Date.now();
761
+ class RuntimeDiagnostics {
762
+ constructor() {
763
+ this.providers = new Map();
764
+ this.observers = new Set();
765
+ }
766
+ get active() { return this.observers.size > 0; }
767
+ get samplingOptions() {
768
+ return { gpuTiming: [...this.observers].some(observer => observer.gpuTiming) };
769
+ }
770
+ startProvider(provider) {
771
+ try {
772
+ provider.start(this.samplingOptions);
773
+ }
774
+ catch (error) {
775
+ console.warn('Runtime metrics provider failed to start', error);
776
+ }
777
+ }
778
+ register(provider) {
779
+ if (this.providers.has(provider.id))
780
+ throw new Error(`Duplicate renderer id: ${provider.id}`);
781
+ this.providers.set(provider.id, provider);
782
+ if (this.active)
783
+ this.startProvider(provider);
784
+ this.notify(observer => observer.providerChanged?.(provider, true));
785
+ return () => {
786
+ if (this.providers.get(provider.id) !== provider)
787
+ return;
788
+ if (this.active)
789
+ provider.stop();
790
+ this.providers.delete(provider.id);
791
+ this.notify(observer => observer.providerChanged?.(provider, false));
792
+ };
793
+ }
794
+ subscribe(observer) {
795
+ const wasActive = this.active;
796
+ const gpuTiming = this.samplingOptions.gpuTiming;
797
+ this.observers.add(observer);
798
+ if (!wasActive)
799
+ for (const provider of this.providers.values())
800
+ this.startProvider(provider);
801
+ else if (gpuTiming !== this.samplingOptions.gpuTiming) {
802
+ for (const provider of this.providers.values()) {
803
+ provider.stop();
804
+ this.startProvider(provider);
805
+ }
806
+ }
807
+ return () => {
808
+ const previousGpuTiming = this.samplingOptions.gpuTiming;
809
+ this.observers.delete(observer);
810
+ if (!this.active)
811
+ for (const provider of this.providers.values())
812
+ provider.stop();
813
+ else if (previousGpuTiming !== this.samplingOptions.gpuTiming) {
814
+ for (const provider of this.providers.values()) {
815
+ provider.stop();
816
+ this.startProvider(provider);
817
+ }
818
+ }
819
+ };
820
+ }
821
+ notify(callback) {
822
+ for (const observer of this.observers) {
823
+ try {
824
+ callback(observer);
825
+ }
826
+ catch (error) {
827
+ console.warn('Runtime diagnostics observer failed', error);
828
+ }
829
+ }
830
+ }
831
+ recordRaf(at) {
832
+ if (this.active)
833
+ this.notify(observer => observer.raf?.(at));
834
+ }
835
+ recordUpdate(start) {
836
+ if (this.active) {
837
+ const at = runtimeNow();
838
+ this.notify(observer => observer.update?.(at, at - start));
839
+ }
840
+ }
841
+ measureRender(id, render) {
842
+ const provider = this.providers.get(id);
843
+ if (!this.active || !provider) {
844
+ render();
845
+ return;
846
+ }
847
+ let metrics = { drawCalls: null, canvasDrawOps: null, triangles: null, gpuMs: null };
848
+ try {
849
+ provider.beginFrame();
850
+ }
851
+ catch (error) {
852
+ console.warn('Runtime metrics beginFrame failed', error);
853
+ }
854
+ const start = runtimeNow();
855
+ try {
856
+ render();
857
+ }
858
+ finally {
859
+ const at = runtimeNow();
860
+ try {
861
+ metrics = provider.endFrame();
862
+ }
863
+ catch (error) {
864
+ console.warn('Runtime metrics endFrame failed', error);
865
+ }
866
+ const sample = { provider, at, submitMs: at - start, metrics };
867
+ this.notify(observer => observer.render?.(sample));
868
+ }
869
+ }
870
+ measureInput(timestamp, dispatch) {
871
+ if (!this.active)
872
+ return dispatch();
873
+ const start = runtimeNow();
874
+ // Legacy events may use epoch timestamps instead of performance time.
875
+ const relative = timestamp > 1e12 ? timestamp - (performance.timeOrigin || Date.now() - start) : timestamp;
876
+ const delay = Number.isFinite(relative) ? Math.max(0, start - relative) : 0;
877
+ try {
878
+ return dispatch();
879
+ }
880
+ finally {
881
+ this.notify(observer => observer.input?.(start, delay, runtimeNow() - start));
882
+ }
883
+ }
884
+ destroy() {
885
+ if (this.active)
886
+ for (const provider of this.providers.values())
887
+ provider.stop();
888
+ this.observers.clear();
889
+ this.providers.clear();
890
+ }
891
+ }
892
+
760
893
  /** Default Ticker Options */
761
894
  const defaultOptions = {
762
895
  autoStart: true,
@@ -783,6 +916,7 @@ class Ticker {
783
916
  this._ticker = () => {
784
917
  if (this._started) {
785
918
  this._requestId = requestAnimationFrame(this._ticker);
919
+ this.onRaf?.(runtimeNow());
786
920
  this.update();
787
921
  }
788
922
  };
@@ -885,7 +1019,41 @@ class Scene extends GameObject {
885
1019
  }
886
1020
 
887
1021
  /** Generated at build from package.json */
888
- const version = "0.1.24";
1022
+ const version = "0.1.26";
1023
+
1024
+ const listeners = new Set();
1025
+ let latestResourcesReady;
1026
+ function observeRuntimeMessages(listener) {
1027
+ listeners.add(listener);
1028
+ return () => listeners.delete(listener);
1029
+ }
1030
+ function getLatestResourcesReady() { return latestResourcesReady; }
1031
+ function postRuntimeMessage(message, targetOrigin = '*') {
1032
+ if (message.type === 'combos-game:resources-ready')
1033
+ latestResourcesReady = message;
1034
+ if (typeof window !== 'undefined') {
1035
+ try {
1036
+ if (window.parent && window.parent !== window)
1037
+ window.parent.postMessage(message, targetOrigin);
1038
+ else {
1039
+ const host = window;
1040
+ const bridge = typeof host.CombosRuntimeBridge?.postMessage === 'function' ? host.CombosRuntimeBridge : host.webkit?.messageHandlers?.combosRuntime;
1041
+ if (typeof bridge?.postMessage === 'function')
1042
+ bridge.postMessage(JSON.stringify(message));
1043
+ }
1044
+ }
1045
+ catch { /* detached frame or unavailable native host */ }
1046
+ }
1047
+ // Deliver after the lifecycle message has been handed to the host.
1048
+ for (const listener of listeners) {
1049
+ try {
1050
+ listener(message);
1051
+ }
1052
+ catch (error) {
1053
+ console.warn('Runtime message observer failed', error);
1054
+ }
1055
+ }
1056
+ }
889
1057
 
890
1058
  /**
891
1059
  * Sent after each `System.init` completes during `Game.addSystem`.
@@ -927,31 +1095,14 @@ function setParentNotifyTargetOrigin(targetOrigin) {
927
1095
  parentNotifyTargetOrigin = targetOrigin || "*";
928
1096
  }
929
1097
  function postToParent(payload, targetOrigin) {
930
- if (typeof window === "undefined")
931
- return;
932
- const parent = window.parent;
933
- if (parent && parent !== window) {
934
- try {
935
- parent.postMessage(payload, targetOrigin);
936
- }
937
- catch {
938
- /* ignore cross-origin or detached frame */
939
- }
940
- return;
941
- }
942
- try {
943
- const body = JSON.stringify(payload);
944
- const host = window;
945
- const bridge = host.CombosRuntimeBridge;
946
- if (typeof bridge?.postMessage === "function") {
947
- bridge.postMessage(body);
948
- return;
949
- }
950
- host.webkit?.messageHandlers?.combosRuntime?.postMessage(body);
951
- }
952
- catch {
953
- /* no native bridge */
954
- }
1098
+ const startTime = typeof window === 'undefined' ? undefined : window.startTime;
1099
+ const message = {
1100
+ ...payload,
1101
+ ...(typeof startTime === "number" && Number.isFinite(startTime)
1102
+ ? { duration: Math.max(0, Date.now() - startTime) }
1103
+ : {}),
1104
+ };
1105
+ postRuntimeMessage(message, targetOrigin);
955
1106
  }
956
1107
  /**
957
1108
  * Notifies the embedding page that a system (plugin) finished async/sync `init`.
@@ -1196,6 +1347,8 @@ const gameObjectPause = (gameObjects) => {
1196
1347
  class Game extends EventEmitter {
1197
1348
  constructor({ systems, frameRate = 60, autoStart = true, needScene = true, onSystemsBootstrapComplete, pluginInitNotifyTargetOrigin = "*", allowedMessageOrigins, } = {}) {
1198
1349
  super();
1350
+ this.diagnostics = new RuntimeDiagnostics();
1351
+ this.ready = false;
1199
1352
  /**
1200
1353
  * State of game
1201
1354
  * @defaultValue false
@@ -1225,6 +1378,7 @@ class Game extends EventEmitter {
1225
1378
  setParentNotifyTargetOrigin(pluginInitNotifyTargetOrigin);
1226
1379
  this.allowedMessageOrigins = mergeAllowedMessageOrigins(allowedMessageOrigins);
1227
1380
  this.ticker = new Ticker({ autoStart: false, frameRate });
1381
+ this.ticker.onRaf = at => this.diagnostics.recordRaf(at);
1228
1382
  this.initTicker();
1229
1383
  if (typeof window !== "undefined") {
1230
1384
  window.addEventListener("message", this.onHostMessage);
@@ -1257,7 +1411,10 @@ class Game extends EventEmitter {
1257
1411
  }
1258
1412
  }
1259
1413
  notifyReady(error) {
1414
+ this.ready = true;
1415
+ this.readyError = error;
1260
1416
  postParentGameReady(error, this.pluginInitNotifyTargetOrigin);
1417
+ this.emit(COMBOS_GAME_READY, { error });
1261
1418
  }
1262
1419
  /** Drain queued component observer events without starting the ticker. */
1263
1420
  flushObservedComponents() {
@@ -1275,6 +1432,7 @@ class Game extends EventEmitter {
1275
1432
  }
1276
1433
  notifyStateChanged() {
1277
1434
  postParentGameState({ playing: this.playing, started: this.started }, this.pluginInitNotifyTargetOrigin);
1435
+ this.emit(COMBOS_GAME_STATE_CHANGED, { playing: this.playing, started: this.started });
1278
1436
  }
1279
1437
  /** When `systems` is passed in the constructor, run async `init` for each before `loadScene` / `beforeReady` / `start`. */
1280
1438
  async bootstrapSystemsAndMaybeStart(systemsToAdd, needScene, autoStart, onComplete) {
@@ -1446,6 +1604,7 @@ class Game extends EventEmitter {
1446
1604
  */
1447
1605
  initTicker() {
1448
1606
  this.ticker.add((e) => {
1607
+ const diagnosticsStart = this.diagnostics.active ? runtimeNow() : null;
1449
1608
  this.scene && gameObjectLoop(e, this.gameObjects);
1450
1609
  for (const system of this.systems) {
1451
1610
  try {
@@ -1464,6 +1623,8 @@ class Game extends EventEmitter {
1464
1623
  console.error(`${systemClassName(system.constructor)} lateUpdate error`, e);
1465
1624
  }
1466
1625
  }
1626
+ if (diagnosticsStart !== null && this.diagnostics.active)
1627
+ this.diagnostics.recordUpdate(diagnosticsStart);
1467
1628
  });
1468
1629
  }
1469
1630
  /** Call onResume method on all gameObject's, and then call onResume method on all system */
@@ -1500,6 +1661,7 @@ class Game extends EventEmitter {
1500
1661
  }
1501
1662
  /** Destroy game instance */
1502
1663
  destroy() {
1664
+ this.diagnostics.destroy();
1503
1665
  if (typeof window !== "undefined") {
1504
1666
  window.removeEventListener("message", this.onHostMessage);
1505
1667
  }
@@ -2588,6 +2750,82 @@ function fitOrthographicDisplay(input) {
2588
2750
  };
2589
2751
  }
2590
2752
 
2753
+ /** Sparse asynchronous GPU queries, never waits for completion. */
2754
+ class WebGLGpuTimer {
2755
+ constructor(gl) {
2756
+ this.gl = gl;
2757
+ this.pending = [];
2758
+ this.current = null;
2759
+ this.frame = 0;
2760
+ this.latest = null;
2761
+ this.webgl2 = typeof gl?.createQuery === 'function';
2762
+ this.ext = gl?.getExtension(this.webgl2 ? 'EXT_disjoint_timer_query_webgl2' : 'EXT_disjoint_timer_query');
2763
+ }
2764
+ get supported() { return !!this.ext; }
2765
+ begin() {
2766
+ if (!this.ext || this.gl.isContextLost?.())
2767
+ return;
2768
+ const sampleThisFrame = this.frame++ % 30 === 0;
2769
+ if (!sampleThisFrame && !this.pending.length)
2770
+ return;
2771
+ const gl = this.gl, ext = this.ext;
2772
+ if (gl.getParameter(ext.GPU_DISJOINT_EXT)) {
2773
+ this.clear();
2774
+ return;
2775
+ }
2776
+ this.latest = null;
2777
+ this.pending = this.pending.filter(query => {
2778
+ const available = this.webgl2 ? gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE) : ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);
2779
+ if (!available)
2780
+ return true;
2781
+ const ns = this.webgl2 ? gl.getQueryParameter(query, gl.QUERY_RESULT) : ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);
2782
+ if (Number.isFinite(ns) && ns >= 0)
2783
+ this.latest = ns / 1e6;
2784
+ this.remove(query);
2785
+ return false;
2786
+ });
2787
+ if (!sampleThisFrame || this.pending.length >= 4)
2788
+ return;
2789
+ const active = this.webgl2 ? gl.getQuery(ext.TIME_ELAPSED_EXT, gl.CURRENT_QUERY) : ext.getQueryEXT(ext.TIME_ELAPSED_EXT, ext.CURRENT_QUERY_EXT);
2790
+ if (active)
2791
+ return;
2792
+ this.current = this.webgl2 ? gl.createQuery() : ext.createQueryEXT();
2793
+ if (!this.current)
2794
+ return;
2795
+ if (this.webgl2)
2796
+ gl.beginQuery(ext.TIME_ELAPSED_EXT, this.current);
2797
+ else
2798
+ ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, this.current);
2799
+ }
2800
+ end() {
2801
+ if (this.current) {
2802
+ if (this.webgl2)
2803
+ this.gl.endQuery(this.ext.TIME_ELAPSED_EXT);
2804
+ else
2805
+ this.ext.endQueryEXT(this.ext.TIME_ELAPSED_EXT);
2806
+ this.pending.push(this.current);
2807
+ this.current = null;
2808
+ }
2809
+ const value = this.latest;
2810
+ this.latest = null;
2811
+ return value;
2812
+ }
2813
+ remove(query) {
2814
+ if (this.webgl2)
2815
+ this.gl.deleteQuery(query);
2816
+ else
2817
+ this.ext.deleteQueryEXT(query);
2818
+ }
2819
+ clear() {
2820
+ if (this.current)
2821
+ this.end();
2822
+ for (const query of this.pending)
2823
+ this.remove(query);
2824
+ this.pending = [];
2825
+ this.latest = null;
2826
+ }
2827
+ }
2828
+
2591
2829
  /** Decorators util */
2592
2830
  const decorators = {
2593
2831
  IDEProp,
@@ -2595,5 +2833,5 @@ const decorators = {
2595
2833
  };
2596
2834
  console.log(`@combos-fun/engine version: ${version}`);
2597
2835
 
2598
- 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, displayBufferSize, fitOrthographicDisplay, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, shouldPauseRendering, spriteClipKeyOrder, version };
2836
+ 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, RuntimeDiagnostics, Scene, System, WebGLGpuTimer, applyCompressedImagePreference, componentObserver, compressedTextureUrl, decorators, displayBufferSize, fitOrthographicDisplay, getLatestResourcesReady, gpuSupportsCompressedTexture, imageFallbackUrl, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, observeRuntimeMessages, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, postParentResourceProgress, postParentResourcesReady, postRuntimeMessage, readSpriteClipSheet, resolveRenderQuality, resolveSpriteClip, resource, resourceLoader, runtimeNow, shouldPauseRendering, spriteClipKeyOrder, version };
2599
2837
  //# sourceMappingURL=engine.esm.js.map