@combos-fun/engine 0.1.25 → 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.25";
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,38 +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 startTime = window.startTime;
1098
+ const startTime = typeof window === 'undefined' ? undefined : window.startTime;
933
1099
  const message = {
934
1100
  ...payload,
935
1101
  ...(typeof startTime === "number" && Number.isFinite(startTime)
936
1102
  ? { duration: Math.max(0, Date.now() - startTime) }
937
1103
  : {}),
938
1104
  };
939
- const parent = window.parent;
940
- if (parent && parent !== window) {
941
- try {
942
- parent.postMessage(message, targetOrigin);
943
- }
944
- catch {
945
- /* ignore cross-origin or detached frame */
946
- }
947
- return;
948
- }
949
- try {
950
- const body = JSON.stringify(message);
951
- const host = window;
952
- const bridge = host.CombosRuntimeBridge;
953
- if (typeof bridge?.postMessage === "function") {
954
- bridge.postMessage(body);
955
- return;
956
- }
957
- host.webkit?.messageHandlers?.combosRuntime?.postMessage(body);
958
- }
959
- catch {
960
- /* no native bridge */
961
- }
1105
+ postRuntimeMessage(message, targetOrigin);
962
1106
  }
963
1107
  /**
964
1108
  * Notifies the embedding page that a system (plugin) finished async/sync `init`.
@@ -1203,6 +1347,8 @@ const gameObjectPause = (gameObjects) => {
1203
1347
  class Game extends EventEmitter {
1204
1348
  constructor({ systems, frameRate = 60, autoStart = true, needScene = true, onSystemsBootstrapComplete, pluginInitNotifyTargetOrigin = "*", allowedMessageOrigins, } = {}) {
1205
1349
  super();
1350
+ this.diagnostics = new RuntimeDiagnostics();
1351
+ this.ready = false;
1206
1352
  /**
1207
1353
  * State of game
1208
1354
  * @defaultValue false
@@ -1232,6 +1378,7 @@ class Game extends EventEmitter {
1232
1378
  setParentNotifyTargetOrigin(pluginInitNotifyTargetOrigin);
1233
1379
  this.allowedMessageOrigins = mergeAllowedMessageOrigins(allowedMessageOrigins);
1234
1380
  this.ticker = new Ticker({ autoStart: false, frameRate });
1381
+ this.ticker.onRaf = at => this.diagnostics.recordRaf(at);
1235
1382
  this.initTicker();
1236
1383
  if (typeof window !== "undefined") {
1237
1384
  window.addEventListener("message", this.onHostMessage);
@@ -1264,7 +1411,10 @@ class Game extends EventEmitter {
1264
1411
  }
1265
1412
  }
1266
1413
  notifyReady(error) {
1414
+ this.ready = true;
1415
+ this.readyError = error;
1267
1416
  postParentGameReady(error, this.pluginInitNotifyTargetOrigin);
1417
+ this.emit(COMBOS_GAME_READY, { error });
1268
1418
  }
1269
1419
  /** Drain queued component observer events without starting the ticker. */
1270
1420
  flushObservedComponents() {
@@ -1282,6 +1432,7 @@ class Game extends EventEmitter {
1282
1432
  }
1283
1433
  notifyStateChanged() {
1284
1434
  postParentGameState({ playing: this.playing, started: this.started }, this.pluginInitNotifyTargetOrigin);
1435
+ this.emit(COMBOS_GAME_STATE_CHANGED, { playing: this.playing, started: this.started });
1285
1436
  }
1286
1437
  /** When `systems` is passed in the constructor, run async `init` for each before `loadScene` / `beforeReady` / `start`. */
1287
1438
  async bootstrapSystemsAndMaybeStart(systemsToAdd, needScene, autoStart, onComplete) {
@@ -1453,6 +1604,7 @@ class Game extends EventEmitter {
1453
1604
  */
1454
1605
  initTicker() {
1455
1606
  this.ticker.add((e) => {
1607
+ const diagnosticsStart = this.diagnostics.active ? runtimeNow() : null;
1456
1608
  this.scene && gameObjectLoop(e, this.gameObjects);
1457
1609
  for (const system of this.systems) {
1458
1610
  try {
@@ -1471,6 +1623,8 @@ class Game extends EventEmitter {
1471
1623
  console.error(`${systemClassName(system.constructor)} lateUpdate error`, e);
1472
1624
  }
1473
1625
  }
1626
+ if (diagnosticsStart !== null && this.diagnostics.active)
1627
+ this.diagnostics.recordUpdate(diagnosticsStart);
1474
1628
  });
1475
1629
  }
1476
1630
  /** Call onResume method on all gameObject's, and then call onResume method on all system */
@@ -1507,6 +1661,7 @@ class Game extends EventEmitter {
1507
1661
  }
1508
1662
  /** Destroy game instance */
1509
1663
  destroy() {
1664
+ this.diagnostics.destroy();
1510
1665
  if (typeof window !== "undefined") {
1511
1666
  window.removeEventListener("message", this.onHostMessage);
1512
1667
  }
@@ -2595,6 +2750,82 @@ function fitOrthographicDisplay(input) {
2595
2750
  };
2596
2751
  }
2597
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
+
2598
2829
  /** Decorators util */
2599
2830
  const decorators = {
2600
2831
  IDEProp,
@@ -2602,5 +2833,5 @@ const decorators = {
2602
2833
  };
2603
2834
  console.log(`@combos-fun/engine version: ${version}`);
2604
2835
 
2605
- 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 };
2606
2837
  //# sourceMappingURL=engine.esm.js.map