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

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.
@@ -885,7 +885,7 @@ class Scene extends GameObject {
885
885
  }
886
886
 
887
887
  /** Generated at build from package.json */
888
- const version = "0.1.13";
888
+ const version = "0.1.14-beta.1";
889
889
 
890
890
  /**
891
891
  * Sent to `window.parent` after each `System.init` completes during `Game.addSystem`
@@ -1571,6 +1571,7 @@ const EXT_TO_TYPE = {
1571
1571
  jpg: 'jpg',
1572
1572
  jpeg: 'jpeg',
1573
1573
  webp: 'webp',
1574
+ ktx2: 'ktx2',
1574
1575
  json: 'json',
1575
1576
  tex: 'tex',
1576
1577
  ske: 'ske',
@@ -1639,6 +1640,38 @@ function wrapSlot(slot, value, resourceName) {
1639
1640
  url,
1640
1641
  };
1641
1642
  }
1643
+ function nonemptyUrl(url) {
1644
+ if (typeof url !== 'string')
1645
+ return undefined;
1646
+ const trimmed = url.trim();
1647
+ return trimmed || undefined;
1648
+ }
1649
+ /** KTX2 URL for one image slot: the slot itself, `ktx2`, or a `texture` entry. */
1650
+ function compressedTextureUrl(slot) {
1651
+ if (!slot)
1652
+ return undefined;
1653
+ if (slot.type === 'ktx2') {
1654
+ const own = nonemptyUrl(slot.url);
1655
+ if (own)
1656
+ return own;
1657
+ }
1658
+ const companion = nonemptyUrl(slot.ktx2);
1659
+ if (companion)
1660
+ return companion;
1661
+ const textures = Array.isArray(slot.texture) ? slot.texture : slot.texture ? [slot.texture] : [];
1662
+ for (const item of textures) {
1663
+ if (item?.type !== 'ktx2')
1664
+ continue;
1665
+ const url = nonemptyUrl(item.url);
1666
+ if (url)
1667
+ return url;
1668
+ }
1669
+ return undefined;
1670
+ }
1671
+ /** Raster URL used when KTX2 transcode has no compressed GPU target. */
1672
+ function imageFallbackUrl(slot) {
1673
+ return nonemptyUrl(slot?.fallback?.url);
1674
+ }
1642
1675
  function missingUrlError(resourceName, slot) {
1643
1676
  return new Error(`Resource "${resourceName}" src.${slot}.url is required. ` +
1644
1677
  `Use { type, url } (e.g. { type: "webp", url: "https://..." }). ` +
@@ -1671,6 +1704,108 @@ function normalizeResourceSrc(src, resourceType, resourceName = '(unnamed)') {
1671
1704
  return out;
1672
1705
  }
1673
1706
 
1707
+ function rasterType(type, url) {
1708
+ if (type && type !== 'ktx2')
1709
+ return type;
1710
+ const path = url.split('?')[0].split('#')[0];
1711
+ const dot = path.lastIndexOf('.');
1712
+ const ext = dot >= 0 ? path.slice(dot + 1).toLowerCase() : '';
1713
+ if (ext === 'png' || ext === 'jpg' || ext === 'jpeg' || ext === 'webp')
1714
+ return ext;
1715
+ return 'png';
1716
+ }
1717
+ function preferImageSlot(slot, supported) {
1718
+ const ktx2 = compressedTextureUrl(slot);
1719
+ if (!ktx2)
1720
+ return;
1721
+ if (supported) {
1722
+ if (slot.type !== 'ktx2' && slot.url && slot.url !== ktx2 && !imageFallbackUrl(slot)) {
1723
+ slot.fallback = { type: slot.type, url: slot.url };
1724
+ }
1725
+ slot.type = 'ktx2';
1726
+ slot.url = ktx2;
1727
+ return;
1728
+ }
1729
+ if (slot.type !== 'ktx2')
1730
+ return;
1731
+ const fallback = imageFallbackUrl(slot);
1732
+ if (!fallback)
1733
+ return;
1734
+ slot.type = rasterType(slot.fallback?.type, fallback);
1735
+ slot.url = fallback;
1736
+ }
1737
+ /** Point a failed KTX2 image slot at its raster fallback. Returns false when there is nothing to load. */
1738
+ function useRasterImageFallback(slot) {
1739
+ if (!slot || slot.type !== 'ktx2')
1740
+ return false;
1741
+ const fallback = imageFallbackUrl(slot);
1742
+ if (!fallback || fallback === slot.url)
1743
+ return false;
1744
+ slot.type = rasterType(slot.fallback?.type, fallback);
1745
+ slot.url = fallback;
1746
+ return true;
1747
+ }
1748
+ /**
1749
+ * Choose the image file for this load. A supported GPU downloads `ktx2`
1750
+ * and keeps the raster URL as `fallback`. Otherwise the raster URL stays
1751
+ * the file that will be downloaded.
1752
+ */
1753
+ function applyCompressedImagePreference(src, supported) {
1754
+ if (src.image)
1755
+ preferImageSlot(src.image, supported);
1756
+ }
1757
+
1758
+ const WEBGL_COMPRESSED_EXTENSIONS = [
1759
+ 'WEBGL_compressed_texture_astc',
1760
+ 'EXT_texture_compression_bptc',
1761
+ 'WEBGL_compressed_texture_s3tc',
1762
+ 'WEBGL_compressed_texture_etc',
1763
+ ];
1764
+ const WEBGPU_COMPRESSED_FEATURES = [
1765
+ 'texture-compression-astc',
1766
+ 'texture-compression-bc',
1767
+ 'texture-compression-etc2',
1768
+ ];
1769
+ let supportPromise = null;
1770
+ /** True when the GPU can take ASTC, BC7, BC3, or ETC2. Cached for the page. */
1771
+ function gpuSupportsCompressedTexture() {
1772
+ if (!supportPromise)
1773
+ supportPromise = probeCompressedTextureSupport();
1774
+ return supportPromise;
1775
+ }
1776
+ async function probeCompressedTextureSupport() {
1777
+ if (probeWebGL())
1778
+ return true;
1779
+ return probeWebGPU();
1780
+ }
1781
+ function probeWebGL() {
1782
+ if (typeof document === 'undefined')
1783
+ return false;
1784
+ const canvas = document.createElement('canvas');
1785
+ const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
1786
+ if (!gl)
1787
+ return false;
1788
+ const supported = WEBGL_COMPRESSED_EXTENSIONS.some((name) => gl.getExtension(name));
1789
+ const lose = gl.getExtension('WEBGL_lose_context');
1790
+ lose?.loseContext?.();
1791
+ return supported;
1792
+ }
1793
+ async function probeWebGPU() {
1794
+ const gpu = (typeof navigator === 'undefined' ? undefined : navigator.gpu);
1795
+ if (!gpu?.requestAdapter)
1796
+ return false;
1797
+ try {
1798
+ const adapter = await gpu.requestAdapter();
1799
+ const has = adapter?.features?.has;
1800
+ if (!has)
1801
+ return false;
1802
+ return WEBGPU_COMPRESSED_FEATURES.some((name) => has.call(adapter.features, name));
1803
+ }
1804
+ catch {
1805
+ return false;
1806
+ }
1807
+ }
1808
+
1674
1809
  const resourceLoader = {
1675
1810
  AbstractLoadStrategy,
1676
1811
  AudioLoadStrategy,
@@ -1812,11 +1947,13 @@ XhrLoadStrategy.setExtensionXhrType('dae', XhrResponseType.Text);
1812
1947
  XhrLoadStrategy.setExtensionXhrType('vert', XhrResponseType.Text);
1813
1948
  XhrLoadStrategy.setExtensionXhrType('frag', XhrResponseType.Text);
1814
1949
  XhrLoadStrategy.setExtensionXhrType('glsl', XhrResponseType.Text);
1950
+ XhrLoadStrategy.setExtensionXhrType('ktx2', XhrResponseType.Buffer);
1815
1951
  const RESOURCE_TYPE_STRATEGY = {
1816
1952
  png: ImageLoadStrategy,
1817
1953
  jpg: ImageLoadStrategy,
1818
1954
  jpeg: ImageLoadStrategy,
1819
1955
  webp: ImageLoadStrategy,
1956
+ ktx2: XhrLoadStrategy,
1820
1957
  json: XhrLoadStrategy,
1821
1958
  tex: XhrLoadStrategy,
1822
1959
  ske: XhrLoadStrategy,
@@ -1966,14 +2103,38 @@ class Resource extends EventEmitter {
1966
2103
  if (!unLoadNames.length)
1967
2104
  return;
1968
2105
  const resolves = {};
1969
- const loader = this.getLoader(preload);
1970
2106
  unLoadNames.forEach(name => {
1971
2107
  this.promiseMap[name] = new Promise(r => (resolves[name] = r));
2108
+ });
2109
+ void this.beginLoad(unLoadNames, resolves, preload);
2110
+ }
2111
+ async beginLoad(names, resolves, preload) {
2112
+ let supported = false;
2113
+ try {
2114
+ supported = await gpuSupportsCompressedTexture();
2115
+ }
2116
+ catch {
2117
+ supported = false;
2118
+ }
2119
+ const loader = this.getLoader(preload);
2120
+ for (const name of names) {
1972
2121
  const res = this.resourcesMap[name];
1973
- for (const handler of this.preProcessResourceHandlers) {
1974
- handler(res);
2122
+ if (!res) {
2123
+ resolves[name]?.({});
2124
+ continue;
2125
+ }
2126
+ try {
2127
+ for (const handler of this.preProcessResourceHandlers) {
2128
+ handler(res);
2129
+ }
2130
+ res.src = normalizeResourceSrc(res.src, String(res.type), res.name);
2131
+ applyCompressedImagePreference(res.src, supported);
2132
+ }
2133
+ catch (err) {
2134
+ console.error(err);
2135
+ resolves[name]?.({});
2136
+ continue;
1975
2137
  }
1976
- res.src = normalizeResourceSrc(res.src, String(res.type), res.name);
1977
2138
  for (const key in res.src) {
1978
2139
  const resourceType = res.src[key].type;
1979
2140
  if (resourceType === 'data') {
@@ -1993,7 +2154,7 @@ class Resource extends EventEmitter {
1993
2154
  });
1994
2155
  }
1995
2156
  }
1996
- });
2157
+ }
1997
2158
  loader.load();
1998
2159
  }
1999
2160
  async doComplete(name, resolve, preload = false) {
@@ -2029,11 +2190,12 @@ class Resource extends EventEmitter {
2029
2190
  return Array.from(Object.keys(res.src)).every(resourceKey => res.data[resourceKey]);
2030
2191
  }
2031
2192
  getLoader(preload = false) {
2032
- let loader = this.loaders.find(({ loading }) => !loading);
2193
+ let loader = this.loaders.find((item) => !item.loading && !reservedLoaders.has(item));
2033
2194
  if (!loader) {
2034
2195
  loader = new Loader();
2035
2196
  this.loaders.push(loader);
2036
2197
  }
2198
+ reservedLoaders.add(loader);
2037
2199
  if (preload) {
2038
2200
  loader.onStart.once(() => {
2039
2201
  this.progress.onStart();
@@ -2046,6 +2208,7 @@ class Resource extends EventEmitter {
2046
2208
  this.onError({ errMsg, resource, preload });
2047
2209
  });
2048
2210
  loader.onComplete.once(() => {
2211
+ reservedLoaders.delete(loader);
2049
2212
  loader.onLoad.detachAll();
2050
2213
  loader.onError.detachAll();
2051
2214
  loader.reset();
@@ -2059,7 +2222,20 @@ class Resource extends EventEmitter {
2059
2222
  this.doComplete(name, resolves[name], preload);
2060
2223
  }
2061
2224
  async onError({ errMsg, preload = false, resource }) {
2062
- const { metadata: { name, resolves }, } = resource;
2225
+ const { metadata: { key, name, resolves }, } = resource;
2226
+ const res = this.resourcesMap[name];
2227
+ if (key === 'image' && useRasterImageFallback(res?.src?.image)) {
2228
+ const slot = res.src.image;
2229
+ const loader = this.getLoader(preload);
2230
+ loader.add({
2231
+ url: slot.url,
2232
+ name: `${name}_image_fallback`,
2233
+ strategy: RESOURCE_TYPE_STRATEGY[slot.type],
2234
+ metadata: { key, name, resolves },
2235
+ });
2236
+ loader.load();
2237
+ return;
2238
+ }
2063
2239
  this._destroy(name, true);
2064
2240
  resolves[name]({});
2065
2241
  if (preload) {
@@ -2074,12 +2250,114 @@ class Resource extends EventEmitter {
2074
2250
  }
2075
2251
  }
2076
2252
  /** Resource manager single instance */
2253
+ const reservedLoaders = new WeakSet();
2077
2254
  const resource = new Resource();
2078
2255
  resource.registerInstance(RESOURCE_TYPE.SHADER, (res) => ({
2079
2256
  vertex: typeof res.data?.vertex === 'string' ? res.data.vertex : '',
2080
2257
  fragment: typeof res.data?.fragment === 'string' ? res.data.fragment : '',
2081
2258
  }));
2082
2259
 
2260
+ const DEFAULT_MAX_PIXEL_RATIO = 2;
2261
+ const ADAPTIVE_WARMUP_MS = 3000;
2262
+ const ADAPTIVE_SLOW_FRAME_MS = 20;
2263
+ const ADAPTIVE_FAST_FRAME_MS = 12;
2264
+ const ADAPTIVE_SLOW_FRAME_COUNT = 30;
2265
+ const ADAPTIVE_FAST_FRAME_COUNT = 120;
2266
+ const ADAPTIVE_STEP = 0.5;
2267
+ const MIN_PIXEL_RATIO = 1;
2268
+ function isPositive(value) {
2269
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
2270
+ }
2271
+ function roundToHalf(value) {
2272
+ return Math.round(value * 2) / 2;
2273
+ }
2274
+ function readDevicePixelRatio(devicePixelRatio) {
2275
+ if (isPositive(devicePixelRatio))
2276
+ return devicePixelRatio;
2277
+ if (typeof window !== 'undefined' && isPositive(window.devicePixelRatio)) {
2278
+ return window.devicePixelRatio;
2279
+ }
2280
+ return 1;
2281
+ }
2282
+ function resolveRenderQuality(input = {}, defaults = {}) {
2283
+ const maxPixelRatio = isPositive(input.maxPixelRatio) ? input.maxPixelRatio : DEFAULT_MAX_PIXEL_RATIO;
2284
+ const explicit = isPositive(input.resolution)
2285
+ ? input.resolution
2286
+ : isPositive(input.pixelRatio)
2287
+ ? input.pixelRatio
2288
+ : undefined;
2289
+ const devicePixelRatio = readDevicePixelRatio(input.devicePixelRatio ?? defaults.devicePixelRatio);
2290
+ const pixelRatio = explicit ?? Math.min(devicePixelRatio, maxPixelRatio);
2291
+ return {
2292
+ pixelRatio,
2293
+ pixelRatioCeiling: pixelRatio,
2294
+ antialias: typeof input.antialias === 'boolean' ? input.antialias : pixelRatio < 2,
2295
+ pauseWhenHidden: typeof input.pauseWhenHidden === 'boolean' ? input.pauseWhenHidden : true,
2296
+ adaptivePixelRatio: typeof input.adaptivePixelRatio === 'boolean'
2297
+ ? input.adaptivePixelRatio
2298
+ : defaults.adaptivePixelRatio ?? false,
2299
+ powerPreference: input.powerPreference ?? 'high-performance',
2300
+ autoDensity: typeof input.autoDensity === 'boolean' ? input.autoDensity : true,
2301
+ explicitPixelRatio: explicit != null,
2302
+ };
2303
+ }
2304
+ function shouldPauseRendering(pauseWhenHidden) {
2305
+ return pauseWhenHidden && typeof document !== 'undefined' && document.hidden === true;
2306
+ }
2307
+ /**
2308
+ * After a warmup, a run of slow frames steps the pixel ratio down by 0.5
2309
+ * (floor 1). A longer run of fast frames steps it back up toward the ceiling.
2310
+ */
2311
+ class AdaptivePixelRatio {
2312
+ constructor(options) {
2313
+ this.elapsedMs = 0;
2314
+ this.slowFrames = 0;
2315
+ this.fastFrames = 0;
2316
+ this.pixelRatio = options.pixelRatio;
2317
+ this.ceiling = options.ceiling;
2318
+ this.enabled = options.enabled;
2319
+ }
2320
+ /** Returns the new ratio when it changes, otherwise null. */
2321
+ sample(deltaMs) {
2322
+ if (!this.enabled)
2323
+ return null;
2324
+ if (!(deltaMs > 0) || !Number.isFinite(deltaMs))
2325
+ return null;
2326
+ this.elapsedMs += deltaMs;
2327
+ if (this.elapsedMs < ADAPTIVE_WARMUP_MS)
2328
+ return null;
2329
+ if (deltaMs > ADAPTIVE_SLOW_FRAME_MS) {
2330
+ this.fastFrames = 0;
2331
+ this.slowFrames += 1;
2332
+ if (this.slowFrames >= ADAPTIVE_SLOW_FRAME_COUNT && this.pixelRatio > MIN_PIXEL_RATIO) {
2333
+ this.slowFrames = 0;
2334
+ const next = Math.max(MIN_PIXEL_RATIO, roundToHalf(this.pixelRatio - ADAPTIVE_STEP));
2335
+ if (next < this.pixelRatio) {
2336
+ this.pixelRatio = next;
2337
+ return next;
2338
+ }
2339
+ }
2340
+ return null;
2341
+ }
2342
+ if (deltaMs < ADAPTIVE_FAST_FRAME_MS) {
2343
+ this.slowFrames = 0;
2344
+ this.fastFrames += 1;
2345
+ if (this.fastFrames >= ADAPTIVE_FAST_FRAME_COUNT && this.pixelRatio < this.ceiling) {
2346
+ this.fastFrames = 0;
2347
+ const next = Math.min(this.ceiling, roundToHalf(this.pixelRatio + ADAPTIVE_STEP));
2348
+ if (next > this.pixelRatio) {
2349
+ this.pixelRatio = next;
2350
+ return next;
2351
+ }
2352
+ }
2353
+ return null;
2354
+ }
2355
+ this.slowFrames = 0;
2356
+ this.fastFrames = 0;
2357
+ return null;
2358
+ }
2359
+ }
2360
+
2083
2361
  /** Decorators util */
2084
2362
  const decorators = {
2085
2363
  IDEProp,
@@ -2087,5 +2365,5 @@ const decorators = {
2087
2365
  };
2088
2366
  console.log(`@combos-fun/engine version: ${version}`);
2089
2367
 
2090
- export { COMBOS_GAME_PLUGIN_INIT_SUCCESS, COMBOS_GAME_READY, COMBOS_GAME_SET_PLAYING, COMBOS_GAME_STATE_CHANGED, Component, DEFAULT_ALLOWED_MESSAGE_HOST_SUFFIXES, Game, GameObject, IDEProp, LOAD_EVENT, LOAD_SCENE_MODE, ObserverType as OBSERVER_TYPE, RESOURCE_TYPE, RESOURCE_TYPE_STRATEGY, Scene, System, componentObserver, decorators, isAllowedMessageOrigin, mergeAllowedMessageOrigins, normalizeResourceSrc, normalizeSpritesheetData, parseSetPlayingMessage, postParentGameReady, postParentGameState, postParentPluginInitSuccess, resource, resourceLoader, version };
2368
+ 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, resolveRenderQuality, resource, resourceLoader, shouldPauseRendering, version };
2091
2369
  //# sourceMappingURL=engine.esm.js.map