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): colorSpace is a project setting - editor, Play, and every export boot it

yhh527cfe03150c
diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.ts
index 54ddf2b4a..e68c28cf9 100644
--- a/desktop/electron/exportGame.ts
+++ b/desktop/electron/exportGame.ts
@@ -286,6 +286,8 @@ export async function exportGame(opts: {
sourcemap?: boolean;
/** Bitmask of render layers (0..31) that y-sort (Project Settings → Rendering). */
ySortLayers?: number;
+ /** Project color space — 'linear' boots the shipped game on the linear-light pipeline. */
+ colorSpace?: 'gamma' | 'linear';
}): Promise<ExportGameResult> {
const platform = opts.platform ?? 'web';
const title = opts.title ?? 'Game';
@@ -306,6 +308,7 @@ export async function exportGame(opts: {
appid: opts.wechatAppid,
orientation: opts.wechatOrientation,
ySortLayers: opts.ySortLayers,
+ colorSpace: opts.colorSpace,
minify: opts.minify,
contentAddressed: opts.contentAddressed,
compressTextures: opts.compressTextures,
@@ -329,6 +332,7 @@ export async function exportGame(opts: {
title,
minify: opts.minify,
ySortLayers: opts.ySortLayers,
+ colorSpace: opts.colorSpace,
onProgress: opts.onProgress,
});
}
@@ -394,7 +398,11 @@ export async function exportGame(opts: {
await writeFile(
path.join(payloadDir, 'game.config.json'),
JSON.stringify(
- { entryScene: opts.entryScene, scenes, ...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}) },
+ {
+ entryScene: opts.entryScene, scenes,
+ ...(opts.ySortLayers ? { ySortLayers: opts.ySortLayers } : {}),
+ ...(opts.colorSpace === 'linear' ? { colorSpace: opts.colorSpace } : {}),
+ },
null, 2,
) + '\n',
);
diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.ts
index d616a4a0d..2eec474ea 100644
--- a/desktop/electron/exportPlayable.ts
+++ b/desktop/electron/exportPlayable.ts
@@ -145,6 +145,8 @@ export async function exportPlayable(opts: {
minify?: boolean;
/** Bitmask of render layers (0..31) that y-sort (Project Settings → Rendering). */
ySortLayers?: number;
+ /** Project color space — 'linear' boots the playable on the linear-light pipeline. */
+ colorSpace?: 'gamma' | 'linear';
onProgress?: OnExportProgress;
}): Promise<ExportPlayableResult> {
const title = opts.title ?? 'Game';
@@ -259,7 +261,8 @@ export async function exportPlayable(opts: {
`window.__GAME_PATHMAP__=${JSON.stringify(pathMap)};` +
`window.__GAME_SCENES__=${JSON.stringify(scenes)};` +
`window.__GAME_FIRST__=${JSON.stringify(sceneName)};` +
- `window.__GAME_YSORT__=${(opts.ySortLayers ?? 0) >>> 0};`;
+ `window.__GAME_YSORT__=${(opts.ySortLayers ?? 0) >>> 0};` +
+ `window.__GAME_COLORSPACE__=${JSON.stringify(opts.colorSpace === 'linear' ? 'linear' : 'gamma')};`;
const outFile = path.join(absOut, 'index.html');
await writeFile(outFile, indexHtml(title, globals, bundle));
await rm(cookDir, { recursive: true, force: true });
diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.ts
index 396491d9b..9d69dce2a 100644
--- a/desktop/electron/exportWeChat.ts
+++ b/desktop/electron/exportWeChat.ts
@@ -256,6 +256,8 @@ export async function exportWeChat(opts: {
orientation?: 'portrait' | 'landscape';
/** Bitmask of render layers (0..31) that y-sort (Project Settings → Rendering). */
ySortLayers?: number;
+ /** Project color space — 'linear' boots the mini-game on the linear-light pipeline. */
+ colorSpace?: 'gamma' | 'linear';
minify?: boolean;
/** Emit content-addressed asset filenames (<hash><ext>) for dedup + immutable caching. */
contentAddressed?: boolean;
@@ -369,7 +371,7 @@ export async function exportWeChat(opts: {
`import { initWeChatRuntime } from 'esengine';\n` +
(scriptsAbs && existsSync(scriptsAbs) ? `import ${JSON.stringify(scriptsAbs)};\n` : '') +
`export function boot(engineFactory, sideModuleFactories) {\n` +
- ` return initWeChatRuntime({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''} });\n` +
+ ` return initWeChatRuntime({ engineFactory, engineWasmPath: ${JSON.stringify(engineWasmPath)}, sideModuleFactories, sceneNames: ${JSON.stringify(scenes.map((s) => s.name))}, firstScene: ${JSON.stringify(sceneName)}${opts.ySortLayers ? `, ySortLayers: ${opts.ySortLayers >>> 0}` : ''}${opts.colorSpace === 'linear' ? `, colorSpace: 'linear'` : ''} });\n` +
`}\n`;
progress({ phase: 'Bundling game' });
try {
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 97fb2db93..f19e75997 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -579,12 +579,14 @@ ipcMain.handle(
const plat = manifest.packaging?.platforms;
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;
return exportGame({
root,
entryScene,
scenesDir: resolveLayout(manifest).scenes,
excludeScenes: manifest.packaging?.excludeScenes,
ySortLayers,
+ colorSpace,
gameHostEntry: path.join(HOSTS_DIR, 'gameHost.js'),
playableHostEntry: path.join(HOSTS_DIR, 'playableHost.js'),
scriptsEntry: resolveScripts(manifest).main,
diff --git a/desktop/src/engine/EngineHost.ts b/desktop/src/engine/EngineHost.ts
index 1bfc6ceef..479b05958 100644
--- a/desktop/src/engine/EngineHost.ts
+++ b/desktop/src/engine/EngineHost.ts
@@ -22,6 +22,7 @@ import { SceneLoader } from './SceneLoader';
import { useSettings } from '@/store/settingsStore';
import { loadEditorSpine } from './spineLoad';
import { checkEngineBuild } from './EngineGuard';
+import { PROJECT_MANIFEST_FILE } from '@/project/format';
import type { ReadonlyWorldT, WorldT } from './schema';
// Scene the editor opens on boot (placeholder until a project/open-scene flow exists).
@@ -53,6 +54,8 @@ class EngineHostImpl {
private booted = false;
/** The GPU backend the viewport actually booted with (after availability fallback). */
activeBackend: 'webgl2' | 'webgpu' = 'webgl2';
+ /** The color space the engine booted with (Project Settings → Rendering; boot-fixed). */
+ activeColorSpace: 'gamma' | 'linear' = 'gamma';
private resizeObserver: ResizeObserver | null = null;
private readonly statusStore = createStore<EngineSnapshot>(() => ({ status: 'idle', error: null }));
@@ -380,12 +383,30 @@ class EngineHostImpl {
try {
const canvas = this.ensureCanvas();
const backend = await this.resolveBackend();
- await this.bootCore(canvas, { runLoop: true, loadInitialScene: true, backend });
+ const colorSpace = await this.resolveColorSpace();
+ await this.bootCore(canvas, { runLoop: true, loadInitialScene: true, backend, colorSpace });
} catch (err) {
this.swallowUnwind(err);
}
}
+ /**
+ * The project's declared color space (Project Settings → Rendering), read
+ * straight from the manifest: shaders compile against it, so it must be known
+ * before bootCore — and EngineHost cannot import ProjectStore (which imports
+ * EngineHost). No project / unreadable manifest ⇒ the default gamma pipeline.
+ */
+ private async resolveColorSpace(): Promise<'gamma' | 'linear'> {
+ try {
+ const raw = JSON.parse(await window.estella.fs.read(PROJECT_MANIFEST_FILE)) as {
+ features?: { rendering?: { colorSpace?: unknown } };
+ };
+ return raw.features?.rendering?.colorSpace === 'linear' ? 'linear' : 'gamma';
+ } catch {
+ return 'gamma';
+ }
+ }
+
/**
* The viewport's GPU backend: the persisted `renderer.backend` setting, with a
* safe fall back to WebGL2 when WebGPU is requested but unavailable (no
@@ -453,7 +474,8 @@ class EngineHostImpl {
) {
const backend = opts.backend ?? 'webgl2';
this.activeBackend = backend;
- console.info(`[engine] backend: ${backend}`);
+ this.activeColorSpace = opts.colorSpace ?? 'gamma';
+ console.info(`[engine] backend: ${backend}, colorSpace: ${this.activeColorSpace}`);
// Early build-consistency check: compare the wasm's stamped manifest
// (variant / ABI / provenance) against this SDK before the heavy
// instantiate. Advisory only — the runtime bridge handshake is the
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index 31d5b0a45..070077723 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -61,6 +61,8 @@ export interface PlayPayload {
audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer — forwarded. */
ySortLayers?: number;
+ /** Project color space — 'linear' boots the realm on the linear-light pipeline. */
+ colorSpace?: 'gamma' | 'linear';
/** Multiplayer preview role; absent = a plain single-player session. */
net?: PlayNetConfig;
}
diff --git a/desktop/src/gameHost.ts b/desktop/src/gameHost.ts
index 431cb3537..a83a9f69f 100644
--- a/desktop/src/gameHost.ts
+++ b/desktop/src/gameHost.ts
@@ -20,6 +20,8 @@ interface GameConfig {
scenes?: Array<{ name: string; path: string }>;
/** Bitmask of render layers (0..31) that y-sort within the layer. */
ySortLayers?: number;
+ /** Project color space — 'linear' boots the linear-light pipeline. */
+ colorSpace?: 'gamma' | 'linear';
}
interface CookedManifest {
entries: { uuid: string; path: string; sourcePath?: string; type: string; atlas?: CookedAtlasInfo }[];
@@ -103,6 +105,7 @@ async function boot(): Promise<void> {
const app = createWebApp(module, {
glContextHandle: glHandle,
ySortLayers: cfg.ySortLayers,
+ colorSpace: cfg.colorSpace,
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 1c94750e1..e3e97b80a 100644
--- a/desktop/src/i18n/messages/settings.ts
+++ b/desktop/src/i18n/messages/settings.ts
@@ -48,6 +48,7 @@ export const settingsMessages = defineMessages({
'set.group.designResolution': { en: 'Design Resolution', zh: '设计分辨率' },
'set.group.sortingLayers': { en: 'Sorting Layers', zh: '排序层' },
'set.group.ySort': { en: 'Y-Sort', zh: 'Y 轴排序' },
+ 'set.group.colorSpace': { en: 'Color Space', zh: '色彩空间' },
'set.group.physics': { en: 'Physics', zh: '物理' },
'set.group.gravity': { en: 'Gravity', zh: '重力' },
'set.group.collisionLayers': { en: 'Collision Layers', zh: '碰撞层' },
@@ -108,6 +109,13 @@ export const settingsMessages = defineMessages({
en: 'Name render sorting layers (lowest first); a render `layer` field then picks from them instead of a raw number.',
zh: '为渲染排序层命名(最低层在前);渲染组件的 layer 字段将从中选择,而非填原始数字。',
},
+ 'set.project.rendering.colorSpace': { en: 'Color space', zh: '色彩空间' },
+ 'set.project.rendering.colorSpace.desc': {
+ en: 'Linear renders in physically-correct linear light: textures decode from sRGB on sample, lights and tints blend linearly, and the final frame encodes back to sRGB. Gamma is the classic pipeline. Applies to the editor, Play, and every export after a reload.',
+ zh: '线性模式以物理正确的线性光渲染:纹理采样时从 sRGB 解码、光照与染色在线性空间混合、最终画面编码回 sRGB。伽马为经典管线。重新加载后对编辑器、运行预览和所有导出生效。',
+ },
+ 'set.project.rendering.colorSpace.gamma': { en: 'Gamma', zh: '伽马' },
+ 'set.project.rendering.colorSpace.linear': { en: 'Linear', zh: '线性' },
'set.project.rendering.ySortLayers': { en: 'Y-sorted layers', zh: 'Y 轴排序层' },
'set.project.rendering.ySortLayers.desc': {
en: 'Entities on a checked layer draw in world-Y order (lower on screen on top) — top-down occlusion. Within a y-sorted layer, paint order wins over material batching.',
@@ -197,4 +205,8 @@ export const settingsMessages = defineMessages({
en: 'Reload to render with {backend}',
zh: '重新加载后使用 {backend} 渲染',
},
+ 'toast.colorSpaceReload': {
+ en: 'Reload to apply the new color space',
+ zh: '重新加载后应用新的色彩空间',
+ },
});
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index 184bcb02b..05e5bac78 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -175,6 +175,7 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
app = createWebApp(module, {
glContextHandle: glHandle,
ySortLayers: msg.ySortLayers,
+ colorSpace: msg.colorSpace,
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 896e731a9..1ca92daaa 100644
--- a/desktop/src/playableHost.ts
+++ b/desktop/src/playableHost.ts
@@ -26,6 +26,7 @@ declare const __GAME_PATHMAP__: Record<string, string>;
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';
function decodeBase64(b64: string): Uint8Array {
const raw = atob(b64);
@@ -73,6 +74,8 @@ async function boot(): Promise<void> {
const app = createWebApp(module, {
glContextHandle: glHandle,
+ // Older exports predate the color-space global; treat it as optional.
+ colorSpace: typeof __GAME_COLORSPACE__ !== 'undefined' ? __GAME_COLORSPACE__ : 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 119420387..bfba39b79 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -788,6 +788,7 @@ class ProjectStoreImpl {
physicsConfig?: PhysicsPluginConfig;
audioConfig?: AudioProjectConfig;
ySortLayers?: number;
+ colorSpace?: 'gamma' | 'linear';
} | null {
const sceneData = SceneModel.serialize();
if (!sceneData) return null;
@@ -817,10 +818,12 @@ class ProjectStoreImpl {
}
const ySortLayers = this.ySortMask();
const audioConfig = this.audioFeature();
+ const colorSpace = this.renderingFeature().colorSpace;
return {
sceneData, assetManifest, physicsEnabled: f.enabled, physicsConfig,
...(audioConfig.buses ? { audioConfig } : {}),
...(ySortLayers !== 0 ? { ySortLayers } : {}),
+ ...(colorSpace === 'linear' ? { colorSpace } : {}),
};
}
@@ -881,11 +884,12 @@ class ProjectStoreImpl {
}
/** Named render sorting layers (z-order = slot index). Default empty list. */
- renderingFeature(): { sortingLayers: string[]; ySortLayers: number[] } {
+ renderingFeature(): { sortingLayers: string[]; ySortLayers: number[]; colorSpace: 'gamma' | 'linear' } {
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',
};
}
@@ -904,11 +908,18 @@ class ProjectStoreImpl {
.filter((o) => o.label !== '');
}
- /** Set rendering-feature config (sorting layers, y-sort) and persist to the manifest. */
- async setRendering(patch: { sortingLayers?: string[]; ySortLayers?: number[] }): Promise<void> {
+ /** 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> {
const st = this.state;
if (!st) return;
- const rendering: NonNullable<ProjectFeatures['rendering']> = { ...st.features?.rendering, ...patch };
+ const rendering: NonNullable<ProjectFeatures['rendering']> = { ...st.features?.rendering };
+ if (patch.sortingLayers) rendering.sortingLayers = patch.sortingLayers;
+ if (patch.ySortLayers) rendering.ySortLayers = patch.ySortLayers;
+ // '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;
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 714f8af1c..4340412ab 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -88,6 +88,10 @@ export interface ProjectFeatures {
sortingLayers?: string[];
/** Indices of sorting layers that y-sort within the layer (top-down occlusion). */
ySortLayers?: number[];
+ /** Render color space. 'linear' = linear-light pipeline (sRGB decode on
+ * sample, linear blending, OETF at the final blit). Fixed at engine boot —
+ * shaders compile against it. Absent ⇒ 'gamma'. */
+ colorSpace?: 'linear';
};
/** Project mixer state (bus volumes / custom buses / effects / duck rules). */
audio?: AudioProjectConfig;
@@ -280,6 +284,8 @@ export function parseManifest(raw: unknown): ProjectManifest {
rendering.ySortLayers = r.ySortLayers
.filter((n): n is number => typeof n === 'number' && Number.isInteger(n) && n >= 0 && n < 32);
}
+ // Only 'linear' persists; 'gamma' (the default) is expressed by absence.
+ if (r.colorSpace === 'linear') rendering.colorSpace = 'linear';
if (Object.keys(rendering).length > 0) features.rendering = rendering;
}
if (f.audio && typeof f.audio === 'object') {
diff --git a/desktop/src/settings/projectSettings.ts b/desktop/src/settings/projectSettings.ts
index 936a19621..d74d96163 100644
--- a/desktop/src/settings/projectSettings.ts
+++ b/desktop/src/settings/projectSettings.ts
@@ -9,6 +9,8 @@
*/
import { settingsRegistry } from './registry';
import { ProjectStore } from '@/project/ProjectStore';
+import { EngineHost } from '@/engine/EngineHost';
+import { Toasts } from '@/store/Toasts';
import { t } from '@/i18n';
// ── Display (design/reference resolution; seeds new Canvas entities) ──
@@ -60,6 +62,35 @@ settingsRegistry.register({
},
});
+settingsRegistry.register({
+ id: 'project.rendering.colorSpace',
+ type: 'enum',
+ scope: 'project',
+ section: 'rendering',
+ group: t('set.group.colorSpace'),
+ label: t('set.project.rendering.colorSpace'),
+ description: t('set.project.rendering.colorSpace.desc'),
+ default: 'gamma',
+ segmented: true,
+ options: [
+ { value: 'gamma', label: t('set.project.rendering.colorSpace.gamma') },
+ { value: 'linear', label: t('set.project.rendering.colorSpace.linear') },
+ ],
+ bind: {
+ get: () => ProjectStore.renderingFeature().colorSpace,
+ // Shaders compile against the color space, so it is fixed at engine boot —
+ // persist, then prompt for a reload when it differs from the live frame
+ // (the renderer.backend precedent).
+ set: (v) => {
+ void ProjectStore.setRendering({ colorSpace: v as 'gamma' | 'linear' });
+ if (v !== EngineHost.activeColorSpace) {
+ Toasts.push(t('toast.colorSpaceReload'), 'info', 8000,
+ { label: t('ui.reloadNow'), run: () => location.reload() });
+ }
+ },
+ },
+});
+
settingsRegistry.register({
id: 'project.rendering.ySortLayers',
type: 'flagList',
diff --git a/desktop/tests/project-rendering.test.ts b/desktop/tests/project-rendering.test.ts
new file mode 100644
index 000000000..a3990e5f3
--- /dev/null
+++ b/desktop/tests/project-rendering.test.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file parseManifest — rendering feature (Project Settings → Rendering). Guards the
+ * colorSpace project setting: 'linear' persists, the default 'gamma' is expressed
+ * by absence, and junk values are dropped.
+ */
+import { describe, it, expect } from 'vitest';
+import { parseManifest } from '../src/project/format';
+
+describe('parseManifest — rendering.colorSpace', () => {
+ it("keeps 'linear'", () => {
+ const m = parseManifest({ name: 'X', features: { rendering: { colorSpace: 'linear' } } });
+ expect(m.features?.rendering?.colorSpace).toBe('linear');
+ });
+
+ it("drops 'gamma' (default = absence) and junk values", () => {
+ for (const v of ['gamma', 'LINEAR', 42, true, null]) {
+ const m = parseManifest({ name: 'X', features: { rendering: { colorSpace: v } } });
+ expect(m.features?.rendering?.colorSpace).toBeUndefined();
+ }
+ });
+
+ it('coexists with sorting/y-sort config', () => {
+ const m = parseManifest({
+ name: 'X',
+ features: { rendering: { sortingLayers: ['BG', 'FG'], ySortLayers: [1], colorSpace: 'linear' } },
+ });
+ expect(m.features?.rendering).toEqual({
+ sortingLayers: ['BG', 'FG'],
+ ySortLayers: [1],
+ colorSpace: 'linear',
+ });
+ });
+});
diff --git a/docs/astro/src/content/docs/guides/lighting.mdx b/docs/astro/src/content/docs/guides/lighting.mdx
index 932e8ffdf..cfdbc2824 100644
--- a/docs/astro/src/content/docs/guides/lighting.mdx
+++ b/docs/astro/src/content/docs/guides/lighting.mdx
@@ -171,6 +171,27 @@ Shadow **quality** is controlled on the light, not the caster:
- **`shadowDistance`** — for a **Directional** light, how far its shadows extend; `0`
leaves a directional light shadow-free.
+## Linear color space
+
+By default the engine renders **gamma-space** — colors blend as-authored, the way 2D
+pipelines classically have. A project can switch to the **linear-light pipeline**:
+textures decode from sRGB to linear on sample (in hardware), lights and tints blend in
+linear light, and the finished frame encodes back to sRGB in the final blit.
+
+Physically-correct blending changes how light *accumulates*: falloffs stop crushing to
+black, and overlapping lights add like light instead of paint. Unlit art round-trips
+unchanged — decode followed by encode is an identity — so switching does not repaint
+your sprites; the difference shows wherever colors mix.
+
+Enable it in **Project Settings → Rendering → Color space → Linear**. Shaders compile
+against the mode, so it is fixed at engine boot — the editor prompts for a reload. The
+setting rides the project manifest: the viewport, Play, and every export — web, desktop,
+WeChat, playable — boot the same pipeline. Code-first projects pass it at app creation:
+
+```typescript
+const app = createWebApp(module, { colorSpace: 'linear' });
+```
+
## In the editor
- **Add a light** via **Create… → Light**, or add a `Light2D` component to an existing
diff --git a/docs/astro/src/content/docs/zh-cn/guides/lighting.mdx b/docs/astro/src/content/docs/zh-cn/guides/lighting.mdx
index 4cb070c76..1a9cebfea 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/lighting.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/lighting.mdx
@@ -166,6 +166,23 @@ cmds.spawn()
阴影)。
- **`shadowDistance`** — 对 **Directional** 光,阴影延伸多远;`0` 让方向光不产生阴影。
+## 线性色彩空间
+
+引擎默认以**伽马空间**渲染——颜色按作者所写直接混合,这是 2D 管线的经典方式。项目可以切换到
+**线性光管线**:纹理在采样时从 sRGB 解码到线性(硬件完成)、光照与染色在线性光下混合、最终画面在
+末尾 blit 时编码回 sRGB。
+
+物理正确的混合改变的是光的*叠加方式*:衰减不再压向死黑,多盏灯的重叠像光一样相加而不是像颜料。
+不受光的美术资源经解码再编码是恒等回环——切换不会"重画"你的精灵;差异只出现在颜色相互混合的地方。
+
+在 **项目设置 → 渲染 → 色彩空间 → 线性** 启用。着色器按该模式编译,所以它在引擎启动时定死——
+编辑器会提示重新加载。设置随项目清单走:视口、运行预览和所有导出——web、桌面、微信、playable——
+启动同一条管线。纯代码项目在创建应用时传入:
+
+```typescript
+const app = createWebApp(module, { colorSpace: 'linear' });
+```
+
## 在编辑器里
- 通过 **创建… → 光** 添加光源,或在 Details 面板里给已有实体加一个 `Light2D` 组件。
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index 2defd8aa9..4273ecc6e 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -76,6 +76,8 @@ export interface WeChatRuntimeConfig {
audioConfig?: AudioProjectConfig;
/** Bitmask of render layers (0..31) that y-sort within the layer (Project Settings → Rendering). */
ySortLayers?: number;
+ /** Project color space — 'linear' boots the linear-light pipeline (Project Settings → Rendering). */
+ colorSpace?: 'gamma' | 'linear';
/** id → emscripten factory (`require('./wasm/<file>.js')`); the generated
* game.js supplies exactly the modules the scene needs. Physics + spine
* self-gate off these via {@link createWeChatSideModuleHost}. */
@@ -140,6 +142,7 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
const app = createWebApp(module, {
glContextHandle: glHandle,
ySortLayers: config.ySortLayers,
+ colorSpace: config.colorSpace,
getViewportSize: () => ({
width: canvas.width,
height: canvas.height,