Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(project): the settings a runtime is told are derived once

yhhbaa56b7a4e0d
diff --git a/desktop/src/panels/AudioMixerPanel.tsx b/desktop/src/panels/AudioMixerPanel.tsx
index 97e79cf76..287328a96 100644
--- a/desktop/src/panels/AudioMixerPanel.tsx
+++ b/desktop/src/panels/AudioMixerPanel.tsx
@@ -13,11 +13,9 @@
import { useSyncExternalStore } from 'react';
import { Plus, Trash2, VolumeX, Volume2 } from 'lucide-react';
import {
- Audio, applyAudioProjectConfig,
type AudioProjectConfig, type AudioBusDecl, type BusEffectDef,
} from 'esengine';
import { ProjectStore } from '@/project/ProjectStore';
-import { EngineHost } from '@/engine/EngineHost';
import { Select } from '@/components/Select';
import { EmptyState } from '@/components/EmptyState';
import { t } from '@/i18n';
@@ -42,11 +40,12 @@ function stripsOf(config: AudioProjectConfig): StripModel[] {
return strips;
}
-/** Persist + live-apply one new config state. */
+/** Persist one new config state; the store live-applies it to the edit session
+ * (setAudio → applyEditorRuntimeConfig), the same way opening a project does —
+ * this panel used to be the ONLY thing that applied the mixer, so a project's
+ * bus levels were silent until someone opened it. */
function commit(next: AudioProjectConfig): void {
void ProjectStore.setAudio(next);
- const audio = EngineHost.getResource(Audio);
- if (audio) applyAudioProjectConfig(audio, next);
}
/** Replace/patch one bus's declaration inside the config. */
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index e20e4c950..447e92c90 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1,8 +1,12 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { createStore } from 'zustand/vanilla';
-import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, validateOverrides, setTextureParams, setTextureSliceBorder, textureImportSettingsFrom, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides, resolveAssetGroup, folderGroupMode, withFolderGroup, folderAlwaysInclude, withFolderAlwaysInclude, withActiveRemoteRoot } from 'esengine';
+import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, validateOverrides, setTextureParams, setTextureSliceBorder, textureImportSettingsFrom, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides, resolveAssetGroup, folderGroupMode, withFolderGroup, folderAlwaysInclude, withFolderAlwaysInclude, withActiveRemoteRoot, Audio, applyAudioProjectConfig } from 'esengine';
import { importerDefaults, applyImporterEdit } from './assetImporter';
+import {
+ runtimeConfigOf, packagedRuntimeFields, normalizeCollisionLayers, normalizeCollisionLayerMasks,
+ type RuntimeProjectConfig,
+} from './runtimeConfig';
import type { ParsedTextureImportSettings } from 'esengine';
import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides, StaleOverride, PrefabOverride, AddressableManifest, AssetGroupsConfig, AssetGroupMode } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
@@ -47,16 +51,6 @@ import { projectReplacing } from './projectReplacing';
import { fsRefresh } from './fsRefresh';
import type { DocSnapshot } from '@/document/DirtyRegistry';
-/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */
-function normalizeLayers(layers?: string[]): string[] {
- return Array.from({ length: 16 }, (_, i) => layers?.[i] ?? (i === 0 ? 'Default' : ''));
-}
-
-/** Pad/truncate the collision matrix to 16 rows; absent rows default to all-collide. */
-function normalizeLayerMasks(masks?: number[]): number[] {
- return Array.from({ length: 16 }, (_, i) => (typeof masks?.[i] === 'number' ? masks[i] & 0xffff : 0xffff));
-}
-
/** Whether an asset of the editor `type` is a valid pick for a `fieldType` slot. */
function assetMatchesSlot(type: AssetType, path: string, fieldType?: string): boolean {
if (!fieldType) return true;
@@ -536,7 +530,7 @@ class ProjectStoreImpl {
if (!st) return;
// Project-level render config (WYSIWYG in the edit viewport). Applied here —
// the one path that runs both on project open and once the engine is ready.
- this.applySortingLayerModes();
+ this.applyEditorRuntimeConfig();
const found = await this.firstReadableScene([
st.workspace.lastOpenedScene,
st.defaultScene,
@@ -628,9 +622,10 @@ class ProjectStoreImpl {
for (const { id, tag } of tags) SceneModel.setPrefabTag(id, tag);
EngineHost.syncEditorViewToScene();
- // Edit-world live theme: re-resolve ThemeStyle-tagged widgets against the
- // project's effective theme, matching what a shipped runtime boots with.
- applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());
+ // Edit-world live settings: the theme re-resolves ThemeStyle-tagged widgets
+ // and the mixer/sorting masks re-apply, matching what a shipped runtime
+ // boots with.
+ this.applyEditorRuntimeConfig();
// Surface any instance overrides the loader just dropped (they point at prefab
// structure that no longer exists) — otherwise the customization loss is silent.
this.detectPrefabConflicts(raw);
@@ -1699,46 +1694,21 @@ class ProjectStoreImpl {
if (!/\.esscene$/i.test(q) || q === currentScene) continue;
extraScenes.push({ name: exportSceneName(q), path: q });
}
- // Carry the project's physics world config so the realm installs physics (even for
- // runtime-spawned bodies the static scene doesn't show) and matches the editor's
- // Project Settings. The collision matrix is sent ONLY when configured — otherwise
- // a layer's mask would override each collider's own maskBits (the two are exclusive).
- const f = this.physicsFeature();
- const physicsConfig: PhysicsPluginConfig = {
- gravity: f.gravity,
- fixedTimestep: f.fixedTimestep,
- subStepCount: f.subStepCount,
- contactHertz: f.contactHertz,
- contactDampingRatio: f.contactDampingRatio,
- contactSpeed: f.contactSpeed,
- enableSleep: f.enableSleep,
- enableContinuous: f.enableContinuous,
- };
- // Send the collision matrix ONLY when it actually restricts a pair — an all-collide
- // matrix would otherwise override each single-layer collider's own maskBits for nothing.
- if (f.collisionLayerMasks.some((m) => (m & 0xffff) !== 0xffff)) {
- physicsConfig.collisionLayerMasks = f.collisionLayerMasks;
- }
- const ySortLayers = this.ySortMask();
- const depthLayers = this.depthMask();
- const audioConfig = this.audioFeature();
- const colorSpace = this.renderingFeature().colorSpace;
- // Camera fit: only sent when the project opts in (scaleMode ≥ 0), so a played
- // scene with no fit boots exactly as before.
- const screenFit = this.screenFit();
- const uiTheme = this.uiTheme();
+ // The project's settings, from the ONE derivation an exported build also uses
+ // — Play is a rehearsal of shipping, and a field only one of them carried is
+ // what made the rehearsal lie (the 2.5D depth mask reached here and no
+ // shipped build at all). Physics rides along whole: the realm installs it
+ // even for runtime-spawned bodies the static scene doesn't show.
+ const rc = this.runtimeConfig();
const uiThemeOverrides = this.uiThemeOverrides();
return {
- sceneData, assetManifest, manifest: this.buildPlayManifest(), physicsEnabled: f.enabled, physicsConfig,
+ sceneData, assetManifest, manifest: this.buildPlayManifest(),
+ physicsEnabled: rc.physicsEnabled, physicsConfig: rc.physicsConfig,
...(currentScene ? { entrySceneName: exportSceneName(currentScene) } : {}),
...(extraScenes.length > 0 ? { extraScenes } : {}),
- ...(audioConfig.buses ? { audioConfig } : {}),
- ...(uiTheme === 'light' ? { uiTheme } : {}),
+ ...(rc.audioConfig.buses ? { audioConfig: rc.audioConfig } : {}),
...(uiThemeOverrides ? { uiThemeOverrides } : {}),
- ...(ySortLayers !== 0 ? { ySortLayers } : {}),
- ...(depthLayers !== 0 ? { depthLayers } : {}),
- ...(colorSpace === 'linear' ? { colorSpace } : {}),
- ...(screenFit.scaleMode >= 0 ? { screenFit } : {}),
+ ...packagedRuntimeFields(rc),
};
}
@@ -1796,7 +1766,7 @@ class ProjectStoreImpl {
if (ui) features.ui = ui;
else delete features.ui;
this.store.setState({ project: { ...st, features } });
- applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());
+ this.applyEditorRuntimeConfig();
await this.patchManifest((raw) => {
const rf = { ...(raw.features as Record<string, unknown> ?? {}) };
if (ui) rf.ui = ui;
@@ -1815,6 +1785,7 @@ class ProjectStoreImpl {
if (!st) return;
const features: ProjectFeatures = { ...st.features, audio: config };
this.store.setState({ project: { ...st, features } });
+ this.applyEditorRuntimeConfig();
await this.patchManifest((raw) => {
raw.features = { ...(raw.features as Record<string, unknown> ?? {}), audio: config };
}, t('proj.saveAudioFailed'));
@@ -1829,19 +1800,24 @@ class ProjectStoreImpl {
contactDampingRatio: number; contactSpeed: number;
enableSleep: boolean; enableContinuous: boolean;
} {
- const p = this.state?.features?.physics;
+ // The solver values come from the SAME derivation the runtime is given, so
+ // the settings page cannot show one set of effective defaults while the game
+ // runs on another. The layer NAMES are editor-only (a runtime filters by
+ // bits), which is why they are added here rather than carried through.
+ const rc = this.runtimeConfig();
+ const c = rc.physicsConfig;
return {
- enabled: p?.enabled ?? false,
- gravity: p?.gravity ?? { x: 0, y: -9.81 },
- collisionLayers: normalizeLayers(p?.collisionLayers),
- collisionLayerMasks: normalizeLayerMasks(p?.collisionLayerMasks),
- fixedTimestep: p?.fixedTimestep ?? 1 / 60,
- subStepCount: p?.subStepCount ?? 4,
- contactHertz: p?.contactHertz ?? 120,
- contactDampingRatio: p?.contactDampingRatio ?? 10,
- contactSpeed: p?.contactSpeed ?? 10,
- enableSleep: p?.enableSleep ?? true,
- enableContinuous: p?.enableContinuous ?? true,
+ enabled: rc.physicsEnabled,
+ gravity: c.gravity ?? { x: 0, y: -9.81 },
+ collisionLayers: normalizeCollisionLayers(this.state?.features?.physics?.collisionLayers),
+ collisionLayerMasks: normalizeCollisionLayerMasks(this.state?.features?.physics?.collisionLayerMasks),
+ fixedTimestep: c.fixedTimestep ?? 1 / 60,
+ subStepCount: c.subStepCount ?? 4,
+ contactHertz: c.contactHertz ?? 120,
+ contactDampingRatio: c.contactDampingRatio ?? 10,
+ contactSpeed: c.contactSpeed ?? 10,
+ enableSleep: c.enableSleep ?? true,
+ enableContinuous: c.enableContinuous ?? true,
};
}
@@ -1877,36 +1853,49 @@ class ProjectStoreImpl {
};
}
+ /**
+ * The project's effective runtime settings — the ONE derivation the play realm,
+ * every exported build and the edit viewport all read (see runtimeConfig.ts).
+ * Defined with no project open too, so a bare editor answers with the defaults.
+ */
+ runtimeConfig(): RuntimeProjectConfig {
+ const st = this.state;
+ return runtimeConfigOf({ features: st?.features, designResolution: st?.designResolution });
+ }
+
/** Bitmask over layers 0..31 that y-sort within the layer (0 = feature off). */
ySortMask(): number {
- let mask = 0;
- for (const i of this.renderingFeature().ySortLayers) mask |= 1 << i;
- return mask >>> 0;
+ return this.runtimeConfig().ySortLayers;
}
/** Bitmask over layers 0..31 that resolve by real depth (0 = feature off). */
depthMask(): number {
- let mask = 0;
- for (const i of this.renderingFeature().depthLayers) mask |= 1 << i;
- return mask >>> 0;
+ return this.runtimeConfig().depthLayers;
}
/**
- * Push how each sorting layer resolves — y-sort and depth — into the edit
- * viewport, so authoring shows what the game will show.
+ * Apply every project setting the EDIT session can show, so authoring shows
+ * what the game will show.
+ *
+ * One method, called wherever a setting can change, because a per-setting
+ * apply is how the list rots: depth layers used to reach only the play realm
+ * (author against paint order, ship 2.5D), and the mixer used to be applied by
+ * the Mixer PANEL — so a project whose buses were configured previewed audio
+ * at the wrong levels until someone happened to open it.
*
- * BOTH masks, in ONE place. Depth used to reach only the play realm: a project
- * could check "Depth-sorted layers", get 2.5D occlusion in the game, and author
- * against an edit viewport still painting in list order — the setting was real
- * everywhere except where it is set. And picking reads the same two masks (see
- * projectSeams), because a click that ranks overlapping entities differently
- * from the renderer selects what you cannot see.
+ * What is NOT here is here on purpose: the colour space is boot-fixed (shaders
+ * compile against it, so the settings page asks for a reload), and physics is
+ * not simulated in edit mode at all. Picking reads the same two sorting masks
+ * through projectSeams, since a click that ranks overlapping entities
+ * differently from the renderer selects what you cannot see.
*/
- private applySortingLayerModes(): void {
- const ySort = this.ySortMask();
- const depth = this.depthMask();
- Renderer.setYSortLayers(ySort);
- Renderer.setDepthLayers(depth);
+ private applyEditorRuntimeConfig(): void {
+ const rc = this.runtimeConfig();
+ Renderer.setYSortLayers(rc.ySortLayers);
+ Renderer.setDepthLayers(rc.depthLayers);
+ const audio = EngineHost.getResource(Audio);
+ if (audio) applyAudioProjectConfig(audio, rc.audioConfig);
+ applyWidgetTheme(rc.uiTheme, this.uiThemeOverrides());
}
/** Sorting-layer dropdown options for render `layer` fields — only the NAMED
@@ -1941,7 +1930,7 @@ class ProjectStoreImpl {
if (patch.cameraMatch !== undefined) rendering.cameraMatch = patch.cameraMatch;
const features: ProjectFeatures = { ...st.features, rendering };
this.store.setState({ project: { ...st, features } });
- this.applySortingLayerModes();
+ this.applyEditorRuntimeConfig();
await this.patchManifest((raw) => {
raw.features = { ...((raw.features as Record<string, unknown>) ?? {}), rendering };
}, t('proj.saveSortingLayersFailed'));
@@ -2488,7 +2477,7 @@ class ProjectStoreImpl {
installSkeletalSync(this.skeletalTransport());
Reconciler.adopt(raw, resolved);
EngineHost.syncEditorViewToScene();
- applyWidgetTheme(this.uiTheme(), this.uiThemeOverrides());
+ this.applyEditorRuntimeConfig();
}
/**
diff --git a/desktop/src/project/runtimeConfig.ts b/desktop/src/project/runtimeConfig.ts
new file mode 100644
index 000000000..118337065
--- /dev/null
+++ b/desktop/src/project/runtimeConfig.ts
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file runtimeConfig.ts — what a RUNTIME has to be told about the project, once.
+ *
+ * A project setting is never one fact in one file. "This layer resolves by depth"
+ * is a manifest field, a parse branch, something the edit viewport applies, a
+ * field in the play payload, and a field a shipped build is written with. Each of
+ * those used to be spelled out by hand at its own site, and a setting is only as
+ * real as its least-remembered site: the 2.5D depth mask reached the play realm
+ * and NEITHER the editor nor any exported build, because the export re-derives
+ * the settings from the manifest in the main process and simply never mentioned
+ * it. It looked right in Play and shipped wrong — the worst shape a bug can take.
+ *
+ * So the derivation happens once, as a pure function over a parsed manifest, and
+ * both processes call it: the renderer to build the play payload, the main
+ * process to build an export (it cannot import ProjectStore — that lives in the
+ * window — but it can import this).
+ *
+ * The values are EFFECTIVE ones, defaults folded in, because "what will the game
+ * run with" is the question every caller is asking. Each consumer still decides
+ * what to omit from its own wire format (absence = default is how the manifest,
+ * the play payload and game.config.json all express a default).
+ *
+ * Adding a setting means adding it here. `tools/check-project-settings.mjs`
+ * fails the build when a field in this shape is not carried by every consumer —
+ * or is not listed there as a declared, reasoned gap.
+ */
+import type { AudioProjectConfig, PackagedGameConfig, PhysicsPluginConfig } from 'esengine';
+import { resolveScreenFit, SORTING_LAYER_COUNT, type ProjectManifest } from './format';
+
+/** The project's camera fit as a runtime takes it (`scaleMode < 0` ⇒ off). */
+export interface RuntimeScreenFit {
+ designWidth: number;
+ designHeight: number;
+ scaleMode: number;
+ matchWidthOrHeight: number;
+}
+
+/**
+ * Every project setting a runtime is told about, with defaults applied.
+ *
+ * One shape for the play realm and for a shipped build, because the whole point
+ * is that Play is a rehearsal of shipping: a field only one of them carries is a
+ * field that makes the rehearsal lie.
+ */
+export interface RuntimeProjectConfig {
+ /** Install physics even when the static scene shows no bodies (runtime-spawned). */
+ physicsEnabled: boolean;
+ /** World solver + collision matrix (Project Settings → Physics). */
+ physicsConfig: PhysicsPluginConfig;
+ /** Mixer state: bus volumes, custom buses, effects, duck rules. */
+ audioConfig: AudioProjectConfig;
+ /** Built-in widget theme; 'dark' is the default. */
+ uiTheme: 'dark' | 'light';
+ /** Theme colour overrides (role → #rrggbbaa), possibly empty. */
+ uiThemeColors: Record<string, string>;
+ /** Bitmask of sorting layers (0..31) that y-sort within the layer. */
+ ySortLayers: number;
+ /** Bitmask of sorting layers (0..31) that resolve by depth — the 2.5D opt-in. */
+ depthLayers: number;
+ /** Render colour space; 'gamma' is the default. Boot-fixed (shaders compile against it). */
+ colorSpace: 'gamma' | 'linear';
+ /** Main-camera fit of the design resolution; `scaleMode < 0` = off. */
+ screenFit: RuntimeScreenFit;
+}
+
+/** Bit i set ⇒ sorting layer i is in `list`. Layers outside 0..31 have no bit. */
+function layerMask(list: readonly number[] | undefined): number {
+ let mask = 0;
+ for (const i of list ?? []) {
+ if (Number.isInteger(i) && i >= 0 && i < SORTING_LAYER_COUNT) mask |= 1 << i;
+ }
+ return mask >>> 0;
+}
+
+/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */
+export function normalizeCollisionLayers(layers?: string[]): string[] {
+ return Array.from({ length: 16 }, (_, i) => layers?.[i] ?? (i === 0 ? 'Default' : ''));
+}
+
+/** Pad/truncate the collision matrix to 16 rows; absent rows default to all-collide. */
+export function normalizeCollisionLayerMasks(masks?: number[]): number[] {
+ return Array.from({ length: 16 }, (_, i) => (typeof masks?.[i] === 'number' ? masks[i] & 0xffff : 0xffff));
+}
+
+/**
+ * The physics world config a runtime installs, defaults folded in. The solver
+ * defaults mirror the engine's own fallbacks, so Project Settings shows the
+ * effective values rather than blanks.
+ *
+ * The collision matrix rides along ONLY when it actually restricts a pair: an
+ * all-collide matrix would otherwise override each single-layer collider's own
+ * maskBits for nothing.
+ */
+function physicsConfigOf(features: ProjectManifest['features']): PhysicsPluginConfig {
+ const p = features?.physics;
+ const config: PhysicsPluginConfig = {
+ gravity: p?.gravity ?? { x: 0, y: -9.81 },
+ fixedTimestep: p?.fixedTimestep ?? 1 / 60,
+ subStepCount: p?.subStepCount ?? 4,
+ contactHertz: p?.contactHertz ?? 120,
+ contactDampingRatio: p?.contactDampingRatio ?? 10,
+ contactSpeed: p?.contactSpeed ?? 10,
+ enableSleep: p?.enableSleep ?? true,
+ enableContinuous: p?.enableContinuous ?? true,
+ };
+ const masks = normalizeCollisionLayerMasks(p?.collisionLayerMasks);
+ if (masks.some((m) => (m & 0xffff) !== 0xffff)) config.collisionLayerMasks = masks;
+ return config;
+}
+
+/**
+ * The project's effective runtime settings. Takes the parsed manifest shape both
+ * processes have — the editor's live project state satisfies it structurally.
+ */
+export function runtimeConfigOf(
+ manifest: Pick<ProjectManifest, 'designResolution' | 'features'>,
+): RuntimeProjectConfig {
+ const f = manifest.features;
+ return {
+ physicsEnabled: f?.physics?.enabled ?? false,
+ physicsConfig: physicsConfigOf(f),
+ audioConfig: f?.audio ?? {},
+ uiTheme: f?.ui?.theme === 'light' ? 'light' : 'dark',
+ uiThemeColors: f?.ui?.colors ?? {},
+ ySortLayers: layerMask(f?.rendering?.ySortLayers),
+ depthLayers: layerMask(f?.rendering?.depthLayers),
+ colorSpace: f?.rendering?.colorSpace === 'linear' ? 'linear' : 'gamma',
+ screenFit: resolveScreenFit(manifest),
+ };
+}
+
+/** The settings a shipped build carries, as `game.config.json` spells them. */
+export type PackagedRuntimeFields = Pick<
+ PackagedGameConfig,
+ 'ySortLayers' | 'depthLayers' | 'colorSpace' | 'screenFit' | 'uiTheme' | 'uiThemeColors'
+>;
+
+/**
+ * The shipped-build slice of the config, with defaults OMITTED — absence is how
+ * `game.config.json` and the generated mini-game / playable boots all express a
+ * default, so an untouched project ships the same bytes it always did.
+ *
+ * Every packaged target goes through this one function rather than restating the
+ * list, which is what makes "the export forgot a setting" impossible to write
+ * rather than merely unlikely.
+ */
+export function packagedRuntimeFields(rc: RuntimeProjectConfig): PackagedRuntimeFields {
+ return {
+ ...(rc.ySortLayers ? { ySortLayers: rc.ySortLayers } : {}),
+ ...(rc.depthLayers ? { depthLayers: rc.depthLayers } : {}),
+ ...(rc.colorSpace === 'linear' ? { colorSpace: rc.colorSpace } : {}),
+ ...(rc.screenFit.scaleMode >= 0 ? { screenFit: rc.screenFit } : {}),
+ ...(rc.uiTheme === 'light' ? { uiTheme: rc.uiTheme } : {}),
+ ...(Object.keys(rc.uiThemeColors).length > 0 ? { uiThemeColors: rc.uiThemeColors } : {}),
+ };
+}
+
+/** The effective settings of a project with nothing declared — every default. */
+export const DEFAULT_RUNTIME_CONFIG: RuntimeProjectConfig = runtimeConfigOf({});
diff --git a/desktop/tests/runtime-config.test.ts b/desktop/tests/runtime-config.test.ts
new file mode 100644
index 000000000..38ff8b414
--- /dev/null
+++ b/desktop/tests/runtime-config.test.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file runtimeConfig — the one derivation of "what the game will run with".
+ *
+ * The play realm and every exported build read this, so what it says a project
+ * runs with IS what both do. The cases here are the ones a second, hand-written
+ * copy of the list used to get wrong: a mask that never made it out of the
+ * editor, and a default that has to stay expressed by ABSENCE or an untouched
+ * project ships different bytes.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ DEFAULT_RUNTIME_CONFIG, packagedRuntimeFields, runtimeConfigOf,
+} from '@/project/runtimeConfig';
+
+describe('runtimeConfigOf', () => {
+ it('answers with the engine defaults for a project that declares nothing', () => {
+ const rc = runtimeConfigOf({});
+ expect(rc.ySortLayers).toBe(0);
+ expect(rc.depthLayers).toBe(0);
+ expect(rc.colorSpace).toBe('gamma');
+ expect(rc.uiTheme).toBe('dark');
+ expect(rc.uiThemeColors).toEqual({});
+ expect(rc.physicsEnabled).toBe(false);
+ expect(rc.audioConfig).toEqual({});
+ expect(rc.screenFit.scaleMode).toBe(-1); // fit off
+ expect(rc.physicsConfig.gravity).toEqual({ x: 0, y: -9.81 });
+ expect(rc).toEqual(DEFAULT_RUNTIME_CONFIG);
+ });
+
+ it('turns the sorting-layer lists into the masks the renderer takes', () => {
+ const rc = runtimeConfigOf({
+ features: { rendering: { ySortLayers: [0, 3], depthLayers: [1, 2] } },
+ });
+ expect(rc.ySortLayers).toBe(0b1001);
+ expect(rc.depthLayers).toBe(0b0110);
+ });
+
+ it('drops layer indices no 32-bit mask can carry, rather than wrapping them', () => {
+ const rc = runtimeConfigOf({
+ features: { rendering: { depthLayers: [-1, 0, 31, 32, 1.5] } },
+ });
+ // Bit 31 + bit 0, UNSIGNED: the mask crosses to C++ as a u32, so a signed
+ // `|` result here would be a different number than the renderer receives.
+ expect(rc.depthLayers).toBe(((1 << 31) >>> 0) + 1);
+ });
+
+ it('sends the collision matrix only when it actually restricts a pair', () => {
+ const open = runtimeConfigOf({ features: { physics: { collisionLayerMasks: [0xffff, 0xffff] } } });
+ expect(open.physicsConfig.collisionLayerMasks).toBeUndefined();
+
+ const restricted = runtimeConfigOf({ features: { physics: { collisionLayerMasks: [0xfffe] } } });
+ expect(restricted.physicsConfig.collisionLayerMasks?.[0]).toBe(0xfffe);
+ expect(restricted.physicsConfig.collisionLayerMasks).toHaveLength(16); // padded to the filter bits
+ });
+
+ it('folds the solver defaults in, so the settings page and the game agree', () => {
+ const rc = runtimeConfigOf({ features: { physics: { enabled: true, subStepCount: 8 } } });
+ expect(rc.physicsEnabled).toBe(true);
+ expect(rc.physicsConfig.subStepCount).toBe(8);
+ expect(rc.physicsConfig.fixedTimestep).toBeCloseTo(1 / 60, 9);
+ expect(rc.physicsConfig.enableSleep).toBe(true);
+ });
+});
+
+describe('packagedRuntimeFields', () => {
+ // Absence IS the default in game.config.json, so an untouched project has to
+ // produce an empty object — otherwise every existing build's config changes.
+ it('is empty for a project that declared nothing', () => {
+ expect(packagedRuntimeFields(runtimeConfigOf({}))).toEqual({});
+ });
+
+ it('carries the 2.5D depth mask — the field that used to reach Play and no build', () => {
+ const fields = packagedRuntimeFields(runtimeConfigOf({
+ features: { rendering: { depthLayers: [1, 2] } },
+ }));
+ expect(fields.depthLayers).toBe(0b110);
+ });
+
+ it('carries every non-default and nothing else', () => {
+ const fields = packagedRuntimeFields(runtimeConfigOf({
+ designResolution: { width: 800, height: 600 },
+ features: {
+ rendering: { ySortLayers: [1], depthLayers: [2], colorSpace: 'linear', cameraScaleMode: 'expand' },
+ ui: { theme: 'light', colors: { accent: '#ff0000ff' } },
+ },
+ }));
+ expect(Object.keys(fields).sort()).toEqual(
+ ['colorSpace', 'depthLayers', 'screenFit', 'uiTheme', 'uiThemeColors', 'ySortLayers'],
+ );
+ expect(fields.screenFit).toEqual({
+ designWidth: 800, designHeight: 600, scaleMode: 2, matchWidthOrHeight: 0.5,
+ });
+ });
+
+ // The editor's live project state is not a manifest object, but it has the two
+ // fields this reads — that structural match is what lets one derivation serve
+ // the renderer and the main process.
+ it('reads a project state as readily as a parsed manifest', () => {
+ const state = { name: 'X', root: '/p', designResolution: { width: 640, height: 480 }, features: {} };
+ expect(runtimeConfigOf(state).screenFit.designWidth).toBe(640);
+ });
+});