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): shareable shaders — Shader picker + builtin: refs
yhh77c1672fd03c
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.tsindex 4c9c399b7..988dc066b 100644--- a/desktop/electron/cookAssets.ts+++ b/desktop/electron/cookAssets.ts@@ -122,7 +122,8 @@ function rewriteMaterialRefs(const json = JSON.parse(Buffer.from(bytes).toString('utf8')) as Record<string, unknown>;const dir = matPath.includes('/') ? matPath.slice(0, matPath.lastIndexOf('/')) : '';const rewrite = (ref: unknown): unknown => {- if (typeof ref !== 'string' || ref.startsWith('@uuid:') || ref.includes('://')) return ref;+ // `builtin:<id>` shaders compile from in-code templates (no file); pass through like @uuid/URLs.+ if (typeof ref !== 'string' || ref.startsWith('@uuid:') || ref.startsWith('builtin:') || ref.includes('://')) return ref;const norm = ref.replace(/^\.\//, '').replace(/^\//, '');if (byPath.has(norm)) return ref; // already a logical project pathconst joined = dir ? `${dir}/${norm}` : norm;diff --git a/desktop/src/i18n/messages/content.ts b/desktop/src/i18n/messages/content.tsindex 54ba5ff1e..790cfb22a 100644--- a/desktop/src/i18n/messages/content.ts+++ b/desktop/src/i18n/messages/content.ts@@ -69,6 +69,7 @@ export const contentMessages = defineMessages({'cb.menuNewLocaleTable': { en: 'New Locale Table', zh: '新建本地化表' },'cb.menuNewMaterial': { en: 'New Material', zh: '新建材质' },'cb.menuNewMaterialGraph': { en: 'New Material Graph', zh: '新建材质图' },+ 'cb.menuNewShader': { en: 'New Shader', zh: '新建着色器' },'cb.menuNewStateMachine': { en: 'New State Machine', zh: '新建状态机' },'cb.menuNewAnimatorController': { en: 'New Animation Controller', zh: '新建动画控制器' },'cb.menuNewBehaviorTree': { en: 'New Behavior Tree', zh: '新建行为树' },diff --git a/desktop/src/i18n/messages/material.ts b/desktop/src/i18n/messages/material.tsindex 149d5e171..cc9e8ddca 100644--- a/desktop/src/i18n/messages/material.ts+++ b/desktop/src/i18n/messages/material.ts@@ -35,8 +35,28 @@ export const materialMessages = defineMessages({'mat.created': { en: 'Created material: {name}', zh: '已创建材质:{name}' },'mat.createInstanceFailed': { en: 'Failed to create material instance: {error}', zh: '创建材质实例失败:{error}' },'mat.createdInstance': { en: 'Created material instance: {name}', zh: '已创建材质实例:{name}' },+ 'mat.convertFailed': { en: 'Failed to convert shader: {error}', zh: '转换着色器失败:{error}' },+ 'mat.convertedShader': { en: 'Extracted shader: {name}', zh: '已提取着色器:{name}' },+ 'mat.createShaderFailed': { en: 'Failed to create shader: {error}', zh: '创建着色器失败:{error}' },+ 'mat.createdShader': { en: 'Created shader: {name}', zh: '已创建着色器:{name}' },// — Material inspector sections + render state (material/materialInspectorModel.ts) —+ 'mat.shader': { en: 'Shader', zh: '着色器' },+ 'mat.shaderTip': {+ en: 'The shader that defines this material’s parameters and how it renders. Pick another to switch effects, or share one shader across several materials.',+ zh: '定义此材质参数与渲染方式的着色器。选择其他着色器可切换效果,也可让多个材质共用同一个着色器。',+ },+ 'mat.shaderInherited': { en: 'Shader inherited from the parent material.', zh: '着色器继承自父材质。' },+ 'mat.shaderMissing': {+ en: 'Shader “{ref}” not found — it may have been renamed or moved. Pick it again below.',+ zh: '未找到着色器“{ref}”——它可能已被重命名或移动。请在下方重新选择。',+ },+ 'mat.shaderBuiltin': { en: 'Built-in · {name}', zh: '内置 · {name}' },+ 'mat.convertToUnique': { en: 'Convert to Unique Shader', zh: '转为独立着色器' },+ 'mat.convertToUniqueTip': {+ en: 'Copy this built-in shader into an editable .esshader file beside the material, so you can hand-edit its source.',+ zh: '把这个内置着色器复制成材质旁的可编辑 .esshader 文件,以便手动编辑其源码。',+ },'mat.parameters': { en: 'Parameters', zh: '参数' },'mat.renderState': { en: 'Render State', zh: '渲染状态' },'mat.blendMode': { en: 'Blend Mode', zh: '混合模式' },diff --git a/desktop/src/material/materialInspectorModel.ts b/desktop/src/material/materialInspectorModel.tsindex 7052a05a1..e477b4c61 100644--- a/desktop/src/material/materialInspectorModel.ts+++ b/desktop/src/material/materialInspectorModel.ts@@ -12,7 +12,7 @@* handle for the live viewport preview. The engine stays the single source of the* std140 layout; this is the editor view of the declarations.*/-import { BlendMode, CullMode, Material, type MaterialAssetData, type UniformValue } from 'esengine';+import { BlendMode, CullMode, Material, builtinShaderTemplate, type MaterialAssetData, type UniformValue } from 'esengine';import type { InspectorComponent, InspectorField, InspectorFieldType, EnumOption, GradientValue, CurveValue, DimensionValue } from '@/types';import { t } from '@/i18n';import { MaterialDocument } from './MaterialDocument';@@ -31,6 +31,10 @@ const CULL_OPTIONS: EnumOption[] = [{ label: t('mat.cullFront'), value: CullMode.Front },];+/** A material's `shader` ref that names a stock template (compiled from in-code source, no file),+ * e.g. `builtin:sprite-unlit`. Mirrors the SDK loader's own literal. */+export const BUILTIN_SHADER_PREFIX = 'builtin:';+const ARITY: Record<string, number> = { float: 1, int: 1, vec2: 2, vec3: 3, vec4: 4, color: 4 };const VEC_KEYS = ['x', 'y', 'z', 'w'] as const;const RENDER_STATE_KEYS = new Set(['blendMode', 'depthTest', 'depthWrite', 'cull']);@@ -84,6 +88,47 @@ export function isMaterialAsset(path: string): boolean {return /\.(esmaterial|esmat)$/i.test(path);}+/** Collapse `.`/`..` segments in a project-relative path. */+function normalizeProjectPath(p: string): string {+ const out: string[] = [];+ for (const seg of p.split('/')) {+ if (seg === '' || seg === '.') continue;+ if (seg === '..') out.pop();+ else out.push(seg);+ }+ return out.join('/');+}++/**+ * A material's stored `shader` ref → the referenced shader's project path — what the inspector's+ * asset picker displays and resolves. `/`-rooted refs are project-absolute (cook's spelling for a+ * cross-folder ref); everything else is relative to the material's own directory. Returns '' when+ * no shader is bound (a material instance, which inherits its shader from the parent).+ */+export function shaderProjectPathOf(matPath: string, shaderRef: string | undefined): string {+ if (!shaderRef) return '';+ if (shaderRef.startsWith('/')) return normalizeProjectPath(shaderRef.slice(1));+ const dir = matPath.includes('/') ? matPath.slice(0, matPath.lastIndexOf('/') + 1) : '';+ return normalizeProjectPath(dir + shaderRef);+}++/**+ * The inverse: a picked shader's project path → the ref stored in the material, spelled relative+ * to the material's directory. Same-folder shaders get a bare `name.esshader` (exactly what New+ * Material writes, and the always-safe spelling); a different folder yields a `../`-relative path.+ */+export function shaderRelRef(matPath: string, shaderProjPath: string): string {+ const matDir = matPath.includes('/') ? matPath.slice(0, matPath.lastIndexOf('/')) : '';+ const shDir = shaderProjPath.includes('/') ? shaderProjPath.slice(0, shaderProjPath.lastIndexOf('/')) : '';+ const name = shaderProjPath.slice(shaderProjPath.lastIndexOf('/') + 1);+ if (shDir === matDir) return name;+ const from = matDir ? matDir.split('/') : [];+ const to = shDir ? shDir.split('/') : [];+ let i = 0;+ while (i < from.length && i < to.length && from[i] === to[i]) i++;+ return [...from.slice(i).map(() => '..'), ...to.slice(i), name].join('/');+}+export interface MaterialContext {reflection: ShaderReflection;/** Resolved parameter values inherited from the parent chain (empty for a base material). */@@ -125,11 +170,17 @@ export async function resolveMaterialContext(const root = chain[chain.length - 1];let shaderSource: string | null = null;- if (root?.asset.shader) {- try {- shaderSource = await window.estella.fs.read(resolveRef(root.asset.shader, dirOf(root.path)));- } catch {- shaderSource = null;+ const rootShader = root?.asset.shader;+ if (rootShader) {+ if (rootShader.startsWith(BUILTIN_SHADER_PREFIX)) {+ // A stock shader reflects from its in-code template source — no file to read.+ shaderSource = builtinShaderTemplate(rootShader.slice(BUILTIN_SHADER_PREFIX.length))?.source ?? null;+ } else {+ try {+ shaderSource = await window.estella.fs.read(resolveRef(rootShader, dirOf(root.path)));+ } catch {+ shaderSource = null;+ }}}diff --git a/desktop/src/material/openMaterial.ts b/desktop/src/material/openMaterial.tsindex 942af295d..ece14f8fe 100644--- a/desktop/src/material/openMaterial.ts+++ b/desktop/src/material/openMaterial.ts@@ -14,6 +14,7 @@ import { useSelection } from '@/store/selectionStore';import { baseName } from '@/project/assetMeta';import { Toasts } from '@/store/Toasts';import { t } from '@/i18n';+import { MaterialDocument } from './MaterialDocument';/*** Open a `.esmaterial` for editing: select it so the unified Details inspector edits it inline@@ -39,7 +40,12 @@ async function writeMeta(rel: string): Promise<void> {);}-/** Create a new base material (+ its own shader from a builtin template) in @p dir, then open it. */+/**+ * Create a new base material referencing a built-in shader by id (`builtin:<id>`) — no per-material+ * `.esshader` file is spawned (that was an invisible, name-coupled copy; a stock effect is shared by+ * reference, like Unity's built-in shaders). Editing the shader source is an explicit opt-in later+ * via "Convert to Unique Shader". Then open it.+ */export async function createMaterial(dir: string, templateId = 'sprite-unlit'): Promise<void> {const template = builtinShaderTemplate(templateId);if (!template) {@@ -48,13 +54,11 @@ export async function createMaterial(dir: string, templateId = 'sprite-unlit'):}const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';const matRel = uniqueMaterialPath(folder, `New${template.label}Material`);- const base = baseName(matRel).replace(/\.esmaterial$/, '');- const shaderRel = `${folder}${base}.esshader`;const asset: MaterialAssetData = {version: '1.0',type: 'material',- shader: `${base}.esshader`,+ shader: `builtin:${templateId}`,blendMode: 0,depthTest: false,depthWrite: true,@@ -63,7 +67,6 @@ export async function createMaterial(dir: string, templateId = 'sprite-unlit'):};try {- await window.estella.fs.write(shaderRel, template.source);await window.estella.fs.write(matRel, JSON.stringify(asset, null, 2) + '\n');await writeMeta(matRel);} catch (e) {@@ -100,3 +103,63 @@ export async function createMaterialInstance(parentPath: string): Promise<void>Toasts.push(t('mat.createdInstance', { name: baseName(matRel) }), 'info');openMaterial(matRel);}++// Pick a `<base>.esshader` name in @p dir that no tracked asset already uses. A refreshAssets scan+// then adopts the file (mints its `.meta` uuid/type — see EXT_TO_TYPE) so it becomes pickable.+function uniqueShaderPath(dir: string, base: string): string {+ let rel = `${dir}${base}.esshader`;+ for (let n = 1; ProjectStore.assetRef(rel); n++) rel = `${dir}${base}-${n}.esshader`;+ return rel;+}++/**+ * Extract a material's built-in shader into an editable project `.esshader` beside it and re-point+ * the material at the file — the escape hatch for hand-editing a stock effect's source (UE's "make+ * unique"). The only door that turns a shared `builtin:` ref into a per-material file. Parameters+ * carry over unchanged (the template *is* the shader the material already used).+ */+export async function convertShaderToUnique(matPath: string, builtinId: string): Promise<void> {+ const template = builtinShaderTemplate(builtinId);+ if (!template) {+ Toasts.push(t('mat.unknownTemplate', { id: builtinId }), 'error');+ return;+ }+ const folder = matPath.includes('/') ? matPath.slice(0, matPath.lastIndexOf('/') + 1) : '';+ const matBase = baseName(matPath).replace(/\.esmaterial$/, '');+ const shaderRel = uniqueShaderPath(folder, matBase);+ try {+ await window.estella.fs.write(shaderRel, template.source);+ } catch (e) {+ Toasts.push(t('mat.convertFailed', { error: String(e) }), 'error');+ return;+ }+ await ProjectStore.refreshAssets();+ // Re-point the live document (one undo step, dirty until saved), same-folder → bare ref.+ MaterialDocument.edit('Convert to Unique Shader', (d) => {+ d.shader = baseName(shaderRel);+ });+ Toasts.push(t('mat.convertedShader', { name: baseName(shaderRel) }), 'info');+}++/**+ * Create a standalone project `.esshader` from a built-in template — for authoring a shareable+ * shader from scratch; materials point at it through the inspector's Shader picker.+ */+export async function createShaderAsset(dir: string, templateId = 'sprite-unlit'): Promise<void> {+ const template = builtinShaderTemplate(templateId);+ if (!template) {+ Toasts.push(t('mat.unknownTemplate', { id: templateId }), 'error');+ return;+ }+ const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';+ const shaderRel = uniqueShaderPath(folder, `New${template.label}Shader`);+ try {+ await window.estella.fs.write(shaderRel, template.source);+ } catch (e) {+ Toasts.push(t('mat.createShaderFailed', { error: String(e) }), 'error');+ return;+ }+ await ProjectStore.refreshAssets();+ Toasts.push(t('mat.createdShader', { name: baseName(shaderRel) }), 'info');+ useSelection.getState().selectAsset(shaderRel);+}diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex f29ab1c18..b85e2ad22 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -25,7 +25,7 @@ import { createFlipbookFromTexture } from '@/flipbook/openFlipbook';import { createAnimatedSpriteFromClip } from '@/flipbook/createAnimatedSprite';import { createTilemapFromTileset } from '@/tilemap/createTilemap';import { BUILTIN_SHADER_TEMPLATES } from 'esengine';-import { createMaterial, createMaterialInstance } from '@/material/openMaterial';+import { createMaterial, createMaterialInstance, createShaderAsset } from '@/material/openMaterial';import { createMaterialGraph } from '@/material/openMaterialGraph';import { createStateMachine } from '@/fsm/openStateMachine';import { createAnimatorController } from '@/animator/openAnimatorController';@@ -999,6 +999,13 @@ export function ContentBrowser() {})),},{ label: t('cb.menuNewMaterialGraph'), onClick: () => void createMaterialGraph(cwd) },+ {+ label: t('cb.menuNewShader'),+ children: BUILTIN_SHADER_TEMPLATES.map((tpl) => ({+ label: tpl.label,+ onClick: () => void createShaderAsset(cwd, tpl.id),+ })),+ },{ label: t('cb.menuNewStateMachine'), onClick: () => void createStateMachine(cwd) },{ label: t('cb.menuNewAnimatorController'), onClick: () => void createAnimatorController(cwd) },{ label: t('cb.menuNewBehaviorTree'), onClick: () => void createBehaviorTree(cwd) },diff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex 954ecd72a..6a83e58c2 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -13,7 +13,7 @@*/import {Folder, Film, Image, FileImage, PersonStanding, Music,- Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images, Video, Waypoints,+ Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2, GitBranch, ListTree, Languages, Images, Video, Waypoints, Sparkles,type LucideIcon,} from 'lucide-react';import type { AssetType } from '@/types';@@ -43,6 +43,9 @@ export const ASSET_TYPES: Record<AssetType, AssetTypeDef> = {// .esmat is tolerated as a legacy alias (cf. electron/importAssets.ts).material: { extensions: ['esmaterial', 'esmat'], badge: 'MAT', icon: Blend, tint: '#c0917a' },materialgraph: { extensions: ['esmatgraph'], badge: 'MGR', icon: Workflow, tint: '#c0917a' },+ // A `.esshader` is the fragment-shader source (with #pragma param declarations) a material+ // references; recognizable here so it never reads as a mystery "file" next to its material.+ shader: { extensions: ['esshader'], badge: 'SHD', icon: Sparkles, tint: '#c9a26a' },script: { extensions: ['ts', 'js'], badge: 'TS', icon: FileCode2, tint: '#93a3bf' },// Two animation documents, two editors: .estimeline is the Sequencer's// multi-track timeline; .esanim is the sprite flipbook (Flipbook editor).diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex e35f538aa..f45dd8aa2 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -192,6 +192,7 @@ export type AssetType =| 'prefab'| 'material'| 'materialgraph'+ | 'shader'| 'script'| 'animation'| 'animclip'diff --git a/desktop/tests/asset-types.test.ts b/desktop/tests/asset-types.test.tsindex 1a67c71b1..02be85530 100644--- a/desktop/tests/asset-types.test.ts+++ b/desktop/tests/asset-types.test.ts@@ -19,6 +19,7 @@ describe('asset type registry', () => {expect(assetTypeOf('a.esmaterial')).toBe('material'); // real ext (SDK loader)expect(assetTypeOf('a.esmat')).toBe('material'); // legacy aliasexpect(assetTypeOf('a.esmat')).toBe('material');+ expect(assetTypeOf('a.esshader')).toBe('shader');expect(assetTypeOf('a.esanim')).toBe('animclip');expect(assetTypeOf('a.estimeline')).toBe('animation');expect(assetTypeOf('a.estileset')).toBe('tileset');diff --git a/desktop/tests/material-shader-ref.test.ts b/desktop/tests/material-shader-ref.test.tsnew file mode 100644index 000000000..b1707b89b--- /dev/null+++ b/desktop/tests/material-shader-ref.test.ts@@ -0,0 +1,44 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { shaderProjectPathOf, shaderRelRef } from '../src/material/materialInspectorModel';++describe('material shader ref <-> project path', () => {+ it('resolves a same-folder relative ref to the shader project path', () => {+ expect(shaderProjectPathOf('assets/mats/foo.esmaterial', 'bar.esshader')).toBe('assets/mats/bar.esshader');+ });++ it('resolves a `../` relative ref and a `/`-rooted ref', () => {+ expect(shaderProjectPathOf('assets/mats/foo.esmaterial', '../shaders/x.esshader')).toBe('assets/shaders/x.esshader');+ expect(shaderProjectPathOf('assets/mats/foo.esmaterial', '/assets/shaders/x.esshader')).toBe('assets/shaders/x.esshader');+ });++ it('reports no bound shader for an instance / empty ref', () => {+ expect(shaderProjectPathOf('assets/mats/foo.esmaterial', '')).toBe('');+ expect(shaderProjectPathOf('assets/mats/foo.esmaterial', undefined)).toBe('');+ });++ it('stores a same-folder shader as a bare name (what New Material writes)', () => {+ expect(shaderRelRef('assets/mats/foo.esmaterial', 'assets/mats/bar.esshader')).toBe('bar.esshader');+ });++ it('stores a cross-folder shader as a `../`-relative ref', () => {+ expect(shaderRelRef('assets/mats/foo.esmaterial', 'assets/shaders/x.esshader')).toBe('../shaders/x.esshader');+ expect(shaderRelRef('assets/a/b/foo.esmaterial', 'assets/shaders/x.esshader')).toBe('../../shaders/x.esshader');+ });++ it('round-trips: picked project path -> stored ref -> project path', () => {+ const mat = 'assets/mats/foo.esmaterial';+ for (const shader of ['assets/mats/bar.esshader', 'assets/shaders/x.esshader', 'shared/effect.esshader', 'top.esshader']) {+ const ref = shaderRelRef(mat, shader);+ expect(shaderProjectPathOf(mat, ref)).toBe(shader);+ }+ });++ it('handles a material at the project root', () => {+ expect(shaderRelRef('foo.esmaterial', 'bar.esshader')).toBe('bar.esshader');+ expect(shaderProjectPathOf('foo.esmaterial', 'bar.esshader')).toBe('bar.esshader');+ expect(shaderRelRef('foo.esmaterial', 'shaders/x.esshader')).toBe('shaders/x.esshader');+ expect(shaderProjectPathOf('foo.esmaterial', 'shaders/x.esshader')).toBe('shaders/x.esshader');+ });+});diff --git a/sdk/src/asset/loaders/MaterialAssetLoader.ts b/sdk/src/asset/loaders/MaterialAssetLoader.tsindex ab48118cd..e94b1df9a 100644--- a/sdk/src/asset/loaders/MaterialAssetLoader.ts+++ b/sdk/src/asset/loaders/MaterialAssetLoader.ts@@ -3,9 +3,15 @@import type { AssetLoader, LoadContext, MaterialResult } from '../AssetLoader';import type { MaterialAssetData, ShaderHandle } from '../../material';import { Material } from '../../material';+import { builtinShaderTemplate } from '../../builtinShaders';import { AsyncCache } from '../AsyncCache';import { log } from '../../logger';+// A `builtin:<id>` shader ref names a stock template compiled from its in-code source (no file);+// anything else is a path to a project `.esshader`. Kept a literal (not a shared export) so it+// stays out of the public API surface — the editor mirrors it.+const BUILTIN_SHADER_PREFIX = 'builtin:';+export class MaterialAssetLoader implements AssetLoader<MaterialResult> {readonly type = 'material';readonly extensions = ['.esmaterial'];@@ -39,8 +45,7 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {// Enabled static switches select the shader permutation (compiled once per switch-set).const features = enabledSwitches(data.switches);- const shaderPath = resolveRelativePath(path, data.shader);- const shaderHandle = await this.loadShader(shaderPath, features, ctx);+ const shaderHandle = await this.loadShader(path, data.shader, features, ctx);const handle = Material.createFromAsset(data, shaderHandle);const texturePaths = await this.applyTextureProps(handle, data, path, ctx);@@ -84,22 +89,34 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {this.shaderCache_.clearAll();}- // One compiled program per (shader path, enabled-switch set) — distinct switch sets are- // distinct permutations, so the cache key folds the sorted features in.- private async loadShader(path: string, features: string[], ctx: LoadContext): Promise<ShaderHandle> {- const cacheKey = features.length ? `${path}#${features.join('|')}` : path;+ // Compile a material's shader ref — either a `builtin:<id>` stock template (from its in-code+ // source, no file) or a path to a project `.esshader` resolved relative to the material. One+ // compiled program per (resolved key, enabled-switch set) — distinct switch sets are distinct+ // permutations, so the cache key folds the sorted features in.+ private async loadShader(matPath: string, ref: string, features: string[], ctx: LoadContext): Promise<ShaderHandle> {+ const isBuiltin = ref.startsWith(BUILTIN_SHADER_PREFIX);+ const key = isBuiltin ? ref : resolveRelativePath(matPath, ref);+ const cacheKey = features.length ? `${key}#${features.join('|')}` : key;const cached = this.shaderCache_.get(cacheKey);if (cached !== undefined) return cached;return this.shaderCache_.getOrLoad(cacheKey, async () => {- const buildPath = ctx.catalog.getBuildPath(path);- const content = await ctx.loadText(buildPath);+ let content: string;+ if (isBuiltin) {+ const template = builtinShaderTemplate(ref.slice(BUILTIN_SHADER_PREFIX.length));+ if (!template) {+ throw new Error(`Unknown built-in shader: ${ref}`);+ }+ content = template.source;+ } else {+ content = await ctx.loadText(ctx.catalog.getBuildPath(key));+ }// Compile through ShaderParser (engine-side): assembles the stages + the enabled// switch permutation, generates the std140 MaterialConstants block from #pragma param,// and registers the layout so the material's parameters reach the GPU.const handle = Material.compileShader(content, features);if (!handle) {- throw new Error(`Failed to compile material shader: ${path}`);+ throw new Error(`Failed to compile material shader: ${key}`);}return handle;});diff --git a/sdk/tests/material-asset-loader.test.ts b/sdk/tests/material-asset-loader.test.tsindex bde5a04a4..28012c91e 100644--- a/sdk/tests/material-asset-loader.test.ts+++ b/sdk/tests/material-asset-loader.test.ts@@ -99,3 +99,38 @@ describe('MaterialAssetLoader texture release on unload', () => {expect(Material.release).toHaveBeenCalledWith(11);});});++describe('MaterialAssetLoader built-in shader ref', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ (Material.createFromAsset as ReturnType<typeof vi.fn>).mockReturnValue(11);+ (Material.compileShader as ReturnType<typeof vi.fn>).mockReturnValue(7);+ });++ function ctxFor(shader: string): LoadContext {+ const materialJson = JSON.stringify({ type: 'material', shader, properties: {} });+ return {+ catalog: { getBuildPath: (p: string) => p },+ // Only the material is ever read — a built-in shader has no file.+ loadText: vi.fn(async () => materialJson),+ loadTexture: vi.fn(),+ } as unknown as LoadContext;+ }++ it('compiles a `builtin:<id>` shader from its in-code template, reading no shader file', async () => {+ const loader = new MaterialAssetLoader();+ const ctx = ctxFor('builtin:sprite-unlit');++ const result = await loader.load(MAT_PATH, ctx);++ expect(result.shaderHandle).toBe(7);+ expect(ctx.loadText).toHaveBeenCalledTimes(1); // the material, never a shader file+ const compiledSrc = (Material.compileShader as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;+ expect(compiledSrc).toContain('#pragma shader "Sprite Unlit"');+ });++ it('throws on an unknown built-in shader id', async () => {+ const loader = new MaterialAssetLoader();+ await expect(loader.load(MAT_PATH, ctxFor('builtin:does-not-exist'))).rejects.toThrow(/Unknown built-in shader/);+ });+});