@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.
@@ -891,7 +891,7 @@ class Scene extends GameObject {
891
891
  }
892
892
 
893
893
  /** Generated at build from package.json */
894
- const version = "0.1.13";
894
+ const version = "0.1.14-beta.1";
895
895
 
896
896
  /**
897
897
  * Sent to `window.parent` after each `System.init` completes during `Game.addSystem`
@@ -1577,6 +1577,7 @@ const EXT_TO_TYPE = {
1577
1577
  jpg: 'jpg',
1578
1578
  jpeg: 'jpeg',
1579
1579
  webp: 'webp',
1580
+ ktx2: 'ktx2',
1580
1581
  json: 'json',
1581
1582
  tex: 'tex',
1582
1583
  ske: 'ske',
@@ -1645,6 +1646,38 @@ function wrapSlot(slot, value, resourceName) {
1645
1646
  url,
1646
1647
  };
1647
1648
  }
1649
+ function nonemptyUrl(url) {
1650
+ if (typeof url !== 'string')
1651
+ return undefined;
1652
+ const trimmed = url.trim();
1653
+ return trimmed || undefined;
1654
+ }
1655
+ /** KTX2 URL for one image slot: the slot itself, `ktx2`, or a `texture` entry. */
1656
+ function compressedTextureUrl(slot) {
1657
+ if (!slot)
1658
+ return undefined;
1659
+ if (slot.type === 'ktx2') {
1660
+ const own = nonemptyUrl(slot.url);
1661
+ if (own)
1662
+ return own;
1663
+ }
1664
+ const companion = nonemptyUrl(slot.ktx2);
1665
+ if (companion)
1666
+ return companion;
1667
+ const textures = Array.isArray(slot.texture) ? slot.texture : slot.texture ? [slot.texture] : [];
1668
+ for (const item of textures) {
1669
+ if (item?.type !== 'ktx2')
1670
+ continue;
1671
+ const url = nonemptyUrl(item.url);
1672
+ if (url)
1673
+ return url;
1674
+ }
1675
+ return undefined;
1676
+ }
1677
+ /** Raster URL used when KTX2 transcode has no compressed GPU target. */
1678
+ function imageFallbackUrl(slot) {
1679
+ return nonemptyUrl(slot?.fallback?.url);
1680
+ }
1648
1681
  function missingUrlError(resourceName, slot) {
1649
1682
  return new Error(`Resource "${resourceName}" src.${slot}.url is required. ` +
1650
1683
  `Use { type, url } (e.g. { type: "webp", url: "https://..." }). ` +
@@ -1677,6 +1710,108 @@ function normalizeResourceSrc(src, resourceType, resourceName = '(unnamed)') {
1677
1710
  return out;
1678
1711
  }
1679
1712
 
1713
+ function rasterType(type, url) {
1714
+ if (type && type !== 'ktx2')
1715
+ return type;
1716
+ const path = url.split('?')[0].split('#')[0];
1717
+ const dot = path.lastIndexOf('.');
1718
+ const ext = dot >= 0 ? path.slice(dot + 1).toLowerCase() : '';
1719
+ if (ext === 'png' || ext === 'jpg' || ext === 'jpeg' || ext === 'webp')
1720
+ return ext;
1721
+ return 'png';
1722
+ }
1723
+ function preferImageSlot(slot, supported) {
1724
+ const ktx2 = compressedTextureUrl(slot);
1725
+ if (!ktx2)
1726
+ return;
1727
+ if (supported) {
1728
+ if (slot.type !== 'ktx2' && slot.url && slot.url !== ktx2 && !imageFallbackUrl(slot)) {
1729
+ slot.fallback = { type: slot.type, url: slot.url };
1730
+ }
1731
+ slot.type = 'ktx2';
1732
+ slot.url = ktx2;
1733
+ return;
1734
+ }
1735
+ if (slot.type !== 'ktx2')
1736
+ return;
1737
+ const fallback = imageFallbackUrl(slot);
1738
+ if (!fallback)
1739
+ return;
1740
+ slot.type = rasterType(slot.fallback?.type, fallback);
1741
+ slot.url = fallback;
1742
+ }
1743
+ /** Point a failed KTX2 image slot at its raster fallback. Returns false when there is nothing to load. */
1744
+ function useRasterImageFallback(slot) {
1745
+ if (!slot || slot.type !== 'ktx2')
1746
+ return false;
1747
+ const fallback = imageFallbackUrl(slot);
1748
+ if (!fallback || fallback === slot.url)
1749
+ return false;
1750
+ slot.type = rasterType(slot.fallback?.type, fallback);
1751
+ slot.url = fallback;
1752
+ return true;
1753
+ }
1754
+ /**
1755
+ * Choose the image file for this load. A supported GPU downloads `ktx2`
1756
+ * and keeps the raster URL as `fallback`. Otherwise the raster URL stays
1757
+ * the file that will be downloaded.
1758
+ */
1759
+ function applyCompressedImagePreference(src, supported) {
1760
+ if (src.image)
1761
+ preferImageSlot(src.image, supported);
1762
+ }
1763
+
1764
+ const WEBGL_COMPRESSED_EXTENSIONS = [
1765
+ 'WEBGL_compressed_texture_astc',
1766
+ 'EXT_texture_compression_bptc',
1767
+ 'WEBGL_compressed_texture_s3tc',
1768
+ 'WEBGL_compressed_texture_etc',
1769
+ ];
1770
+ const WEBGPU_COMPRESSED_FEATURES = [
1771
+ 'texture-compression-astc',
1772
+ 'texture-compression-bc',
1773
+ 'texture-compression-etc2',
1774
+ ];
1775
+ let supportPromise = null;
1776
+ /** True when the GPU can take ASTC, BC7, BC3, or ETC2. Cached for the page. */
1777
+ function gpuSupportsCompressedTexture() {
1778
+ if (!supportPromise)
1779
+ supportPromise = probeCompressedTextureSupport();
1780
+ return supportPromise;
1781
+ }
1782
+ async function probeCompressedTextureSupport() {
1783
+ if (probeWebGL())
1784
+ return true;
1785
+ return probeWebGPU();
1786
+ }
1787
+ function probeWebGL() {
1788
+ if (typeof document === 'undefined')
1789
+ return false;
1790
+ const canvas = document.createElement('canvas');
1791
+ const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
1792
+ if (!gl)
1793
+ return false;
1794
+ const supported = WEBGL_COMPRESSED_EXTENSIONS.some((name) => gl.getExtension(name));
1795
+ const lose = gl.getExtension('WEBGL_lose_context');
1796
+ lose?.loseContext?.();
1797
+ return supported;
1798
+ }
1799
+ async function probeWebGPU() {
1800
+ const gpu = (typeof navigator === 'undefined' ? undefined : navigator.gpu);
1801
+ if (!gpu?.requestAdapter)
1802
+ return false;
1803
+ try {
1804
+ const adapter = await gpu.requestAdapter();
1805
+ const has = adapter?.features?.has;
1806
+ if (!has)
1807
+ return false;
1808
+ return WEBGPU_COMPRESSED_FEATURES.some((name) => has.call(adapter.features, name));
1809
+ }
1810
+ catch {
1811
+ return false;
1812
+ }
1813
+ }
1814
+
1680
1815
  const resourceLoader = {
1681
1816
  AbstractLoadStrategy: resourceLoader$1.AbstractLoadStrategy,
1682
1817
  AudioLoadStrategy: resourceLoader$1.AudioLoadStrategy,
@@ -1818,11 +1953,13 @@ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('dae', resourceLoader$1.Xhr
1818
1953
  resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('vert', resourceLoader$1.XhrResponseType.Text);
1819
1954
  resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('frag', resourceLoader$1.XhrResponseType.Text);
1820
1955
  resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('glsl', resourceLoader$1.XhrResponseType.Text);
1956
+ resourceLoader$1.XhrLoadStrategy.setExtensionXhrType('ktx2', resourceLoader$1.XhrResponseType.Buffer);
1821
1957
  const RESOURCE_TYPE_STRATEGY = {
1822
1958
  png: resourceLoader$1.ImageLoadStrategy,
1823
1959
  jpg: resourceLoader$1.ImageLoadStrategy,
1824
1960
  jpeg: resourceLoader$1.ImageLoadStrategy,
1825
1961
  webp: resourceLoader$1.ImageLoadStrategy,
1962
+ ktx2: resourceLoader$1.XhrLoadStrategy,
1826
1963
  json: resourceLoader$1.XhrLoadStrategy,
1827
1964
  tex: resourceLoader$1.XhrLoadStrategy,
1828
1965
  ske: resourceLoader$1.XhrLoadStrategy,
@@ -1972,14 +2109,38 @@ class Resource extends EventEmitter__default.default {
1972
2109
  if (!unLoadNames.length)
1973
2110
  return;
1974
2111
  const resolves = {};
1975
- const loader = this.getLoader(preload);
1976
2112
  unLoadNames.forEach(name => {
1977
2113
  this.promiseMap[name] = new Promise(r => (resolves[name] = r));
2114
+ });
2115
+ void this.beginLoad(unLoadNames, resolves, preload);
2116
+ }
2117
+ async beginLoad(names, resolves, preload) {
2118
+ let supported = false;
2119
+ try {
2120
+ supported = await gpuSupportsCompressedTexture();
2121
+ }
2122
+ catch {
2123
+ supported = false;
2124
+ }
2125
+ const loader = this.getLoader(preload);
2126
+ for (const name of names) {
1978
2127
  const res = this.resourcesMap[name];
1979
- for (const handler of this.preProcessResourceHandlers) {
1980
- handler(res);
2128
+ if (!res) {
2129
+ resolves[name]?.({});
2130
+ continue;
2131
+ }
2132
+ try {
2133
+ for (const handler of this.preProcessResourceHandlers) {
2134
+ handler(res);
2135
+ }
2136
+ res.src = normalizeResourceSrc(res.src, String(res.type), res.name);
2137
+ applyCompressedImagePreference(res.src, supported);
2138
+ }
2139
+ catch (err) {
2140
+ console.error(err);
2141
+ resolves[name]?.({});
2142
+ continue;
1981
2143
  }
1982
- res.src = normalizeResourceSrc(res.src, String(res.type), res.name);
1983
2144
  for (const key in res.src) {
1984
2145
  const resourceType = res.src[key].type;
1985
2146
  if (resourceType === 'data') {
@@ -1999,7 +2160,7 @@ class Resource extends EventEmitter__default.default {
1999
2160
  });
2000
2161
  }
2001
2162
  }
2002
- });
2163
+ }
2003
2164
  loader.load();
2004
2165
  }
2005
2166
  async doComplete(name, resolve, preload = false) {
@@ -2035,11 +2196,12 @@ class Resource extends EventEmitter__default.default {
2035
2196
  return Array.from(Object.keys(res.src)).every(resourceKey => res.data[resourceKey]);
2036
2197
  }
2037
2198
  getLoader(preload = false) {
2038
- let loader = this.loaders.find(({ loading }) => !loading);
2199
+ let loader = this.loaders.find((item) => !item.loading && !reservedLoaders.has(item));
2039
2200
  if (!loader) {
2040
2201
  loader = new resourceLoader$1.Loader();
2041
2202
  this.loaders.push(loader);
2042
2203
  }
2204
+ reservedLoaders.add(loader);
2043
2205
  if (preload) {
2044
2206
  loader.onStart.once(() => {
2045
2207
  this.progress.onStart();
@@ -2052,6 +2214,7 @@ class Resource extends EventEmitter__default.default {
2052
2214
  this.onError({ errMsg, resource, preload });
2053
2215
  });
2054
2216
  loader.onComplete.once(() => {
2217
+ reservedLoaders.delete(loader);
2055
2218
  loader.onLoad.detachAll();
2056
2219
  loader.onError.detachAll();
2057
2220
  loader.reset();
@@ -2065,7 +2228,20 @@ class Resource extends EventEmitter__default.default {
2065
2228
  this.doComplete(name, resolves[name], preload);
2066
2229
  }
2067
2230
  async onError({ errMsg, preload = false, resource }) {
2068
- const { metadata: { name, resolves }, } = resource;
2231
+ const { metadata: { key, name, resolves }, } = resource;
2232
+ const res = this.resourcesMap[name];
2233
+ if (key === 'image' && useRasterImageFallback(res?.src?.image)) {
2234
+ const slot = res.src.image;
2235
+ const loader = this.getLoader(preload);
2236
+ loader.add({
2237
+ url: slot.url,
2238
+ name: `${name}_image_fallback`,
2239
+ strategy: RESOURCE_TYPE_STRATEGY[slot.type],
2240
+ metadata: { key, name, resolves },
2241
+ });
2242
+ loader.load();
2243
+ return;
2244
+ }
2069
2245
  this._destroy(name, true);
2070
2246
  resolves[name]({});
2071
2247
  if (preload) {
@@ -2080,12 +2256,114 @@ class Resource extends EventEmitter__default.default {
2080
2256
  }
2081
2257
  }
2082
2258
  /** Resource manager single instance */
2259
+ const reservedLoaders = new WeakSet();
2083
2260
  const resource = new Resource();
2084
2261
  resource.registerInstance(exports.RESOURCE_TYPE.SHADER, (res) => ({
2085
2262
  vertex: typeof res.data?.vertex === 'string' ? res.data.vertex : '',
2086
2263
  fragment: typeof res.data?.fragment === 'string' ? res.data.fragment : '',
2087
2264
  }));
2088
2265
 
2266
+ const DEFAULT_MAX_PIXEL_RATIO = 2;
2267
+ const ADAPTIVE_WARMUP_MS = 3000;
2268
+ const ADAPTIVE_SLOW_FRAME_MS = 20;
2269
+ const ADAPTIVE_FAST_FRAME_MS = 12;
2270
+ const ADAPTIVE_SLOW_FRAME_COUNT = 30;
2271
+ const ADAPTIVE_FAST_FRAME_COUNT = 120;
2272
+ const ADAPTIVE_STEP = 0.5;
2273
+ const MIN_PIXEL_RATIO = 1;
2274
+ function isPositive(value) {
2275
+ return typeof value === 'number' && Number.isFinite(value) && value > 0;
2276
+ }
2277
+ function roundToHalf(value) {
2278
+ return Math.round(value * 2) / 2;
2279
+ }
2280
+ function readDevicePixelRatio(devicePixelRatio) {
2281
+ if (isPositive(devicePixelRatio))
2282
+ return devicePixelRatio;
2283
+ if (typeof window !== 'undefined' && isPositive(window.devicePixelRatio)) {
2284
+ return window.devicePixelRatio;
2285
+ }
2286
+ return 1;
2287
+ }
2288
+ function resolveRenderQuality(input = {}, defaults = {}) {
2289
+ const maxPixelRatio = isPositive(input.maxPixelRatio) ? input.maxPixelRatio : DEFAULT_MAX_PIXEL_RATIO;
2290
+ const explicit = isPositive(input.resolution)
2291
+ ? input.resolution
2292
+ : isPositive(input.pixelRatio)
2293
+ ? input.pixelRatio
2294
+ : undefined;
2295
+ const devicePixelRatio = readDevicePixelRatio(input.devicePixelRatio ?? defaults.devicePixelRatio);
2296
+ const pixelRatio = explicit ?? Math.min(devicePixelRatio, maxPixelRatio);
2297
+ return {
2298
+ pixelRatio,
2299
+ pixelRatioCeiling: pixelRatio,
2300
+ antialias: typeof input.antialias === 'boolean' ? input.antialias : pixelRatio < 2,
2301
+ pauseWhenHidden: typeof input.pauseWhenHidden === 'boolean' ? input.pauseWhenHidden : true,
2302
+ adaptivePixelRatio: typeof input.adaptivePixelRatio === 'boolean'
2303
+ ? input.adaptivePixelRatio
2304
+ : defaults.adaptivePixelRatio ?? false,
2305
+ powerPreference: input.powerPreference ?? 'high-performance',
2306
+ autoDensity: typeof input.autoDensity === 'boolean' ? input.autoDensity : true,
2307
+ explicitPixelRatio: explicit != null,
2308
+ };
2309
+ }
2310
+ function shouldPauseRendering(pauseWhenHidden) {
2311
+ return pauseWhenHidden && typeof document !== 'undefined' && document.hidden === true;
2312
+ }
2313
+ /**
2314
+ * After a warmup, a run of slow frames steps the pixel ratio down by 0.5
2315
+ * (floor 1). A longer run of fast frames steps it back up toward the ceiling.
2316
+ */
2317
+ class AdaptivePixelRatio {
2318
+ constructor(options) {
2319
+ this.elapsedMs = 0;
2320
+ this.slowFrames = 0;
2321
+ this.fastFrames = 0;
2322
+ this.pixelRatio = options.pixelRatio;
2323
+ this.ceiling = options.ceiling;
2324
+ this.enabled = options.enabled;
2325
+ }
2326
+ /** Returns the new ratio when it changes, otherwise null. */
2327
+ sample(deltaMs) {
2328
+ if (!this.enabled)
2329
+ return null;
2330
+ if (!(deltaMs > 0) || !Number.isFinite(deltaMs))
2331
+ return null;
2332
+ this.elapsedMs += deltaMs;
2333
+ if (this.elapsedMs < ADAPTIVE_WARMUP_MS)
2334
+ return null;
2335
+ if (deltaMs > ADAPTIVE_SLOW_FRAME_MS) {
2336
+ this.fastFrames = 0;
2337
+ this.slowFrames += 1;
2338
+ if (this.slowFrames >= ADAPTIVE_SLOW_FRAME_COUNT && this.pixelRatio > MIN_PIXEL_RATIO) {
2339
+ this.slowFrames = 0;
2340
+ const next = Math.max(MIN_PIXEL_RATIO, roundToHalf(this.pixelRatio - ADAPTIVE_STEP));
2341
+ if (next < this.pixelRatio) {
2342
+ this.pixelRatio = next;
2343
+ return next;
2344
+ }
2345
+ }
2346
+ return null;
2347
+ }
2348
+ if (deltaMs < ADAPTIVE_FAST_FRAME_MS) {
2349
+ this.slowFrames = 0;
2350
+ this.fastFrames += 1;
2351
+ if (this.fastFrames >= ADAPTIVE_FAST_FRAME_COUNT && this.pixelRatio < this.ceiling) {
2352
+ this.fastFrames = 0;
2353
+ const next = Math.min(this.ceiling, roundToHalf(this.pixelRatio + ADAPTIVE_STEP));
2354
+ if (next > this.pixelRatio) {
2355
+ this.pixelRatio = next;
2356
+ return next;
2357
+ }
2358
+ }
2359
+ return null;
2360
+ }
2361
+ this.slowFrames = 0;
2362
+ this.fastFrames = 0;
2363
+ return null;
2364
+ }
2365
+ }
2366
+
2089
2367
  /** Decorators util */
2090
2368
  const decorators = {
2091
2369
  IDEProp,
@@ -2093,6 +2371,7 @@ const decorators = {
2093
2371
  };
2094
2372
  console.log(`@combos-fun/engine version: ${version}`);
2095
2373
 
2374
+ exports.AdaptivePixelRatio = AdaptivePixelRatio;
2096
2375
  exports.COMBOS_GAME_PLUGIN_INIT_SUCCESS = COMBOS_GAME_PLUGIN_INIT_SUCCESS;
2097
2376
  exports.COMBOS_GAME_READY = COMBOS_GAME_READY;
2098
2377
  exports.COMBOS_GAME_SET_PLAYING = COMBOS_GAME_SET_PLAYING;
@@ -2105,8 +2384,12 @@ exports.IDEProp = IDEProp;
2105
2384
  exports.RESOURCE_TYPE_STRATEGY = RESOURCE_TYPE_STRATEGY;
2106
2385
  exports.Scene = Scene;
2107
2386
  exports.System = System;
2387
+ exports.applyCompressedImagePreference = applyCompressedImagePreference;
2108
2388
  exports.componentObserver = componentObserver;
2389
+ exports.compressedTextureUrl = compressedTextureUrl;
2109
2390
  exports.decorators = decorators;
2391
+ exports.gpuSupportsCompressedTexture = gpuSupportsCompressedTexture;
2392
+ exports.imageFallbackUrl = imageFallbackUrl;
2110
2393
  exports.isAllowedMessageOrigin = isAllowedMessageOrigin;
2111
2394
  exports.mergeAllowedMessageOrigins = mergeAllowedMessageOrigins;
2112
2395
  exports.normalizeResourceSrc = normalizeResourceSrc;
@@ -2115,7 +2398,9 @@ exports.parseSetPlayingMessage = parseSetPlayingMessage;
2115
2398
  exports.postParentGameReady = postParentGameReady;
2116
2399
  exports.postParentGameState = postParentGameState;
2117
2400
  exports.postParentPluginInitSuccess = postParentPluginInitSuccess;
2401
+ exports.resolveRenderQuality = resolveRenderQuality;
2118
2402
  exports.resource = resource;
2119
2403
  exports.resourceLoader = resourceLoader;
2404
+ exports.shouldPauseRendering = shouldPauseRendering;
2120
2405
  exports.version = version;
2121
2406
  //# sourceMappingURL=engine.cjs.js.map