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(editor): wire the opt-in project camera fit through hosts + settings

yhh1443d1f1ed67
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index 26e2710eb..27dea09a1 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -299,6 +299,9 @@ export async function exportGame(opts: {
ySortLayers?: number;
/** Project color space — 'linear' boots the shipped game on the linear-light pipeline. */
colorSpace?: 'gamma' | 'linear';
+ /** Project camera fit (Project Settings → Display) — the main camera letterboxes this
+ * design resolution regardless of any UI Canvas. Absent ⇒ no fit (raw orthoSize). */
+ screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
}): Promise<ExportGameResult> {
const platform = opts.platform ?? 'web';
const title = opts.title ?? 'Game';
@@ -349,6 +352,7 @@ export async function exportGame(opts: {
minify: opts.minify,
ySortLayers: opts.ySortLayers,
colorSpace: opts.colorSpace,
+ screenFit: opts.screenFit,
onProgress: opts.onProgress,
});
}
@@ -419,6 +423,7 @@ export async function exportGame(opts: {
entryScene: opts.entryScene, scenes,
...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}),
...(opts.colorSpace === 'linear' ? { colorSpace: opts.colorSpace } : {}),
+ ...(opts.screenFit && opts.screenFit.scaleMode >= 0 ? { screenFit: opts.screenFit } : {}),
},
null, 2,
) + '\n',
diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.ts
index fc112708a..6518b20d6 100644
--- a/desktop/electron/exportPlayable.ts
+++ b/desktop/electron/exportPlayable.ts
@@ -155,6 +155,9 @@ export async function exportPlayable(opts: {
ySortLayers?: number;
/** Project color space — 'linear' boots the playable on the linear-light pipeline. */
colorSpace?: 'gamma' | 'linear';
+ /** Project camera fit (design resolution + scale mode) — letterboxes the main camera
+ * without a UI Canvas; absent = no fit. */
+ screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
onProgress?: OnExportProgress;
}): Promise<ExportPlayableResult> {
const title = opts.title ?? 'Game';
@@ -271,7 +274,8 @@ export async function exportPlayable(opts: {
`window.__GAME_SCENES__=${JSON.stringify(scenes)};` +
`window.__GAME_FIRST__=${JSON.stringify(sceneName)};` +
`window.__GAME_YSORT__=${(opts.ySortLayers ?? 0) >>> 0};` +
- `window.__GAME_COLORSPACE__=${JSON.stringify(opts.colorSpace === 'linear' ? 'linear' : 'gamma')};`;
+ `window.__GAME_COLORSPACE__=${JSON.stringify(opts.colorSpace === 'linear' ? 'linear' : 'gamma')};` +
+ (opts.screenFit && opts.screenFit.scaleMode >= 0 ? `window.__GAME_SCREENFIT__=${JSON.stringify(opts.screenFit)};` : '');
const outFile = path.join(absOut, 'index.html');
await writeFile(outFile, indexHtml(title, globals, bundle, orientation));
await rm(cookDir, { recursive: true, force: true });
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 04acea9d8..cfa423d41 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -35,7 +35,7 @@ import { ensureSdkTypes } from './syncSdkTypes';
import { installCrashCapture, logsDir } from './resilience';
import { mcpMode, startMcpEndpoint } from './mcpEndpoint';
import { checkForUpdate } from './updateCheck';
-import { resolveLayout, resolveScripts, resolveOrientation } from '../src/project/format';
+import { resolveLayout, resolveScripts, resolveOrientation, resolveScreenFit } from '../src/project/format';
import type { WorkspaceState } from '../src/project/format';
// Enable WebGPU in the renderer so the viewport's WebGPU backend (Settings →
@@ -623,6 +623,9 @@ ipcMain.handle(
const ySortLayers =
(manifest.features?.rendering?.ySortLayers ?? []).reduce((m, i) => m | (1 << i), 0) >>> 0;
const colorSpace = manifest.features?.rendering?.colorSpace === 'linear' ? 'linear' as const : undefined;
+ // Project camera fit → runtime screenFit (only when the project opts in; scaleMode < 0 = off).
+ const fit = resolveScreenFit(manifest);
+ const screenFit = fit.scaleMode >= 0 ? fit : undefined;
return exportGame({
root,
entryScene,
@@ -630,6 +633,7 @@ ipcMain.handle(
excludeScenes: manifest.packaging?.excludeScenes,
ySortLayers,
colorSpace,
+ screenFit,
gameHostEntry: path.join(HOSTS_DIR, 'gameHost.js'),
playableHostEntry: path.join(HOSTS_DIR, 'playableHost.js'),
scriptsEntry: resolveScripts(manifest).main,
diff --git a/desktop/src/engine/ViewportController.ts b/desktop/src/engine/ViewportController.ts
index a77a92cc0..ccbfcbe2f 100644
--- a/desktop/src/engine/ViewportController.ts
+++ b/desktop/src/engine/ViewportController.ts
@@ -8,7 +8,7 @@ import {
} from 'esengine';
import type { EntityId } from '@/types';
import { EngineHost } from './EngineHost';
-import { projectDesignSeed } from './entitySources';
+import { projectDesignSeed, projectCameraFit } from './entitySources';
import { SceneModel } from './SceneModel';
import {
type OBB,
@@ -579,13 +579,31 @@ export const ViewportController = {
*/
screenInfo(): EditorScreenInfo {
const canvas = this.canvasInfo();
+ const fit = projectCameraFit(); // { scaleMode, matchWidthOrHeight }; scaleMode -1 ⇒ off
+ // Project camera fit is on ⇒ it is authoritative for the camera (overrides the Canvas),
+ // so the device frame must preview THAT: the project design resolution + fit mode.
+ if (fit.scaleMode >= 0) {
+ const d = projectDesignSeed();
+ return {
+ cx: canvas?.cx ?? 0,
+ cy: canvas?.cy ?? 0,
+ designResolution: { x: d.width, y: d.height },
+ pixelsPerUnit: canvas?.pixelsPerUnit ?? 100,
+ scaleMode: fit.scaleMode,
+ matchWidthOrHeight: fit.matchWidthOrHeight,
+ backgroundColor: canvas?.backgroundColor ?? { r: 0, g: 0, b: 0, a: 0 },
+ };
+ }
+ // No project fit: the Canvas (its own scaleMode) when present, else the project
+ // design resolution with FixedHeight (the engine's Canvas default) so the frame
+ // has a defined shape.
if (canvas) return canvas;
const d = projectDesignSeed();
return {
cx: 0, cy: 0,
designResolution: { x: d.width, y: d.height },
pixelsPerUnit: 100,
- scaleMode: 1, // CanvasScaleMode.FixedHeight — the engine's Canvas default
+ scaleMode: 1, // CanvasScaleMode.FixedHeight
matchWidthOrHeight: 0.5,
// No Canvas ⇒ no authored letterbox tint; the overlay falls back to a neutral scrim.
backgroundColor: { r: 0, g: 0, b: 0, a: 0 },
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index e61d84a58..cd217bb5f 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -145,6 +145,18 @@ export function projectDesignSeed(): { width: number; height: number } {
return canvasDesignSeed?.() ?? { width: 1920, height: 1080 };
}
+// Project camera fit provider (ProjectStore wires this). `scaleMode` is a CanvasScaleMode
+// (0..4) or -1 (off). Same injection pattern as canvasDesignSeed — the device preview
+// reads it so its letterbox matches the runtime fit (WYSIWYG), without importing ProjectStore.
+let projectCameraFitSeed: (() => { scaleMode: number; matchWidthOrHeight: number }) | null = null;
+export function setProjectCameraFit(fn: () => { scaleMode: number; matchWidthOrHeight: number }): void {
+ projectCameraFitSeed = fn;
+}
+/** The project's camera fit (scaleMode -1 ⇒ off). Read by ViewportController.screenInfo. */
+export function projectCameraFit(): { scaleMode: number; matchWidthOrHeight: number } {
+ return projectCameraFitSeed?.() ?? { scaleMode: -1, matchWidthOrHeight: 0.5 };
+}
+
const UI_WIDGET_ICON: Record<string, LucideIcon> = {
Button: SquareMousePointer,
Toggle: ToggleLeft,
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index ba45a1844..2bf72672d 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -63,6 +63,9 @@ export interface PlayPayload {
ySortLayers?: number;
/** Project color space — 'linear' boots the realm on the linear-light pipeline. */
colorSpace?: 'gamma' | 'linear';
+ /** Project camera fit (design resolution + scale mode) — letterboxes the realm's
+ * main camera without a UI Canvas; absent = no fit (raw orthoSize). */
+ screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
/** Multiplayer preview role; absent = a plain single-player session. */
net?: PlayNetConfig;
}
diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.ts
index a83a9f69f..9e1206f81 100644
--- a/desktop/src/gameHost.ts
+++ b/desktop/src/gameHost.ts
@@ -22,6 +22,9 @@ interface GameConfig {
ySortLayers?: number;
/** Project color space — 'linear' boots the linear-light pipeline. */
colorSpace?: 'gamma' | 'linear';
+ /** Project camera fit (design resolution + scale mode) — letterboxes the main camera
+ * without a UI Canvas; absent = no fit. */
+ screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
}
interface CookedManifest {
entries: { uuid: string; path: string; sourcePath?: string; type: string; atlas?: CookedAtlasInfo }[];
@@ -106,6 +109,7 @@ async function boot(): Promise<void> {
glContextHandle: glHandle,
ySortLayers: cfg.ySortLayers,
colorSpace: cfg.colorSpace,
+ screenFit: cfg.screenFit,
getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
wasmBaseUrl: wasmBase.replace(/\/$/, ''), // SDK appends "/<file>" — no trailing slash
});
diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.ts
index eba919e96..9c38ded9c 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -108,6 +108,22 @@ export const settingsMessages = defineMessages({
en: 'Screen orientation for every export target (WeChat, playable, web, desktop). Defaults to the design resolution’s aspect — override to lock a specific orientation.',
zh: '所有导出目标(微信、Playable、Web、桌面)的屏幕方向。默认取设计分辨率的宽高比 — 可覆盖以锁定特定方向。',
},
+ 'set.project.display.cameraFit': { en: 'Camera Fit', zh: '相机适配' },
+ 'set.project.display.cameraFit.desc': {
+ en: 'How the main camera scales the design resolution — independent of any UI Canvas, so it works in a gameplay-only scene. “None” keeps the camera’s own orthoSize (default); any other mode letterboxes every target and the editor device preview.',
+ zh: '主相机如何按设计分辨率缩放——独立于任何 UI Canvas,纯玩法场景也生效。“无”保持相机自身的 orthoSize(默认);其他模式会让所有导出目标与编辑器设备预览都做 letterbox。',
+ },
+ 'set.project.display.cameraMatch': { en: 'Match (width ↔ height)', zh: '匹配(宽 ↔ 高)' },
+ 'set.project.display.cameraMatch.desc': {
+ en: 'Blend between fitting width (0) and height (1), for the “Match” camera fit only.',
+ zh: '在适配宽度(0)与高度(1)之间插值,仅“匹配”相机适配模式生效。',
+ },
+ 'set.cameraFit.none': { en: 'None', zh: '无' },
+ 'set.cameraFit.fixedHeight': { en: 'Fit Height', zh: '适配高度' },
+ 'set.cameraFit.fixedWidth': { en: 'Fit Width', zh: '适配宽度' },
+ 'set.cameraFit.expand': { en: 'Expand', zh: '扩展' },
+ 'set.cameraFit.shrink': { en: 'Shrink', zh: '收缩' },
+ 'set.cameraFit.match': { en: 'Match', zh: '匹配' },
'set.project.rendering.sortingLayers': { en: 'Layer names', zh: '层名称' },
'set.project.rendering.sortingLayers.desc': {
en: 'Name render sorting layers (lowest first); a render `layer` field then picks from them instead of a raw number.',
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 69ad10038..cda1e8498 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -187,6 +187,7 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
glContextHandle: glHandle,
ySortLayers: msg.ySortLayers,
colorSpace: msg.colorSpace,
+ screenFit: msg.screenFit,
getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
wasmBaseUrl: wasmBase.replace(/\/$/, ''), // SDK appends "/<file>" — no trailing slash
});
diff --git a/desktop/src/playableHost.ts b/desktop/src/playableHost.ts
index 1ca92daaa..8e6a9c65a 100644
--- a/desktop/src/playableHost.ts
+++ b/desktop/src/playableHost.ts
@@ -27,6 +27,7 @@ declare const __GAME_SCENES__: Array<{ name: string; data: SceneData }>;
declare const __GAME_FIRST__: string;
declare const __GAME_YSORT__: number;
declare const __GAME_COLORSPACE__: 'gamma' | 'linear';
+declare const __GAME_SCREENFIT__: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
function decodeBase64(b64: string): Uint8Array {
const raw = atob(b64);
@@ -76,6 +77,8 @@ async function boot(): Promise<void> {
glContextHandle: glHandle,
// Older exports predate the color-space global; treat it as optional.
colorSpace: typeof __GAME_COLORSPACE__ !== 'undefined' ? __GAME_COLORSPACE__ : undefined,
+ // Present only when the project opts into a camera fit; optional otherwise.
+ screenFit: typeof __GAME_SCREENFIT__ !== 'undefined' ? __GAME_SCREENFIT__ : undefined,
getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
// Physics + spine resolve from the inlined base64 registry (no fetch).
sideModules: createEmbeddedSideModuleHost(typeof __SIDE_MODULES__ !== 'undefined' ? __SIDE_MODULES__ : {}),
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index b57459ab8..773c7b9f9 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -13,7 +13,7 @@ import { EditorHistory } from '@/engine/EditorHistory';
import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';
import { SceneCommands } from '@/engine/SceneCommands';
import { Boxes } from 'lucide-react';
-import { spritePrefab, setCanvasDesignSeed, type EntitySource } from '@/engine/entitySources';
+import { spritePrefab, setCanvasDesignSeed, setProjectCameraFit, type EntitySource } from '@/engine/entitySources';
import { setPrefabBaseResolver } from '@/engine/SceneQuery';
import { setUserSchemas, userSchema, setBitmaskSource, setEnumSource, type UserComponentSchema } from '@/engine/schema';
import { setAssetRefProblemResolver } from '@/engine/EditorControlSurface';
@@ -25,7 +25,7 @@ import { confirmDiscard } from './discardGuard';
import { t } from '@/i18n';
import { assetTypeOf } from '@/project/assetMeta';
import type { AssetType } from '@/types';
-import { resolveLayout, orientationFromDesignResolution, resolveOrientation, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution, type ScreenOrientation } from './format';
+import { resolveLayout, orientationFromDesignResolution, resolveOrientation, cameraScaleModeValue, WORKSPACE_DIR, PROJECT_MANIFEST_FILE, type OpenedProject, type ProjectFeatures, type ProjectLayout, type ProjectPackaging, type WorkspaceState, type DesignResolution, type ScreenOrientation, type CameraScaleMode } from './format';
import { useEditorMode } from '@/store/editorModeStore';
/** Pad/truncate collision-layer names to the 16 Box2D filter bits (layer 0 = Default). */
@@ -202,6 +202,12 @@ class ProjectStoreImpl {
setEnumSource('sortingLayers', () => this.sortingLayerOptions());
// New Canvas entities seed their design resolution from the project setting.
setCanvasDesignSeed(() => this.designResolution());
+ // The device preview reads the project camera fit so its letterbox matches the
+ // runtime (WYSIWYG when the fit is on).
+ setProjectCameraFit(() => {
+ const f = this.screenFit();
+ return { scaleMode: f.scaleMode, matchWidthOrHeight: f.matchWidthOrHeight };
+ });
// Diagnostics ask the registry whether a model-healthy asset ref actually
// names a real, loadable asset (dead refs draw white boxes in silence).
setAssetRefProblemResolver((ref) => this.assetRefProblem(ref));
@@ -1032,6 +1038,7 @@ class ProjectStoreImpl {
audioConfig?: AudioProjectConfig;
ySortLayers?: number;
colorSpace?: 'gamma' | 'linear';
+ screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
} | null {
const sceneData = SceneModel.serialize();
if (!sceneData) return null;
@@ -1062,11 +1069,15 @@ class ProjectStoreImpl {
const ySortLayers = this.ySortMask();
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();
return {
sceneData, assetManifest, physicsEnabled: f.enabled, physicsConfig,
...(audioConfig.buses ? { audioConfig } : {}),
...(ySortLayers !== 0 ? { ySortLayers } : {}),
...(colorSpace === 'linear' ? { colorSpace } : {}),
+ ...(screenFit.scaleMode >= 0 ? { screenFit } : {}),
};
}
@@ -1127,12 +1138,27 @@ class ProjectStoreImpl {
}
/** Named render sorting layers (z-order = slot index). Default empty list. */
- renderingFeature(): { sortingLayers: string[]; ySortLayers: number[]; colorSpace: 'gamma' | 'linear' } {
+ renderingFeature(): { sortingLayers: string[]; ySortLayers: number[]; colorSpace: 'gamma' | 'linear'; cameraScaleMode: CameraScaleMode; cameraMatch: number } {
const r = this.state?.features?.rendering;
return {
sortingLayers: Array.from({ length: 8 }, (_, i) => r?.sortingLayers?.[i] ?? ''),
ySortLayers: r?.ySortLayers ?? [],
colorSpace: r?.colorSpace === 'linear' ? 'linear' : 'gamma',
+ cameraScaleMode: r?.cameraScaleMode ?? 'none',
+ cameraMatch: r?.cameraMatch ?? 0.5,
+ };
+ }
+
+ /** The runtime screen-fit (createWebApp `screenFit` / ScreenScaling): the project
+ * design resolution + the mapped camera fit. `scaleMode` -1 ⇒ off (raw orthoSize). */
+ screenFit(): { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number } {
+ const d = this.designResolution();
+ const r = this.renderingFeature();
+ return {
+ designWidth: d.width,
+ designHeight: d.height,
+ scaleMode: cameraScaleModeValue(r.cameraScaleMode),
+ matchWidthOrHeight: r.cameraMatch,
};
}
@@ -1154,7 +1180,7 @@ class ProjectStoreImpl {
/** Set rendering-feature config (sorting layers, y-sort, color space) and persist
* to the manifest. Sorting/y-sort live-apply; colorSpace is boot-fixed (shaders
* compile against it) — the settings page prompts for a reload, like the backend. */
- async setRendering(patch: { sortingLayers?: string[]; ySortLayers?: number[]; colorSpace?: 'gamma' | 'linear' }): Promise<void> {
+ async setRendering(patch: { sortingLayers?: string[]; ySortLayers?: number[]; colorSpace?: 'gamma' | 'linear'; cameraScaleMode?: CameraScaleMode; cameraMatch?: number }): Promise<void> {
const st = this.state;
if (!st) return;
const rendering: NonNullable<ProjectFeatures['rendering']> = { ...st.features?.rendering };
@@ -1163,6 +1189,10 @@ class ProjectStoreImpl {
// 'gamma' is the default — expressed by ABSENCE so untouched manifests stay untouched.
if (patch.colorSpace === 'linear') rendering.colorSpace = 'linear';
else if (patch.colorSpace === 'gamma') delete rendering.colorSpace;
+ // 'none' (off) is the default — expressed by ABSENCE, like colorSpace 'gamma'.
+ if (patch.cameraScaleMode === 'none') delete rendering.cameraScaleMode;
+ else if (patch.cameraScaleMode !== undefined) rendering.cameraScaleMode = patch.cameraScaleMode;
+ if (patch.cameraMatch !== undefined) rendering.cameraMatch = patch.cameraMatch;
const features: ProjectFeatures = { ...st.features, rendering };
this.store.setState({ project: { ...st, features } });
Renderer.setYSortLayers(this.ySortMask());
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index 49c9d4ec0..c28ed3fe8 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -92,12 +92,23 @@ export interface ProjectFeatures {
* sample, linear blending, OETF at the final blit). Fixed at engine boot —
* shaders compile against it. Absent ⇒ 'gamma'. */
colorSpace?: 'linear';
+ /** How the MAIN camera fits the design resolution, INDEPENDENT of any UI Canvas
+ * (the runtime's ScreenScaling). Absent/'none' ⇒ the camera keeps its raw
+ * orthoSize (Canvas fit when present) — the zero-regression default. */
+ cameraScaleMode?: CameraScaleMode;
+ /** Match-mode blend 0..1 (0 = fit width, 1 = fit height); cameraScaleMode='match' only. */
+ cameraMatch?: number;
};
/** Project mixer state (bus volumes / custom buses / effects / duck rules). */
audio?: AudioProjectConfig;
}
export type ScreenOrientation = 'portrait' | 'landscape';
+
+/** Project camera fit — how the main camera scales the design resolution (a superset of
+ * the engine's CanvasScaleMode names, plus 'none' = off). See {@link cameraScaleModeValue}. */
+export type CameraScaleMode = 'none' | 'fixed-width' | 'fixed-height' | 'expand' | 'shrink' | 'match';
+
/** Per-platform packaging config (the platform-specific Project Settings pages).
* Orientation is NOT here — it is one project-wide {@link ProjectPackaging.orientation}
* consumed by every target (a landscape build is landscape everywhere). */
@@ -297,6 +308,14 @@ export function parseManifest(raw: unknown): ProjectManifest {
}
// Only 'linear' persists; 'gamma' (the default) is expressed by absence.
if (r.colorSpace === 'linear') rendering.colorSpace = 'linear';
+ // Camera fit — 'none' (off) is the default, expressed by absence.
+ if (r.cameraScaleMode === 'fixed-width' || r.cameraScaleMode === 'fixed-height' ||
+ r.cameraScaleMode === 'expand' || r.cameraScaleMode === 'shrink' || r.cameraScaleMode === 'match') {
+ rendering.cameraScaleMode = r.cameraScaleMode;
+ }
+ if (typeof r.cameraMatch === 'number' && Number.isFinite(r.cameraMatch)) {
+ rendering.cameraMatch = Math.min(1, Math.max(0, r.cameraMatch));
+ }
if (Object.keys(rendering).length > 0) features.rendering = rendering;
}
if (f.audio && typeof f.audio === 'object') {
@@ -382,6 +401,35 @@ export function resolveOrientation(manifest: Pick<ProjectManifest, 'packaging' |
return manifest.packaging?.orientation ?? orientationFromDesignResolution(manifest.designResolution);
}
+/** cameraScaleMode → the engine's CanvasScaleMode value the runtime consumes
+ * (FixedWidth=0, FixedHeight=1, Expand=2, Shrink=3, Match=4), or -1 (SCREEN_FIT_OFF)
+ * for 'none'/absent — the camera keeps its raw orthoSize. Single-sourced here so the
+ * editor, the export config writers, and the play realm all map identically. */
+export function cameraScaleModeValue(m: CameraScaleMode | undefined): number {
+ switch (m) {
+ case 'fixed-width': return 0;
+ case 'fixed-height': return 1;
+ case 'expand': return 2;
+ case 'shrink': return 3;
+ case 'match': return 4;
+ default: return -1;
+ }
+}
+
+/** The runtime screen-fit config (createWebApp `screenFit` / ScreenScaling) for a
+ * project: its design resolution + the mapped camera fit. `scaleMode` -1 ⇒ off. */
+export function resolveScreenFit(manifest: Pick<ProjectManifest, 'designResolution' | 'features'>): {
+ designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number;
+} {
+ const dr = manifest.designResolution;
+ return {
+ designWidth: dr?.width ?? 1920,
+ designHeight: dr?.height ?? 1080,
+ scaleMode: cameraScaleModeValue(manifest.features?.rendering?.cameraScaleMode),
+ matchWidthOrHeight: manifest.features?.rendering?.cameraMatch ?? 0.5,
+ };
+}
+
/** Default script entries — the convention most projects follow without config. */
export const DEFAULT_SCRIPTS: Required<ProjectScripts> = {
register: 'src/components.ts',
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index 2e5382808..088b4ac31 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -12,7 +12,7 @@ import { ProjectStore } from '@/project/ProjectStore';
import { EngineHost } from '@/engine/EngineHost';
import { Toasts } from '@/store/Toasts';
import { useEditorMode } from '@/store/editorModeStore';
-import type { ScreenOrientation } from '@/project/format';
+import type { ScreenOrientation, CameraScaleMode } from '@/project/format';
import { t } from '@/i18n';
const ORIENTATION = [
@@ -20,6 +20,15 @@ const ORIENTATION = [
{ value: 'landscape', label: t('set.orientation.landscape') },
];
+const CAMERA_FIT = [
+ { value: 'none', label: t('set.cameraFit.none') },
+ { value: 'fixed-height', label: t('set.cameraFit.fixedHeight') },
+ { value: 'fixed-width', label: t('set.cameraFit.fixedWidth') },
+ { value: 'expand', label: t('set.cameraFit.expand') },
+ { value: 'shrink', label: t('set.cameraFit.shrink') },
+ { value: 'match', label: t('set.cameraFit.match') },
+];
+
// ── Display (design/reference resolution + orientation; screen shape) ──
settingsRegistry.registerSection({ id: 'display', label: t('set.section.display'), category: 'project', order: 0 });
@@ -66,6 +75,33 @@ settingsRegistry.register({
},
});
+// Camera fit — how the MAIN camera scales the design resolution, independent of any UI
+// Canvas. 'None' (default) keeps the raw orthoSize (zero regression); any other mode
+// letterboxes every target + the editor device preview. The sibling of a UI CanvasScaler.
+settingsRegistry.register({
+ id: 'project.display.cameraFit',
+ type: 'enum', scope: 'project', section: 'display', group: t('set.group.designResolution'),
+ label: t('set.project.display.cameraFit'),
+ description: t('set.project.display.cameraFit.desc'),
+ options: CAMERA_FIT, default: 'none',
+ bind: {
+ get: () => ProjectStore.renderingFeature().cameraScaleMode,
+ set: (v) => void ProjectStore.setRendering({ cameraScaleMode: v as CameraScaleMode }),
+ },
+});
+
+settingsRegistry.register({
+ id: 'project.display.cameraMatch',
+ type: 'number', scope: 'project', section: 'display', group: t('set.group.designResolution'),
+ label: t('set.project.display.cameraMatch'),
+ description: t('set.project.display.cameraMatch.desc'),
+ default: 0.5, min: 0, max: 1, step: 0.05,
+ bind: {
+ get: () => ProjectStore.renderingFeature().cameraMatch,
+ set: (v) => void ProjectStore.setRendering({ cameraMatch: v }),
+ },
+});
+
// ── Physics (the enable flag = UE Plugins-Browser analog; gravity = Project Settings) ──
settingsRegistry.registerSection({ id: 'physics', label: t('set.section.physics'), category: 'project', order: 1 });