@energy8platform/game-engine 0.34.2 → 0.35.0

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.
Files changed (45) hide show
  1. package/dist/audio.cjs.js +114 -59
  2. package/dist/audio.cjs.js.map +1 -1
  3. package/dist/audio.d.ts +25 -0
  4. package/dist/audio.esm.js +114 -59
  5. package/dist/audio.esm.js.map +1 -1
  6. package/dist/core.cjs.js +222 -66
  7. package/dist/core.cjs.js.map +1 -1
  8. package/dist/core.d.ts +25 -0
  9. package/dist/core.esm.js +223 -67
  10. package/dist/core.esm.js.map +1 -1
  11. package/dist/flow.cjs.js +246 -0
  12. package/dist/flow.cjs.js.map +1 -1
  13. package/dist/flow.d.ts +192 -33
  14. package/dist/flow.esm.js +238 -1
  15. package/dist/flow.esm.js.map +1 -1
  16. package/dist/host.cjs.js +343 -82
  17. package/dist/host.cjs.js.map +1 -1
  18. package/dist/host.d.ts +82 -2
  19. package/dist/host.esm.js +344 -83
  20. package/dist/host.esm.js.map +1 -1
  21. package/dist/index.cjs.js +222 -66
  22. package/dist/index.cjs.js.map +1 -1
  23. package/dist/index.d.ts +72 -0
  24. package/dist/index.esm.js +223 -67
  25. package/dist/index.esm.js.map +1 -1
  26. package/dist/scene-devtools.cjs.js +529 -115
  27. package/dist/scene-devtools.cjs.js.map +1 -1
  28. package/dist/scene-devtools.d.ts +187 -34
  29. package/dist/scene-devtools.esm.js +529 -115
  30. package/dist/scene-devtools.esm.js.map +1 -1
  31. package/dist/scene.cjs.js +704 -46
  32. package/dist/scene.cjs.js.map +1 -1
  33. package/dist/scene.d.ts +228 -41
  34. package/dist/scene.esm.js +698 -47
  35. package/dist/scene.esm.js.map +1 -1
  36. package/package.json +2 -2
  37. package/src/audio/AudioManager.ts +111 -53
  38. package/src/core/GameApplication.ts +47 -5
  39. package/src/host/buildConfig.ts +17 -4
  40. package/src/host/createSlotGame.ts +114 -12
  41. package/src/host/index.ts +3 -0
  42. package/src/host/types.ts +58 -0
  43. package/src/loading/LoadingScene.ts +76 -2
  44. package/src/loading/index.ts +6 -0
  45. package/src/types.ts +2 -0
package/dist/core.cjs.js CHANGED
@@ -681,6 +681,12 @@ class AudioManager {
681
681
  _categories;
682
682
  _masterGain = 1.0;
683
683
  _currentMusic = null;
684
+ /** Duck factor (0..1) from duckMusic/unduckMusic. A presentation state, not a player setting. */
685
+ _musicDuck = 1;
686
+ /** Crossfade ramp (0..1) for the track that is fading IN. 1 whenever no fade is running. */
687
+ _musicFade = 1;
688
+ /** Generation counter so a superseded crossfade ramp stops writing over the new track's. */
689
+ _musicFadeToken = 0;
684
690
  _unlocked = false;
685
691
  _unlockHandler = null;
686
692
  constructor(config) {
@@ -739,7 +745,10 @@ class AudioManager {
739
745
  if (this._globalMuted || this._categories[category].muted)
740
746
  return;
741
747
  const { sound } = this._soundModule;
742
- const vol = (options?.volume ?? 1) * this._categories[category].volume * this._masterGain;
748
+ // The master gain lives on the GLOBAL bus (`sound.volumeAll`, see applyVolumes) and @pixi/sound
749
+ // already multiplies it in — folding it in here as well squared it, so a master of 0.5 played
750
+ // sfx at 0.25.
751
+ const vol = (options?.volume ?? 1) * this._categories[category].volume;
743
752
  try {
744
753
  sound.play(alias, {
745
754
  volume: vol,
@@ -761,52 +770,50 @@ class AudioManager {
761
770
  if (!this._initialized || !this._soundModule)
762
771
  return;
763
772
  const { sound } = this._soundModule;
764
- // Stop current music with fade-out, start new music with fade-in
765
- if (this._currentMusic && fadeDuration > 0) {
766
- const prevAlias = this._currentMusic;
767
- this._currentMusic = alias;
768
- if (this._globalMuted || this._categories.music.muted)
769
- return;
770
- // Fade out the previous track
771
- this.fadeVolume(prevAlias, this._categories.music.volume * this._masterGain, 0, fadeDuration, () => {
772
- try {
773
- sound.stop(prevAlias);
774
- }
775
- catch { /* ignore */ }
776
- });
777
- // Start new track at zero volume, fade in
778
- try {
779
- sound.play(alias, {
780
- volume: 0,
781
- loop: true,
773
+ const prevAlias = this._currentMusic;
774
+ const crossfade = !!prevAlias && prevAlias !== alias && fadeDuration > 0;
775
+ // Retire the outgoing track. Its own SOUND-level volume is the only thing still pointing at it,
776
+ // so fading that to 0 is safe — nothing else writes it once `_currentMusic` has moved on.
777
+ if (prevAlias) {
778
+ if (crossfade) {
779
+ const from = this.soundVolumeOf(prevAlias);
780
+ this.fadeVolume(prevAlias, from, 0, fadeDuration, () => {
781
+ try {
782
+ sound.stop(prevAlias);
783
+ }
784
+ catch { /* ignore */ }
782
785
  });
783
- this.fadeVolume(alias, 0, this._categories.music.volume * this._masterGain, fadeDuration);
784
- }
785
- catch (e) {
786
- console.warn(`[AudioManager] Failed to play music "${alias}":`, e);
787
786
  }
788
- }
789
- else {
790
- // No crossfade — instant switch
791
- if (this._currentMusic) {
787
+ else {
792
788
  try {
793
- sound.stop(this._currentMusic);
789
+ sound.stop(prevAlias);
794
790
  }
795
791
  catch { /* ignore */ }
796
792
  }
797
- this._currentMusic = alias;
798
- if (this._globalMuted || this._categories.music.muted)
799
- return;
800
- try {
801
- sound.play(alias, {
802
- volume: this._categories.music.volume * this._masterGain,
803
- loop: true,
804
- });
805
- }
806
- catch (e) {
807
- console.warn(`[AudioManager] Failed to play music "${alias}":`, e);
808
- }
809
793
  }
794
+ this._currentMusic = alias;
795
+ this._musicFadeToken++; // any ramp still running belongs to a track we just replaced
796
+ // Deliberately started even while muted. Global mute is the @pixi/sound CONTEXT mute and a
797
+ // muted music category is a 0 term in `musicGain()` — both already make this inaudible, and
798
+ // both undo themselves the moment the player flips them back. Returning early here instead
799
+ // meant a track begun while muted never existed, so unmuting restored silence until some
800
+ // later mode change happened to switch tracks.
801
+ // The incoming track plays at INSTANCE volume 1 and carries its whole gain on the SOUND layer
802
+ // (`musicGain()`), which is the layer the slider, the duck and this fade all write. Splitting
803
+ // them across layers is what silenced every crossfade: the track was started at instance volume
804
+ // 0 and the ramp then moved the sound layer, whose product with 0 is 0 for the track's life.
805
+ // The gain is written BEFORE play() so the first frame is never at full volume.
806
+ this._musicFade = crossfade ? 0 : 1;
807
+ this.applyMusicGain();
808
+ try {
809
+ sound.play(alias, { volume: 1, loop: true });
810
+ }
811
+ catch (e) {
812
+ console.warn(`[AudioManager] Failed to play music "${alias}":`, e);
813
+ return;
814
+ }
815
+ if (crossfade)
816
+ this.rampMusicFade(fadeDuration);
810
817
  }
811
818
  /**
812
819
  * Stop current music.
@@ -822,6 +829,10 @@ class AudioManager {
822
829
  // ignore
823
830
  }
824
831
  this._currentMusic = null;
832
+ // Retire any running ramp and clear the fade term, so the next track does not inherit a
833
+ // half-finished crossfade and start silent.
834
+ this._musicFadeToken++;
835
+ this._musicFade = 1;
825
836
  }
826
837
  /**
827
838
  * Stop all sounds.
@@ -847,6 +858,9 @@ class AudioManager {
847
858
  */
848
859
  setVolume(category, volume) {
849
860
  this._categories[category].volume = Math.max(0, Math.min(1, volume));
861
+ // applyVolumes() re-pushes the music gain, so moving the Music slider is heard on the track
862
+ // that is ALREADY playing — it used to take effect only at the next playMusic (a mode change).
863
+ // SFX need no push: play() reads the category volume fresh on every call.
850
864
  this.applyVolumes();
851
865
  this.saveState();
852
866
  }
@@ -919,30 +933,19 @@ class AudioManager {
919
933
  * @param factor - Volume multiplier (0..1), e.g. 0.3 = 30% of normal
920
934
  */
921
935
  duckMusic(factor) {
922
- if (!this._initialized || !this._soundModule || !this._currentMusic)
923
- return;
924
- const { sound } = this._soundModule;
925
- const vol = this._categories.music.volume * factor;
926
- try {
927
- sound.volume(this._currentMusic, vol);
928
- }
929
- catch {
930
- // ignore
931
- }
936
+ // Held as a FACTOR rather than written as a finished volume: the duck used to write
937
+ // `category × factor` onto a track whose instance already carried the category volume, so it
938
+ // ducked to category², and unducking restored category² instead of category. Keeping it as one
939
+ // term of `musicGain()` also keeps the slider live while ducked.
940
+ this._musicDuck = Math.max(0, Math.min(1, factor));
941
+ this.applyMusicGain();
932
942
  }
933
943
  /**
934
944
  * Restore music to normal volume after ducking.
935
945
  */
936
946
  unduckMusic() {
937
- if (!this._initialized || !this._soundModule || !this._currentMusic)
938
- return;
939
- const { sound } = this._soundModule;
940
- try {
941
- sound.volume(this._currentMusic, this._categories.music.volume);
942
- }
943
- catch {
944
- // ignore
945
- }
947
+ this._musicDuck = 1;
948
+ this.applyMusicGain();
946
949
  }
947
950
  /**
948
951
  * Destroy the audio manager and free resources.
@@ -981,6 +984,57 @@ class AudioManager {
981
984
  };
982
985
  requestAnimationFrame(tick);
983
986
  }
987
+ /**
988
+ * The SOUND-layer gain for the running music track.
989
+ *
990
+ * @pixi/sound resolves a playing instance as `instance × sound × global` (WebAudioInstance.
991
+ * refresh). Each of those three has exactly ONE owner here, which is what keeps the mixer honest:
992
+ * global — the master gain (`applyVolumes`)
993
+ * sound — music: this function. sfx: untouched, left at 1.
994
+ * instance — sfx: the per-call volume × the sfx category. music: always 1.
995
+ * Everything that can move music volume — the player's slider, the category mute, a big-win duck,
996
+ * a crossfade — is a term below, so they compose instead of overwriting each other.
997
+ */
998
+ musicGain() {
999
+ const c = this._categories.music;
1000
+ return (c.muted ? 0 : 1) * c.volume * this._musicDuck * this._musicFade;
1001
+ }
1002
+ /** Push `musicGain()` at the current track. Safe before it starts playing and with none playing. */
1003
+ applyMusicGain() {
1004
+ if (!this._soundModule || !this._currentMusic)
1005
+ return;
1006
+ try {
1007
+ this._soundModule.sound.volume(this._currentMusic, this.musicGain());
1008
+ }
1009
+ catch {
1010
+ // ignore — alias not registered yet
1011
+ }
1012
+ }
1013
+ /** Current SOUND-layer volume of `alias`, or 0 when it cannot be read. */
1014
+ soundVolumeOf(alias) {
1015
+ try {
1016
+ return Number(this._soundModule.sound.volume(alias)) || 0;
1017
+ }
1018
+ catch {
1019
+ return 0;
1020
+ }
1021
+ }
1022
+ /** Ramp the crossfade term 0 → 1 over `durationMs`, recomposing the gain each frame so a slider
1023
+ * drag or a duck landing mid-fade is honoured rather than overwritten when the fade ends. */
1024
+ rampMusicFade(durationMs) {
1025
+ const token = this._musicFadeToken;
1026
+ const start = Date.now();
1027
+ const tick = () => {
1028
+ if (token !== this._musicFadeToken)
1029
+ return; // a newer track owns the music now
1030
+ const t = Math.min((Date.now() - start) / durationMs, 1);
1031
+ this._musicFade = t;
1032
+ this.applyMusicGain();
1033
+ if (t < 1)
1034
+ requestAnimationFrame(tick);
1035
+ };
1036
+ requestAnimationFrame(tick);
1037
+ }
984
1038
  applyVolumes() {
985
1039
  if (!this._soundModule)
986
1040
  return;
@@ -988,6 +1042,7 @@ class AudioManager {
988
1042
  // Global mute is owned by sound.muteAll()/unmuteAll() (context.muted),
989
1043
  // not by volumeAll — mixing both leaves mute un-undoable after reload.
990
1044
  sound.volumeAll = this._masterGain; // master multiplies the global bus
1045
+ this.applyMusicGain(); // category volume/mute reach the RUNNING track
991
1046
  }
992
1047
  setupMobileUnlock() {
993
1048
  if (this._unlocked)
@@ -1469,6 +1524,14 @@ class Scene {
1469
1524
  * tap-to-start → `waitCSSPreloaderTap`, then fades it out via
1470
1525
  * `removeCSSPreloader` before entering the game. One continuous overlay from
1471
1526
  * boot to gameplay — no second logo, no mid-load flash.
1527
+ *
1528
+ * When the game supplied its own overlay (`loading.externalOverlay`, e.g.
1529
+ * Artube's `LoaderViewController`), this scene is also the HAND-OVER point: that
1530
+ * overlay covered the gap this scene's existence ends — the bundle download,
1531
+ * Pixi init and the SDK handshake, none of which the engine can paint over. The
1532
+ * first thing `onEnter` does is mount the preloader, wait for it to be painted,
1533
+ * and dismiss the game's overlay. Everything after that line is identical on
1534
+ * every platform.
1472
1535
  */
1473
1536
  class LoadingScene extends Scene {
1474
1537
  _engine;
@@ -1486,6 +1549,10 @@ class LoadingScene extends Scene {
1486
1549
  this._targetScene = targetScene;
1487
1550
  this._targetData = targetData;
1488
1551
  this._config = engine.config.loading ?? {};
1552
+ // Take the screen from a game-supplied loading overlay, if there is one. Before any awaited
1553
+ // work: from here on the player is looking at OUR loading screen, and `_startTime` (which
1554
+ // `minDisplayTime` is measured from) must start when that becomes true.
1555
+ await this.takeOverFromExternalOverlay();
1489
1556
  this._startTime = Date.now();
1490
1557
  // Initialize asset manager
1491
1558
  await this._engine.assets.init();
@@ -1532,8 +1599,10 @@ class LoadingScene extends Scene {
1532
1599
  // Final snap to 100%
1533
1600
  this._displayedProgress = 1;
1534
1601
  this.updateLoaderBar(1);
1535
- // Wait for the player's tap — resolves immediately when tapToStart is
1536
- // false (the preloader honours that flag) then enter the game.
1602
+ // Wait for the player's tap — resolves immediately when tapToStart is false — then enter the
1603
+ // game. This is the preloader's gate and it reads the preloader's config, so it means the same
1604
+ // thing on every target: a game-supplied overlay has no say in it, and by now no part in the
1605
+ // screen either. It was dismissed at the hand-over above; the player is looking at ours.
1537
1606
  await loading.waitCSSPreloaderTap();
1538
1607
  await this.transitionToGame();
1539
1608
  }
@@ -1552,6 +1621,59 @@ class LoadingScene extends Scene {
1552
1621
  // (e.g. the scene was popped externally). Idempotent.
1553
1622
  void loading.removeCSSPreloader(this.hostElement());
1554
1623
  }
1624
+ // ─── Hand-over from a game-supplied overlay ────────────
1625
+ /**
1626
+ * Swap a game-supplied loading overlay for the engine's own loading screen.
1627
+ *
1628
+ * The overlay (Artube's) has been on screen since before this bundle was fetched, covering a gap
1629
+ * nothing of ours could. Its job ends here, at the first frame the engine paints; the player then
1630
+ * gets the game's own brand, progress bar and tap-to-start, exactly as on every other target.
1631
+ *
1632
+ * The order of the four steps is the whole design, and each is wrong on its own:
1633
+ *
1634
+ * 0. Wait out whatever the overlay is still owed on screen (`externalOverlayMinDisplayTime`,
1635
+ * default 1.5s, plus room for a phase crossfade already in flight). The gap this overlay
1636
+ * covers can be under half a second, which is not long enough for a partner's brand to
1637
+ * register. Waiting here — BEFORE mounting ours — rather than after is what keeps the two
1638
+ * screens' timelines from overlapping: our splash and brand floor start when the player can
1639
+ * actually see them, not behind someone else's overlay. On any boot slower than the floor
1640
+ * this step costs nothing, and on a non-Artube target it is not reached at all.
1641
+ * 1. Mount the preloader, opaque and full-bleed, while theirs is still up. Both are on screen
1642
+ * together for a few frames, so there is never a moment with neither, whatever happens next.
1643
+ * 2. Wait for that frame to actually be PAINTED — mounting only queues it. Dismissing theirs
1644
+ * before the paint is precisely the flash of bare background this ordering exists to avoid.
1645
+ * Two `requestAnimationFrame`s: the first callback runs before the frame it belongs to is
1646
+ * composited, the second after. Two frames is also enough for Pixi's own rAF-driven ticker
1647
+ * to have rendered this scene at least once, so "the loading scene has painted" is literally
1648
+ * true by the time step 3 runs.
1649
+ * 3. Only then dismiss theirs. Their `hideLoader()` plays a 0.3s fade and removes the element.
1650
+ * Not waiting for that fade is deliberate — it is an animation on someone else's element,
1651
+ * and blocking a boot on it would be a hang waiting to happen.
1652
+ *
1653
+ * Which of the two is visually on top is the host page's business, not ours, and it does NOT
1654
+ * change the guarantee. On a typical game page (`#game { position: fixed; inset: 0 }`) the fixed
1655
+ * container establishes a stacking context, so the preloader's z-index is scoped inside it and
1656
+ * Artube's `position: fixed; z-index: 9999` sits above — their fade then crossfades onto our
1657
+ * loading screen, which is what was observed live and looks right. On a page where ours wins
1658
+ * instead, their fade simply plays underneath, unseen. Either way the seam is covered, because
1659
+ * what step 2 buys is that OUR screen is already painted before theirs starts going away.
1660
+ */
1661
+ async takeOverFromExternalOverlay() {
1662
+ if (!loading.hasExternalOverlay())
1663
+ return;
1664
+ await loading.externalOverlayHold();
1665
+ loading.createCSSPreloader(this.hostElement(), this._config);
1666
+ await this.nextPaint();
1667
+ loading.releaseExternalOverlay();
1668
+ }
1669
+ /** Resolves after the browser has composited at least one frame (see step 2 above). */
1670
+ nextPaint() {
1671
+ if (typeof requestAnimationFrame !== 'function')
1672
+ return Promise.resolve();
1673
+ return new Promise((resolve) => {
1674
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
1675
+ });
1676
+ }
1555
1677
  // ─── Progress ──────────────────────────────────────────
1556
1678
  updateLoaderBar(progress) {
1557
1679
  loading.setCSSPreloaderProgress(Math.max(0, Math.min(1, progress)));
@@ -1806,14 +1928,37 @@ class GameApplication extends EventEmitter {
1806
1928
  return;
1807
1929
  }
1808
1930
  try {
1931
+ // 0. Adopt a game-supplied loading overlay (`loading.externalOverlay`) BEFORE anything that
1932
+ // can throw. Such an overlay is already on screen — Artube's is injected into index.html,
1933
+ // so it paints before this bundle is even fetched — and until the engine has adopted it,
1934
+ // the catch below has no way to take it down. A bad `container` selector (step 1) would
1935
+ // otherwise strand it on screen forever. It needs no container of ours.
1936
+ // Adoption is also where its minimum display time starts counting, which is why the
1937
+ // config value is handed over here rather than read at the hand-over: this is the
1938
+ // earliest moment the engine runs, and the overlay has been on screen since before it.
1939
+ const external = this.config.loading?.externalOverlay;
1940
+ if (external)
1941
+ loading.adoptExternalOverlay(external, this.config.loading?.externalOverlayMinDisplayTime);
1809
1942
  // 1. Resolve container element
1810
1943
  this._container = this.resolveContainer();
1811
- // 2. Show CSS preloader immediately (before PixiJS)
1812
- loading.createCSSPreloader(this._container, this.config.loading);
1944
+ // 2. Show the CSS preloader immediately (before PixiJS) — UNLESS a game-supplied overlay is
1945
+ // already covering the screen. In that case the preloader is mounted later, by LoadingScene
1946
+ // at its first frame, which is where the hand-over happens. Mounting it here instead would
1947
+ // put our brand over theirs for the whole of Pixi init and the SDK handshake, i.e. hand
1948
+ // over long before the gap the external overlay exists to cover has closed.
1949
+ if (!loading.hasExternalOverlay())
1950
+ loading.createCSSPreloader(this._container, this.config.loading);
1813
1951
  // 3. Initialize PixiJS
1814
1952
  await this.initPixi();
1953
+ // Milestones through the pre-first-frame gap, for a game-supplied overlay only (no-ops
1954
+ // otherwise, so the built-in preloader's behaviour is untouched). They are also what makes
1955
+ // Artube's loader crossfade from its dark partner phase to its branded one: that transition
1956
+ // fires on the first progress above zero, and without it the player would never see the
1957
+ // brand the loader exists to show. Values are honest weights of what remains, not a timer.
1958
+ loading.advanceExternalOverlay(0.35);
1815
1959
  // 4. Initialize SDK (if enabled)
1816
1960
  await this.initSDK();
1961
+ loading.advanceExternalOverlay(0.7);
1817
1962
  // 4b. Mount the branded game shell after the SDK handshake (optional)
1818
1963
  if (this.config.shell) {
1819
1964
  const { createGameShell } = await import('@energy8platform/shell/html');
@@ -1823,10 +1968,17 @@ class GameApplication extends EventEmitter {
1823
1968
  this.applySDKConfig();
1824
1969
  // 6. Initialize sub-systems
1825
1970
  this.initSubSystems();
1971
+ loading.advanceExternalOverlay(0.85);
1826
1972
  this.emit('initialized');
1827
1973
  // 7. Load assets. The CSS preloader stays on screen — LoadingScene drives
1828
1974
  // its progress/tap and removes it before entering the game, so there's
1829
1975
  // a single continuous overlay from boot to gameplay (no logo flash).
1976
+ //
1977
+ // With a game-supplied overlay the sequence has one extra step at the
1978
+ // front: LoadingScene MOUNTS the preloader, waits for its first painted
1979
+ // frame, and only then dismisses the external overlay. From that frame
1980
+ // on this path and every other are identical — same brand, same bar,
1981
+ // same tap-to-start.
1830
1982
  await this.loadAssets(firstScene, sceneData);
1831
1983
  this.emit('loaded');
1832
1984
  // 8. Start the game loop
@@ -1835,9 +1987,13 @@ class GameApplication extends EventEmitter {
1835
1987
  }
1836
1988
  catch (err) {
1837
1989
  console.error('[GameEngine] Failed to start:', err);
1838
- // Tear down the preloader so a failure doesn't strand the brand frame.
1839
- if (this._container)
1840
- loading.removeCSSPreloader(this._container);
1990
+ // Tear down both possible overlays so a failure strands neither brand frame. BOTH calls run:
1991
+ // a throw during the hand-over window can leave the preloader mounted AND the external
1992
+ // overlay still adopted, and each call is a no-op when there is nothing to remove. The
1993
+ // container may never have resolved (step 1 is inside this try), hence the `document.body`
1994
+ // fallback — the external overlay ignores the element entirely.
1995
+ loading.releaseExternalOverlay();
1996
+ void loading.removeCSSPreloader(this._container ?? document.body);
1841
1997
  this.emit('error', err instanceof Error ? err : new Error(String(err)));
1842
1998
  throw err;
1843
1999
  }