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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): per-platform texture Import Settings (Default + platform overrides)
yhhac82c7a67053
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.tsindex f88a4353e..d5cfc45e1 100644--- a/desktop/electron/cookAssets.ts+++ b/desktop/electron/cookAssets.ts@@ -252,6 +252,9 @@ export async function cookAssets(entryScenes: string[]; outDir: string;contentAddressed?: boolean; compressTextures?: boolean; atlasTextures?: boolean;compressAudio?: boolean; transcodeVideo?: boolean;+ /** Target platform — selects each texture's per-platform Import Settings+ * override (Default when absent). No effect on audio/video/atlas. */+ platform?: string;},): Promise<CookResult> {const contentAddressed = opts.contentAddressed ?? false;@@ -259,6 +262,7 @@ export async function cookAssets(const atlasTextures = opts.atlasTextures ?? false;const compressAudio = opts.compressAudio ?? false;const transcodeVideo = opts.transcodeVideo ?? false;+ const platform = opts.platform;const { index } = await scanAssetDatabase(root, { write: false, adopt: false });const byUuid = new Map(index.entries.map((e) => [e.uuid, e]));const byPath = new Map(index.entries.map((e) => [e.path, e]));@@ -451,7 +455,7 @@ export async function cookAssets(// in VRAM, the runtime transcodes per device. Hash + name reflect the ENCODED// bytes, so this composes with content-addressing below.if (textureEnc && entry.type !== 'scene' && ext.toLowerCase() === '.png') {- const tex = readTextureCookSettings(entry.importer);+ const tex = readTextureCookSettings(entry.importer, platform);// maxSize downscale first — it applies even when a texture opts OUT of// compression (a huge UI sprite can ship as a smaller raw PNG).let rgba: Uint8Array | null = null;diff --git a/desktop/electron/exportGame.ts b/desktop/electron/exportGame.tsindex f0676b279..ba71c37b3 100644--- a/desktop/electron/exportGame.ts+++ b/desktop/electron/exportGame.ts@@ -393,7 +393,7 @@ export async function exportGame(opts: {// 1. Cook reachable assets + manifest, from EVERY shippable scene as a root// (the scene files themselves are staged too).progress({ phase: 'Cooking assets' });- const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures });+ const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: payloadDir, contentAddressed: opts.contentAddressed ?? true, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures, platform });warnings.push(...cook.warnings);progress({ phase: 'Cooking assets', detail: `${cook.included.length} reachable` });diff --git a/desktop/electron/exportMiniGame.ts b/desktop/electron/exportMiniGame.tsindex fd1d580a1..3064a6e25 100644--- a/desktop/electron/exportMiniGame.ts+++ b/desktop/electron/exportMiniGame.ts@@ -219,7 +219,7 @@ export async function exportMiniGame(profile: MiniGameExportProfile, opts: {// manifest. KTX2 textures are fine here: the scan below sees the staged// .ktx2 files and ships the Basis transcoder side module with them.progress({ phase: 'Cooking assets' });- const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures, transcodeVideo: true });+ const cook = await cookAssets(opts.root, { entryScenes: scenes.map((s) => s.path), outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, compressAudio: opts.compressAudio, atlasTextures: opts.atlasTextures, transcodeVideo: true, platform: 'wechat' });warnings.push(...cook.warnings);// 1a. Restage for the vendor's code-package suffix whitelist (WeChat has nodiff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsindex 18f384486..57fd3d6ae 100644--- a/desktop/electron/exportPlayable.ts+++ b/desktop/electron/exportPlayable.ts@@ -175,7 +175,10 @@ export async function exportPlayable(opts: {// 1. Cook reachable assets to a temp dir (everything ends up inlined → removed after).progress({ phase: 'Cooking assets' });- const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: cookDir });+ // Playable inlines everything base64 (no KTX2 transcoder), so it doesn't set+ // compressTextures — the platform is threaded for when per-platform Import+ // Settings (e.g. a tighter Max Size for the ad-size cap) gain a raw-downscale path.+ const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: cookDir, platform: 'playable' });warnings.push(...cook.warnings);// 2. Assets → base64 data URLs, keyed by the scene's @uuid: refs; plus adiff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.tsindex 8bf803279..499f9d1dc 100644--- a/desktop/src/i18n/messages/details.ts+++ b/desktop/src/i18n/messages/details.ts@@ -191,6 +191,9 @@ export const detailsMessages = defineMessages({// — Generic asset inspector (import settings + metadata) —'det.importSettings': { en: 'Import Settings', zh: '导入设置' },+ 'det.platformOverrides': { en: 'Platform Overrides', zh: '平台覆盖' },+ 'det.overrideFor': { en: 'Override for {platform}', zh: '覆盖默认设置({platform})' },+ 'det.followsDefault': { en: 'Follows the default — edit it above in Import Settings.', zh: '跟随默认——在上方「导入设置」里编辑。' },'det.saveImportTip': { en: 'Save import settings', zh: '保存导入设置' },'det.importSaved': { en: 'Import settings saved — size / compression apply on the next build', zh: '导入设置已保存——尺寸 / 压缩在下次构建时生效' },'det.importSaveFailed': { en: 'Failed to save import settings: {error}', zh: '保存导入设置失败:{error}' },diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex b78ed7cb1..558873175 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -24,6 +24,10 @@ import {Filter,Hexagon,FolderOpen,+ Globe,+ Monitor,+ MessageSquare,+ Play,Image as ImageIcon,MoreHorizontal,Move3d,@@ -70,7 +74,7 @@ import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, Pimport { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions, boxGroupsFor, isRequiredEmpty, type BoxGroupDef } from '@/engine/schema';import * as imap from '@/project/inputMapDoc';import * as ldoc from '@/project/localeTableDoc';-import { buildImporterComponent, applyImporterEdit } from '@/project/assetImporter';+import { buildImporterComponent, applyImporterEdit, readTextureCookSettings } from '@/project/assetImporter';import { findAssetUsages } from '@/project/assetUsages';import { FindUsagesDialog } from '@/components/FindUsagesDialog';import { ProjectStore } from '@/project/ProjectStore';@@ -3137,6 +3141,68 @@ function MetaRow({ k, v, mono }: { k: string; v: string; mono?: boolean }) {);}+// Per-platform texture Import Settings — Unity's Default + platform tabs. The+// DEFAULT lives in the Import Settings section above; here each target can override+// the axes that actually vary per platform for a Basis "encode once, transcode per+// GPU" pipeline: size cap + whether/how to compress (e.g. WeChat ships smaller /+// ETC1S). Edits write to `overrides.<platform>.*` through the same importer `write`+// seam, so save + dirty tracking are unchanged.+function TexturePlatformOverrides({ importer, write }: { importer: Record<string, unknown>; write: FieldWrite }) {+ const [tab, setTab] = useState('wechat');+ const overrides = (importer.overrides as Record<string, Record<string, unknown>> | undefined) ?? {};+ const ov = overrides[tab] ?? {};+ const enabled = !!ov.enabled;+ const def = readTextureCookSettings(importer); // true default (what an unset field inherits)+ const platLabel: Record<string, string> = {+ web: t('build.plat.web'), desktop: t('build.plat.desktop'),+ wechat: t('build.plat.wechat'), playable: t('build.plat.playable'),+ };+ const fields: InspectorField[] = [+ {+ key: `overrides.${tab}.maxSize`, label: 'Max Size', type: 'enum', category: '',+ options: [256, 512, 1024, 2048, 4096, 8192].map((n) => ({ label: String(n), value: n })),+ value: typeof ov.maxSize === 'number' ? ov.maxSize : def.maxSize, defaultValue: def.maxSize,+ },+ {+ key: `overrides.${tab}.compress`, label: 'Compress', type: 'bool', category: '',+ value: typeof ov.compress === 'boolean' ? ov.compress : def.compress, defaultValue: def.compress,+ },+ {+ key: `overrides.${tab}.compressFormat`, label: 'Format', type: 'select', category: '',+ selectOptions: ['uastc', 'etc1s'],+ value: ov.compressFormat === 'etc1s' || ov.compressFormat === 'uastc' ? ov.compressFormat : def.format,+ defaultValue: def.format,+ },+ ];+ return (+ <div className="tex-plat">+ <div className="tex-plat__hd">{t('det.platformOverrides')}</div>+ <Segmented+ ariaLabel={t('det.platformOverrides')}+ value={tab}+ onChange={setTab}+ options={[+ { value: 'web', icon: <Globe size={13} />, title: platLabel.web },+ { value: 'desktop', icon: <Monitor size={13} />, title: platLabel.desktop },+ { value: 'wechat', icon: <MessageSquare size={13} />, title: platLabel.wechat },+ { value: 'playable', icon: <Play size={13} />, title: platLabel.playable },+ ]}+ />+ <label className="tex-plat__en">+ <input type="checkbox" checked={enabled} onChange={(e) => write(`overrides.${tab}.enabled`, 'bool', e.target.checked)} />+ {t('det.overrideFor', { platform: platLabel[tab] })}+ </label>+ {enabled ? (+ <div className="tex-plat__fields">+ {fields.map((f) => <FieldRow key={f.key} entities={[]} comp="importer" field={f} write={write} />)}+ </div>+ ) : (+ <div className="tex-plat__inherit">{t('det.followsDefault')}</div>+ )}+ </div>+ );+}+// The asset inspector for every type without a bespoke editor. Renders read-only// metadata plus, for types with an importer schema, editable Import Settings// (written to the `.meta` sidecar) through the shared ComponentSection engine.@@ -3304,6 +3370,10 @@ function GenericAssetInspector({ path }: { path: string }) {</div>)}+ {isImage && importer && !collapsed && (+ <TexturePlatformOverrides importer={importer} write={write} />+ )}+<div className="cb-meta" style={{ padding: '8px 10px 0' }}><MetaRow k={t('det.metaPath')} v={path} mono />{dims && <MetaRow k={t('det.metaDimensions')} v={dims} />}diff --git a/desktop/src/project/assetImporter.ts b/desktop/src/project/assetImporter.tsindex 4c3dea2dc..a95133680 100644--- a/desktop/src/project/assetImporter.ts+++ b/desktop/src/project/assetImporter.ts@@ -176,23 +176,46 @@ export function buildImporterComponent(type: string, importer: Record<string, unreturn { name: 'Import Settings', label: 'Import Settings', fields };}+/** The subset of texture cook settings a platform may override — the axes that+ * actually vary per target for a Basis "encode once, transcode per GPU" pipeline:+ * size cap + whether/how to compress. (sRGB is intrinsic to the asset's color, not+ * the platform, so it is NOT overridable.) `enabled` is the inspector's per-platform+ * "Override for <platform>" switch — an override is only applied when it is on. */+export interface TexturePlatformOverride {+ enabled?: boolean;+ maxSize?: number;+ compress?: boolean;+ compressFormat?: 'uastc' | 'etc1s';+}+/** Cook-facing texture settings (compression + downscale), tolerant of hand-edited* `.meta` blocks. Mirrors {@link readAudioImportSettings} — the cook reads this* per asset so each texture decides its own KTX2 format / opt-out / size cap,- * the way audio clips already do. Defaults match a fresh `.meta`. */-export function readTextureCookSettings(importer: Record<string, unknown> | undefined): {+ * the way audio clips already do. When `platform` is given and that platform has+ * an ENABLED override in `importer.overrides`, its present fields win over the+ * defaults per-field (an unset field inherits the default). Defaults match a+ * fresh `.meta`. */+export function readTextureCookSettings(importer: Record<string, unknown> | undefined, platform?: string): {compress: boolean; format: 'uastc' | 'etc1s'; maxSize: number; srgb: boolean;} {const compress = importer?.compress;const format = importer?.compressFormat;const maxSize = importer?.maxSize;const srgb = importer?.sRGB;- return {+ const resolved = {compress: typeof compress === 'boolean' ? compress : true,- format: format === 'etc1s' ? 'etc1s' : 'uastc',+ format: (format === 'etc1s' ? 'etc1s' : 'uastc') as 'uastc' | 'etc1s',maxSize: typeof maxSize === 'number' && maxSize > 0 ? maxSize : 2048,srgb: typeof srgb === 'boolean' ? srgb : true,};+ const overrides = importer?.overrides as Record<string, TexturePlatformOverride> | undefined;+ const ov = platform ? overrides?.[platform] : undefined;+ if (ov?.enabled) {+ if (typeof ov.compress === 'boolean') resolved.compress = ov.compress;+ if (ov.compressFormat === 'etc1s' || ov.compressFormat === 'uastc') resolved.format = ov.compressFormat;+ if (typeof ov.maxSize === 'number' && ov.maxSize > 0) resolved.maxSize = ov.maxSize;+ }+ return resolved;}/** A texture's sampler settings, in the string shape the engine's TextureLoaderdiff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.cssindex 600a43a20..18ad5c937 100644--- a/desktop/src/theme/inspector.css+++ b/desktop/src/theme/inspector.css@@ -437,3 +437,13 @@transition: border-color var(--t-fast), background var(--t-fast);}.map-add:hover { border-color: var(--acc); background: var(--acc-soft); }++/* ── Per-platform texture Import Settings (Default + platform tabs) ────────────+ Sits under the default Import Settings; each target overrides size/compression.+ Reuses the shared FieldRow, so the fields match the rest of the inspector. */+.tex-plat { display: flex; flex-direction: column; gap: 8px; padding: 10px 10px 6px; border-top: 1px solid var(--line-soft); }+.tex-plat__hd { font-size: var(--fs-2xs); font-weight: 700; letter-spacing: 0.4px; text-transform: uppercase; color: var(--text-mute); }+.tex-plat .seg { align-self: stretch; }+.tex-plat__en { display: flex; align-items: center; gap: 8px; font-size: var(--fs-xs); color: var(--text-dim); cursor: pointer; }+.tex-plat__inherit { font-size: var(--fs-2xs); color: var(--text-mute); padding: 1px 0 3px; }+.tex-plat__fields { display: flex; flex-direction: column; }diff --git a/desktop/tests/asset-importer.test.ts b/desktop/tests/asset-importer.test.tsindex d90f7a4f1..55ff522de 100644--- a/desktop/tests/asset-importer.test.ts+++ b/desktop/tests/asset-importer.test.ts@@ -14,6 +14,7 @@ import {applyImporterEdit,hasImporterSettings,readTextureImportSettings,+ readTextureCookSettings,} from '../src/project/assetImporter';describe('importerDefaults (import-time .meta)', () => {@@ -37,6 +38,32 @@ describe('importerDefaults (import-time .meta)', () => {});});+describe('readTextureCookSettings (per-platform resolution)', () => {+ it('resolves defaults from the base block (no overrides)', () => {+ expect(readTextureCookSettings(undefined)).toEqual({ compress: true, format: 'uastc', maxSize: 2048, srgb: true });+ expect(readTextureCookSettings({ compress: false, compressFormat: 'etc1s', maxSize: 512, sRGB: false }))+ .toEqual({ compress: false, format: 'etc1s', maxSize: 512, srgb: false });+ });++ it('an enabled platform override wins per-field, inheriting the rest', () => {+ const imp = {+ maxSize: 2048, compress: true, compressFormat: 'uastc',+ overrides: { wechat: { enabled: true, maxSize: 1024, compressFormat: 'etc1s' } },+ };+ // WeChat: overridden maxSize + format, inherits compress + srgb.+ expect(readTextureCookSettings(imp, 'wechat')).toEqual({ compress: true, format: 'etc1s', maxSize: 1024, srgb: true });+ // Web: no override for that platform → the defaults.+ expect(readTextureCookSettings(imp, 'web')).toEqual({ compress: true, format: 'uastc', maxSize: 2048, srgb: true });+ // No platform (editor cook) → the defaults, override ignored.+ expect(readTextureCookSettings(imp).maxSize).toBe(2048);+ });++ it('a disabled override is ignored (falls back to default)', () => {+ const imp = { maxSize: 2048, overrides: { wechat: { enabled: false, maxSize: 256 } } };+ expect(readTextureCookSettings(imp, 'wechat').maxSize).toBe(2048);+ });+});+describe('hasImporterSettings', () => {it('is true only for types with editable settings', () => {expect(hasImporterSettings('texture')).toBe(true);diff --git a/desktop/tests/cook-assets.test.ts b/desktop/tests/cook-assets.test.tsindex 02cfd0336..ec8cf1d8d 100644--- a/desktop/tests/cook-assets.test.ts+++ b/desktop/tests/cook-assets.test.ts@@ -277,6 +277,40 @@ describe('cookAssets (A4)', () => {}}, 30_000);+ it('applies a per-platform texture override: one asset, smaller raw PNG for WeChat vs KTX2 for web', async () => {+ const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-platov-'));+ try {+ const TEX = '77777777-7777-4777-8777-777777777773';+ const SC = '88888888-8888-4888-8888-888888888883';+ const png = readFileSync(path.resolve(__dirname, '../../examples/hello-world/assets/textures/logo.png'));+ const abs = path.join(r, 't/logo.png');+ mkdirSync(path.dirname(abs), { recursive: true });+ writeFileSync(abs, png);+ // Default: compress (KTX2). WeChat override: ship a small raw PNG instead.+ writeFileSync(`${abs}.meta`, JSON.stringify({+ uuid: TEX, version: '2.0', type: 'texture',+ importer: { compress: true, overrides: { wechat: { enabled: true, compress: false, maxSize: 64 } } },+ }));+ const sc = path.join(r, 's/main.esscene');+ mkdirSync(path.dirname(sc), { recursive: true });+ writeFileSync(sc, JSON.stringify({ version: '1.0', name: 's', entities: [{ id: 1, name: 'E', parent: null, children: [], components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }));+ writeFileSync(`${sc}.meta`, JSON.stringify({ uuid: SC, version: '2.0', type: 'scene', importer: {} }));++ const web = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out-web', compressTextures: true, platform: 'web' });+ const wechat = await cookAssets(r, { entryScenes: ['s/main.esscene'], outDir: 'out-wx', compressTextures: true, platform: 'wechat' });+ const texOf = (res: Awaited<ReturnType<typeof cookAssets>>) =>+ (JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as AssetManifest).entries.find((e) => e.uuid === TEX)!;++ expect(texOf(web).path).toMatch(/\.ktx2$/); // web: default → compressed+ const wx = texOf(wechat);+ expect(wx.path).toMatch(/\.png$/); // wechat override: raw PNG…+ const shrunk = decodePngImage('wx', readFileSync(path.join(wechat.outDir, wx.path)));+ expect(Math.max(shrunk.width, shrunk.height)).toBeLessThanOrEqual(64); // …downscaled to its cap+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ }, 30_000);+it('follows PATH refs: scene → material (project path) → shader + texture (dir-relative)', async () => {const r = mkdtempSync(path.join(tmpdir(), 'estella-cook-pathref-'));try {