@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.
package/README.md CHANGED
@@ -4,6 +4,13 @@
4
4
 
5
5
  Keywords: `engine`, `ecs`, `kernel`, `runtime`, `game`, `system`, `component`.
6
6
 
7
+ All five outbound `combos-game:*` lifecycle/resource messages support `duration`,
8
+ the elapsed milliseconds from the game window's `window.startTime` to message
9
+ dispatch. Set `window.startTime = Date.now()` before loading the engine to measure
10
+ startup. The field is omitted when `startTime` is missing or is not a finite
11
+ number; negative elapsed times are clamped to `0`. This applies to iframe and
12
+ native bridge messages.
13
+
7
14
  ## Documentation
8
15
 
9
16
  - Per-package agent / developer notes: [`agent-skill.md`](./agent-skill.md)
@@ -763,6 +763,139 @@ class Timeline {
763
763
  }
764
764
  }
765
765
 
766
+ const runtimeNow = () => globalThis.performance?.now() ?? Date.now();
767
+ class RuntimeDiagnostics {
768
+ constructor() {
769
+ this.providers = new Map();
770
+ this.observers = new Set();
771
+ }
772
+ get active() { return this.observers.size > 0; }
773
+ get samplingOptions() {
774
+ return { gpuTiming: [...this.observers].some(observer => observer.gpuTiming) };
775
+ }
776
+ startProvider(provider) {
777
+ try {
778
+ provider.start(this.samplingOptions);
779
+ }
780
+ catch (error) {
781
+ console.warn('Runtime metrics provider failed to start', error);
782
+ }
783
+ }
784
+ register(provider) {
785
+ if (this.providers.has(provider.id))
786
+ throw new Error(`Duplicate renderer id: ${provider.id}`);
787
+ this.providers.set(provider.id, provider);
788
+ if (this.active)
789
+ this.startProvider(provider);
790
+ this.notify(observer => observer.providerChanged?.(provider, true));
791
+ return () => {
792
+ if (this.providers.get(provider.id) !== provider)
793
+ return;
794
+ if (this.active)
795
+ provider.stop();
796
+ this.providers.delete(provider.id);
797
+ this.notify(observer => observer.providerChanged?.(provider, false));
798
+ };
799
+ }
800
+ subscribe(observer) {
801
+ const wasActive = this.active;
802
+ const gpuTiming = this.samplingOptions.gpuTiming;
803
+ this.observers.add(observer);
804
+ if (!wasActive)
805
+ for (const provider of this.providers.values())
806
+ this.startProvider(provider);
807
+ else if (gpuTiming !== this.samplingOptions.gpuTiming) {
808
+ for (const provider of this.providers.values()) {
809
+ provider.stop();
810
+ this.startProvider(provider);
811
+ }
812
+ }
813
+ return () => {
814
+ const previousGpuTiming = this.samplingOptions.gpuTiming;
815
+ this.observers.delete(observer);
816
+ if (!this.active)
817
+ for (const provider of this.providers.values())
818
+ provider.stop();
819
+ else if (previousGpuTiming !== this.samplingOptions.gpuTiming) {
820
+ for (const provider of this.providers.values()) {
821
+ provider.stop();
822
+ this.startProvider(provider);
823
+ }
824
+ }
825
+ };
826
+ }
827
+ notify(callback) {
828
+ for (const observer of this.observers) {
829
+ try {
830
+ callback(observer);
831
+ }
832
+ catch (error) {
833
+ console.warn('Runtime diagnostics observer failed', error);
834
+ }
835
+ }
836
+ }
837
+ recordRaf(at) {
838
+ if (this.active)
839
+ this.notify(observer => observer.raf?.(at));
840
+ }
841
+ recordUpdate(start) {
842
+ if (this.active) {
843
+ const at = runtimeNow();
844
+ this.notify(observer => observer.update?.(at, at - start));
845
+ }
846
+ }
847
+ measureRender(id, render) {
848
+ const provider = this.providers.get(id);
849
+ if (!this.active || !provider) {
850
+ render();
851
+ return;
852
+ }
853
+ let metrics = { drawCalls: null, canvasDrawOps: null, triangles: null, gpuMs: null };
854
+ try {
855
+ provider.beginFrame();
856
+ }
857
+ catch (error) {
858
+ console.warn('Runtime metrics beginFrame failed', error);
859
+ }
860
+ const start = runtimeNow();
861
+ try {
862
+ render();
863
+ }
864
+ finally {
865
+ const at = runtimeNow();
866
+ try {
867
+ metrics = provider.endFrame();
868
+ }
869
+ catch (error) {
870
+ console.warn('Runtime metrics endFrame failed', error);
871
+ }
872
+ const sample = { provider, at, submitMs: at - start, metrics };
873
+ this.notify(observer => observer.render?.(sample));
874
+ }
875
+ }
876
+ measureInput(timestamp, dispatch) {
877
+ if (!this.active)
878
+ return dispatch();
879
+ const start = runtimeNow();
880
+ // Legacy events may use epoch timestamps instead of performance time.
881
+ const relative = timestamp > 1e12 ? timestamp - (performance.timeOrigin || Date.now() - start) : timestamp;
882
+ const delay = Number.isFinite(relative) ? Math.max(0, start - relative) : 0;
883
+ try {
884
+ return dispatch();
885
+ }
886
+ finally {
887
+ this.notify(observer => observer.input?.(start, delay, runtimeNow() - start));
888
+ }
889
+ }
890
+ destroy() {
891
+ if (this.active)
892
+ for (const provider of this.providers.values())
893
+ provider.stop();
894
+ this.observers.clear();
895
+ this.providers.clear();
896
+ }
897
+ }
898
+
766
899
  /** Default Ticker Options */
767
900
  const defaultOptions = {
768
901
  autoStart: true,
@@ -789,6 +922,7 @@ class Ticker {
789
922
  this._ticker = () => {
790
923
  if (this._started) {
791
924
  this._requestId = requestAnimationFrame(this._ticker);
925
+ this.onRaf?.(runtimeNow());
792
926
  this.update();
793
927
  }
794
928
  };
@@ -891,7 +1025,41 @@ class Scene extends GameObject {
891
1025
  }
892
1026
 
893
1027
  /** Generated at build from package.json */
894
- const version = "0.1.24";
1028
+ const version = "0.1.26";
1029
+
1030
+ const listeners = new Set();
1031
+ let latestResourcesReady;
1032
+ function observeRuntimeMessages(listener) {
1033
+ listeners.add(listener);
1034
+ return () => listeners.delete(listener);
1035
+ }
1036
+ function getLatestResourcesReady() { return latestResourcesReady; }
1037
+ function postRuntimeMessage(message, targetOrigin = '*') {
1038
+ if (message.type === 'combos-game:resources-ready')
1039
+ latestResourcesReady = message;
1040
+ if (typeof window !== 'undefined') {
1041
+ try {
1042
+ if (window.parent && window.parent !== window)
1043
+ window.parent.postMessage(message, targetOrigin);
1044
+ else {
1045
+ const host = window;
1046
+ const bridge = typeof host.CombosRuntimeBridge?.postMessage === 'function' ? host.CombosRuntimeBridge : host.webkit?.messageHandlers?.combosRuntime;
1047
+ if (typeof bridge?.postMessage === 'function')
1048
+ bridge.postMessage(JSON.stringify(message));
1049
+ }
1050
+ }
1051
+ catch { /* detached frame or unavailable native host */ }
1052
+ }
1053
+ // Deliver after the lifecycle message has been handed to the host.
1054
+ for (const listener of listeners) {
1055
+ try {
1056
+ listener(message);
1057
+ }
1058
+ catch (error) {
1059
+ console.warn('Runtime message observer failed', error);
1060
+ }
1061
+ }
1062
+ }
895
1063
 
896
1064
  /**
897
1065
  * Sent after each `System.init` completes during `Game.addSystem`.
@@ -933,31 +1101,14 @@ function setParentNotifyTargetOrigin(targetOrigin) {
933
1101
  parentNotifyTargetOrigin = targetOrigin || "*";
934
1102
  }
935
1103
  function postToParent(payload, targetOrigin) {
936
- if (typeof window === "undefined")
937
- return;
938
- const parent = window.parent;
939
- if (parent && parent !== window) {
940
- try {
941
- parent.postMessage(payload, targetOrigin);
942
- }
943
- catch {
944
- /* ignore cross-origin or detached frame */
945
- }
946
- return;
947
- }
948
- try {
949
- const body = JSON.stringify(payload);
950
- const host = window;
951
- const bridge = host.CombosRuntimeBridge;
952
- if (typeof bridge?.postMessage === "function") {
953
- bridge.postMessage(body);
954
- return;
955
- }
956
- host.webkit?.messageHandlers?.combosRuntime?.postMessage(body);
957
- }
958
- catch {
959
- /* no native bridge */
960
- }
1104
+ const startTime = typeof window === 'undefined' ? undefined : window.startTime;
1105
+ const message = {
1106
+ ...payload,
1107
+ ...(typeof startTime === "number" && Number.isFinite(startTime)
1108
+ ? { duration: Math.max(0, Date.now() - startTime) }
1109
+ : {}),
1110
+ };
1111
+ postRuntimeMessage(message, targetOrigin);
961
1112
  }
962
1113
  /**
963
1114
  * Notifies the embedding page that a system (plugin) finished async/sync `init`.
@@ -1202,6 +1353,8 @@ const gameObjectPause = (gameObjects) => {
1202
1353
  class Game extends EventEmitter__default.default {
1203
1354
  constructor({ systems, frameRate = 60, autoStart = true, needScene = true, onSystemsBootstrapComplete, pluginInitNotifyTargetOrigin = "*", allowedMessageOrigins, } = {}) {
1204
1355
  super();
1356
+ this.diagnostics = new RuntimeDiagnostics();
1357
+ this.ready = false;
1205
1358
  /**
1206
1359
  * State of game
1207
1360
  * @defaultValue false
@@ -1231,6 +1384,7 @@ class Game extends EventEmitter__default.default {
1231
1384
  setParentNotifyTargetOrigin(pluginInitNotifyTargetOrigin);
1232
1385
  this.allowedMessageOrigins = mergeAllowedMessageOrigins(allowedMessageOrigins);
1233
1386
  this.ticker = new Ticker({ autoStart: false, frameRate });
1387
+ this.ticker.onRaf = at => this.diagnostics.recordRaf(at);
1234
1388
  this.initTicker();
1235
1389
  if (typeof window !== "undefined") {
1236
1390
  window.addEventListener("message", this.onHostMessage);
@@ -1263,7 +1417,10 @@ class Game extends EventEmitter__default.default {
1263
1417
  }
1264
1418
  }
1265
1419
  notifyReady(error) {
1420
+ this.ready = true;
1421
+ this.readyError = error;
1266
1422
  postParentGameReady(error, this.pluginInitNotifyTargetOrigin);
1423
+ this.emit(COMBOS_GAME_READY, { error });
1267
1424
  }
1268
1425
  /** Drain queued component observer events without starting the ticker. */
1269
1426
  flushObservedComponents() {
@@ -1281,6 +1438,7 @@ class Game extends EventEmitter__default.default {
1281
1438
  }
1282
1439
  notifyStateChanged() {
1283
1440
  postParentGameState({ playing: this.playing, started: this.started }, this.pluginInitNotifyTargetOrigin);
1441
+ this.emit(COMBOS_GAME_STATE_CHANGED, { playing: this.playing, started: this.started });
1284
1442
  }
1285
1443
  /** When `systems` is passed in the constructor, run async `init` for each before `loadScene` / `beforeReady` / `start`. */
1286
1444
  async bootstrapSystemsAndMaybeStart(systemsToAdd, needScene, autoStart, onComplete) {
@@ -1452,6 +1610,7 @@ class Game extends EventEmitter__default.default {
1452
1610
  */
1453
1611
  initTicker() {
1454
1612
  this.ticker.add((e) => {
1613
+ const diagnosticsStart = this.diagnostics.active ? runtimeNow() : null;
1455
1614
  this.scene && gameObjectLoop(e, this.gameObjects);
1456
1615
  for (const system of this.systems) {
1457
1616
  try {
@@ -1470,6 +1629,8 @@ class Game extends EventEmitter__default.default {
1470
1629
  console.error(`${systemClassName(system.constructor)} lateUpdate error`, e);
1471
1630
  }
1472
1631
  }
1632
+ if (diagnosticsStart !== null && this.diagnostics.active)
1633
+ this.diagnostics.recordUpdate(diagnosticsStart);
1473
1634
  });
1474
1635
  }
1475
1636
  /** Call onResume method on all gameObject's, and then call onResume method on all system */
@@ -1506,6 +1667,7 @@ class Game extends EventEmitter__default.default {
1506
1667
  }
1507
1668
  /** Destroy game instance */
1508
1669
  destroy() {
1670
+ this.diagnostics.destroy();
1509
1671
  if (typeof window !== "undefined") {
1510
1672
  window.removeEventListener("message", this.onHostMessage);
1511
1673
  }
@@ -2594,6 +2756,82 @@ function fitOrthographicDisplay(input) {
2594
2756
  };
2595
2757
  }
2596
2758
 
2759
+ /** Sparse asynchronous GPU queries, never waits for completion. */
2760
+ class WebGLGpuTimer {
2761
+ constructor(gl) {
2762
+ this.gl = gl;
2763
+ this.pending = [];
2764
+ this.current = null;
2765
+ this.frame = 0;
2766
+ this.latest = null;
2767
+ this.webgl2 = typeof gl?.createQuery === 'function';
2768
+ this.ext = gl?.getExtension(this.webgl2 ? 'EXT_disjoint_timer_query_webgl2' : 'EXT_disjoint_timer_query');
2769
+ }
2770
+ get supported() { return !!this.ext; }
2771
+ begin() {
2772
+ if (!this.ext || this.gl.isContextLost?.())
2773
+ return;
2774
+ const sampleThisFrame = this.frame++ % 30 === 0;
2775
+ if (!sampleThisFrame && !this.pending.length)
2776
+ return;
2777
+ const gl = this.gl, ext = this.ext;
2778
+ if (gl.getParameter(ext.GPU_DISJOINT_EXT)) {
2779
+ this.clear();
2780
+ return;
2781
+ }
2782
+ this.latest = null;
2783
+ this.pending = this.pending.filter(query => {
2784
+ const available = this.webgl2 ? gl.getQueryParameter(query, gl.QUERY_RESULT_AVAILABLE) : ext.getQueryObjectEXT(query, ext.QUERY_RESULT_AVAILABLE_EXT);
2785
+ if (!available)
2786
+ return true;
2787
+ const ns = this.webgl2 ? gl.getQueryParameter(query, gl.QUERY_RESULT) : ext.getQueryObjectEXT(query, ext.QUERY_RESULT_EXT);
2788
+ if (Number.isFinite(ns) && ns >= 0)
2789
+ this.latest = ns / 1e6;
2790
+ this.remove(query);
2791
+ return false;
2792
+ });
2793
+ if (!sampleThisFrame || this.pending.length >= 4)
2794
+ return;
2795
+ const active = this.webgl2 ? gl.getQuery(ext.TIME_ELAPSED_EXT, gl.CURRENT_QUERY) : ext.getQueryEXT(ext.TIME_ELAPSED_EXT, ext.CURRENT_QUERY_EXT);
2796
+ if (active)
2797
+ return;
2798
+ this.current = this.webgl2 ? gl.createQuery() : ext.createQueryEXT();
2799
+ if (!this.current)
2800
+ return;
2801
+ if (this.webgl2)
2802
+ gl.beginQuery(ext.TIME_ELAPSED_EXT, this.current);
2803
+ else
2804
+ ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, this.current);
2805
+ }
2806
+ end() {
2807
+ if (this.current) {
2808
+ if (this.webgl2)
2809
+ this.gl.endQuery(this.ext.TIME_ELAPSED_EXT);
2810
+ else
2811
+ this.ext.endQueryEXT(this.ext.TIME_ELAPSED_EXT);
2812
+ this.pending.push(this.current);
2813
+ this.current = null;
2814
+ }
2815
+ const value = this.latest;
2816
+ this.latest = null;
2817
+ return value;
2818
+ }
2819
+ remove(query) {
2820
+ if (this.webgl2)
2821
+ this.gl.deleteQuery(query);
2822
+ else
2823
+ this.ext.deleteQueryEXT(query);
2824
+ }
2825
+ clear() {
2826
+ if (this.current)
2827
+ this.end();
2828
+ for (const query of this.pending)
2829
+ this.remove(query);
2830
+ this.pending = [];
2831
+ this.latest = null;
2832
+ }
2833
+ }
2834
+
2597
2835
  /** Decorators util */
2598
2836
  const decorators = {
2599
2837
  IDEProp,
@@ -2614,31 +2852,37 @@ exports.Game = Game;
2614
2852
  exports.GameObject = GameObject;
2615
2853
  exports.IDEProp = IDEProp;
2616
2854
  exports.RESOURCE_TYPE_STRATEGY = RESOURCE_TYPE_STRATEGY;
2855
+ exports.RuntimeDiagnostics = RuntimeDiagnostics;
2617
2856
  exports.Scene = Scene;
2618
2857
  exports.System = System;
2858
+ exports.WebGLGpuTimer = WebGLGpuTimer;
2619
2859
  exports.applyCompressedImagePreference = applyCompressedImagePreference;
2620
2860
  exports.componentObserver = componentObserver;
2621
2861
  exports.compressedTextureUrl = compressedTextureUrl;
2622
2862
  exports.decorators = decorators;
2623
2863
  exports.displayBufferSize = displayBufferSize;
2624
2864
  exports.fitOrthographicDisplay = fitOrthographicDisplay;
2865
+ exports.getLatestResourcesReady = getLatestResourcesReady;
2625
2866
  exports.gpuSupportsCompressedTexture = gpuSupportsCompressedTexture;
2626
2867
  exports.imageFallbackUrl = imageFallbackUrl;
2627
2868
  exports.isAllowedMessageOrigin = isAllowedMessageOrigin;
2628
2869
  exports.mergeAllowedMessageOrigins = mergeAllowedMessageOrigins;
2629
2870
  exports.normalizeResourceSrc = normalizeResourceSrc;
2630
2871
  exports.normalizeSpritesheetData = normalizeSpritesheetData;
2872
+ exports.observeRuntimeMessages = observeRuntimeMessages;
2631
2873
  exports.parseSetPlayingMessage = parseSetPlayingMessage;
2632
2874
  exports.postParentGameReady = postParentGameReady;
2633
2875
  exports.postParentGameState = postParentGameState;
2634
2876
  exports.postParentPluginInitSuccess = postParentPluginInitSuccess;
2635
2877
  exports.postParentResourceProgress = postParentResourceProgress;
2636
2878
  exports.postParentResourcesReady = postParentResourcesReady;
2879
+ exports.postRuntimeMessage = postRuntimeMessage;
2637
2880
  exports.readSpriteClipSheet = readSpriteClipSheet;
2638
2881
  exports.resolveRenderQuality = resolveRenderQuality;
2639
2882
  exports.resolveSpriteClip = resolveSpriteClip;
2640
2883
  exports.resource = resource;
2641
2884
  exports.resourceLoader = resourceLoader;
2885
+ exports.runtimeNow = runtimeNow;
2642
2886
  exports.shouldPauseRendering = shouldPauseRendering;
2643
2887
  exports.spriteClipKeyOrder = spriteClipKeyOrder;
2644
2888
  exports.version = version;