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(agent): the shader picker's list, which no amount of searching could find

yhh0be799840c5b
diff --git a/desktop/electron/agent/prompt.ts b/desktop/electron/agent/prompt.ts
index 145b9ea7b..c2d80cffa 100644
--- a/desktop/electron/agent/prompt.ts
+++ b/desktop/electron/agent/prompt.ts
@@ -44,6 +44,7 @@ Working style:
- Mesh2D geometry is not a component field. Vertices go up through \`Res(Meshes2D)\` — \`meshes.setGeometry(entity, { positions, indices })\` from a system, positions as x,y pairs in local space — so a custom mesh is authored in code and the editor viewport shows it only in Play. set_field cannot reach it.
- Behaviour is a system and data is a component, both declared through the front door: \`defineSystem([Query(Mut(Transform)), Res(Time)], (q, t) => {...})\` and \`defineComponent('Name', { speed: 100 })\`, registered with \`addSystemToSchedule\`. State belonging to no entity — a score, a wave counter — is \`defineResource({ score: 0 }, 'GameState')\`, read with \`Res\` and written with \`ResMut\` (whose value comes through \`.get()\`); PASS THE NAME, because the second argument is what everything outside the module calls it and a resource declared without one answers to \`Resource_49_\` — a counter that lands on a different number the next time the module loads, so a probe that found it once fails on the next run. create_script writes either one already wired into the entry that loads it. The underscore-prefixed fields you can see on those objects (\`_params\`, \`_fn\`, \`_id\`) are the scheduler's, not an authoring surface: assembling one by hand happens to run and leaves a project nobody else's tools understand.
- A game reads input from the ENGINE, never from the DOM. In a system, ask for \`Res(Input)\` and \`Res(CameraView)\`: \`input.isMouseButtonPressed(0)\` (0 = left, 1 = right, 2 = middle — plain numbers; \`MouseButton\` is the InputMap BINDING builder, \`MouseButton(0)\`, and has no \`.Left\`), \`input.mouseX/mouseY\` (SCREEN pixels, canvas-relative, y down), and \`camera.getWorldMousePosition()\` / \`camera.screenToWorld(x, y)\` for where that is in the world — both return \`null\` when there is no camera, so check before using it. \`document.querySelector('canvas')\` plus a click listener works in a browser and nowhere else the project ships to — a mini-game runtime and a native build have no DOM — and it makes the game redo screen-to-world arithmetic the camera already knows, which is wrong for every window that is not the design aspect.
+- A catalog is asked for, not searched for. What the editor offers you — entity templates, shader templates — exists as runtime VALUES, so there is no text of it anywhere in the project and repeated searches for a name you are guessing at will all come back empty while the thing itself is right there. \`list_entity_templates\` and \`list_shader_templates\` are those lists.
- Ask the compiler, do not guess and do not page the .d.ts. \`lookup_symbol\` gives a name's real signature, its doc and where it is declared, in one call — and a CLASS or interface answers with its public members, which is the list you wanted when you asked what it was; \`search_project_files\` finds where something is written, the staged SDK types included, so a type lookup_symbol did not name is one \`query: "interface ThatType"\` away rather than a dozen guesses at a line offset. Writing a .ts file REPORTS ITS TYPE ERRORS in the reply, and \`check_scripts\` asks for them at any time. A game whose script does not compile does not run at all, so an error there is the first thing to fix — not something to discover after the screen comes up black.
- Say what you did in a sentence or two. The user watched it happen — a summary of every call is noise. Speak the user's language: answer in the language they wrote to you in.`;
diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjs
index 48233cc41..11702606e 100644
--- a/desktop/shared/toolCatalog.mjs
+++ b/desktop/shared/toolCatalog.mjs
@@ -382,7 +382,8 @@ const ATOMS = [
js: (i) => `window.estella.project.createScript(${JSON.stringify(i.kind)}, ${JSON.stringify(i.name)}, ${JSON.stringify(i.dir ?? undefined)})` },
{ name: 'create_asset', effect: 'journaled',
description: 'Create a text asset file under a project-relative directory with the given content. `type` is the meta vocabulary: scene, prefab, shader (.esshader), material (.esmaterial), materialgraph (.esmatgraph), animclip (.esanim), animation (.estimeline), tileset, statemachine (.esfsm), behaviortree (.esbt), locale, inputmap, tilemap (.tmj). A bare baseName gets the type\'s canonical extension appended. Returns the project-relative path, immediately referenceable (the registry refresh happens before this resolves). '
- + 'A material graph is the ONE type whose file is not the whole asset: it compiles to a sibling `.esshader`, which is written by save_asset_document — so create it, open_asset it, and save it, rather than leaving a graph with no shader beside it.',
+ + 'A material graph is the ONE type whose file is not the whole asset: it compiles to a sibling `.esshader`, which is written by save_asset_document — so create it, open_asset it, and save it, rather than leaving a graph with no shader beside it. '
+ + "A material's `shader` field names one from list_shader_templates — `builtin:<id>` for a stock template, which needs no shader file of its own; check that list before writing a shader by hand.",
schema: obj({
destDir: { type: 'string' }, baseName: { type: 'string' },
content: { type: 'string' }, type: { type: 'string' },
@@ -543,6 +544,12 @@ const ATOMS = [
{ name: 'list_entity_templates',
description: "The Create-popover catalog: every ready-made entity the editor can spawn (id, label, category). Use an id with create_entity.",
schema: obj({}), method: 'listEntityTemplates', args: () => [], root: 'editor' },
+ { name: 'list_shader_templates',
+ description: "The material picker's catalog: every shader a material can name, and what each one takes. "
+ + 'Answers `[{ ref, label, description, source, params: [{ name, type, default, range? }] }]` — `ref` is EXACTLY what goes in a material\'s `shader` field (`builtin:sprite-outline` for a stock one, the file path for a project `.esshader`), and `params` are the uniforms you then set in its `properties`. '
+ + 'ASK THIS RATHER THAN GUESSING: the stock templates exist only as runtime values and shader source, so their ids and their parameters are in NEITHER the staged types nor anything search_project_files can reach — a project has no text of them to find. '
+ + 'Outline, hit-flash, dissolve, pixelate and UV-scroll are among the ones already here; reaching for a hand-written shader before reading this list is writing one that exists.',
+ schema: obj({}), method: 'listShaderTemplates', args: () => [], root: 'editor' },
{ name: 'create_entity', effect: 'undoable',
description: 'Spawn a ready-made entity from a template id (see list_entity_templates) through the same pipeline as the Create menu; returns the new entity id. Optional world position, parent and NAME. '
+ '`name` matters most for a `prefab:<path>` template: without it every instance arrives called whatever the prefab is called, so ten enemies are ten entities you cannot tell apart. '
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index b0b6af62f..044be388a 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -43,6 +43,7 @@ import './theme/history.css';
import { App } from './App';
import { ProjectStore } from './project/ProjectStore';
import { AssetRegistry } from './project/AssetRegistry';
+import { builtinShaderCatalog, projectShaderEntry } from './material/shaderCatalog';
import { useEditorStore } from './store/editorStore';
import { useSelection } from './store/selectionStore';
import { PlayRealm } from './engine/PlayRealm';
@@ -422,6 +423,17 @@ function buildEditorAutomation(): unknown {
* including the open project's own components and prefabs, so automation sees
* the same list a person does. */
listEntityTemplates: () => allEntitySources().map(({ id, label, category }) => ({ id, label, category })),
+ /** The material picker's catalog: every shader a material can name, and the
+ * parameters each takes. The stock ones exist only as runtime values and
+ * shader source, so nothing about them is in a project's staged types. */
+ listShaderTemplates: async () => {
+ const project = await Promise.all(
+ AssetRegistry.listAssets()
+ .filter((a) => a.path.endsWith('.esshader'))
+ .map(async (a) => projectShaderEntry(a.path, await window.estella.fs.read(a.path))),
+ );
+ return [...builtinShaderCatalog(), ...project];
+ },
/** Create a TilemapLayer from an .estileset with an optional grid layout
* (orientation/stagger/hex) — drives the New-Tilemap flow headlessly. */
// Throws where the UI toasts: a headless caller has no screen to read the
diff --git a/desktop/src/material/shaderCatalog.ts b/desktop/src/material/shaderCatalog.ts
new file mode 100644
index 000000000..789283a54
--- /dev/null
+++ b/desktop/src/material/shaderCatalog.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file shaderCatalog.ts
+ * @brief Every shader a material can be bound to, with the parameters each one
+ * takes — the list the material picker shows, as data.
+ *
+ * The stock templates exist only as runtime values and shader source, so nothing
+ * about them reaches a project's staged `.d.ts`: their ids and their `#pragma
+ * param` declarations cannot be found by reading types or grepping the project.
+ * Reflection is the SAME call the inspector makes, so there is no second list.
+ */
+import { BUILTIN_SHADER_TEMPLATES, reflectEsshader, type ShaderParam } from 'esengine';
+import { BUILTIN_SHADER_PREFIX } from './materialInspectorModel';
+
+/** One parameter of a shader, as a caller needs it to write a material. */
+export interface ShaderParamInfo {
+ name: string;
+ type: string;
+ /** Default components, 1–4 of them; empty for a texture parameter. */
+ default: number[];
+ defaultTexture?: string;
+ range?: { min: number; max: number };
+}
+
+/** One entry of the picker: what to write as the material's `shader`, and what
+ * that shader then takes. */
+export interface ShaderCatalogEntry {
+ /** Exactly what goes in a material's `shader` field. */
+ ref: string;
+ label: string;
+ description: string;
+ source: 'builtin' | 'project';
+ params: ShaderParamInfo[];
+}
+
+const info = (p: ShaderParam): ShaderParamInfo => ({
+ name: p.name,
+ type: p.type,
+ default: [...p.default],
+ ...(p.defaultTexture === undefined ? {} : { defaultTexture: p.defaultTexture }),
+ ...(p.range === undefined ? {} : { range: { ...p.range } }),
+});
+
+/** The stock templates. Pure — the project half is added by the caller that can
+ * read files. */
+export function builtinShaderCatalog(): ShaderCatalogEntry[] {
+ return BUILTIN_SHADER_TEMPLATES.map((t) => ({
+ ref: `${BUILTIN_SHADER_PREFIX}${t.id}`,
+ label: t.label,
+ description: t.description,
+ source: 'builtin' as const,
+ params: reflectEsshader(t.source).params.map(info),
+ }));
+}
+
+/** A project's own `.esshader`, read the same way. Its ref is the path itself. */
+export function projectShaderEntry(path: string, source: string): ShaderCatalogEntry {
+ return {
+ ref: path,
+ label: path.split('/').pop() ?? path,
+ description: '',
+ source: 'project',
+ params: reflectEsshader(source).params.map(info),
+ };
+}
diff --git a/desktop/tests/shader-catalog.test.ts b/desktop/tests/shader-catalog.test.ts
new file mode 100644
index 000000000..ee8e79794
--- /dev/null
+++ b/desktop/tests/shader-catalog.test.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The list of shaders a material can name.
+ *
+ * Measured on a real run before this existed: 47% of the calls went on finding
+ * an API, and `sprite-outline` — which is one of these, described as exactly
+ * what was wanted — was searched for three times and missed three times. The
+ * ids and their parameters are runtime values, so a project holds no text of
+ * them; a catalog that is not asked for cannot be found at all.
+ */
+import { describe, it, expect } from 'vitest';
+import { builtinShaderCatalog, projectShaderEntry } from '@/material/shaderCatalog';
+
+const catalog = builtinShaderCatalog();
+const byRef = (ref: string) => catalog.find((e) => e.ref === ref);
+
+describe('the stock templates', () => {
+ it('answers with a ref that is what goes in the material', () => {
+ for (const entry of catalog) expect(entry.ref).toMatch(/^builtin:[a-z0-9-]+$/);
+ });
+
+ it('carries every one the engine has', () => {
+ expect(catalog.length).toBeGreaterThanOrEqual(7);
+ for (const id of ['sprite-unlit', 'sprite-lit', 'sprite-outline', 'sprite-dissolve']) {
+ expect(byRef(`builtin:${id}`)).toBeTruthy();
+ }
+ });
+
+ it('says what each one is for, in the words the picker shows', () => {
+ expect(byRef('builtin:sprite-outline')).toMatchObject({
+ label: expect.stringMatching(/outline/i),
+ description: expect.stringMatching(/outline/i),
+ source: 'builtin',
+ });
+ });
+
+ // The other half of the guessing: the uniform names. Reflected from the same
+ // source the material is compiled from, so a name here is a name that works.
+ it('lists the parameters each one takes, with their defaults', () => {
+ const outline = byRef('builtin:sprite-outline')!;
+ expect(outline.params.length).toBeGreaterThan(0);
+ for (const p of outline.params) {
+ expect(p.name).toMatch(/^u_/);
+ expect(typeof p.type).toBe('string');
+ expect(Array.isArray(p.default)).toBe(true);
+ }
+ });
+});
+
+describe("a project's own shader", () => {
+ it('is named by its path and reflected the same way', () => {
+ const entry = projectShaderEntry('assets/shaders/wave.esshader', [
+ '#pragma param u_amplitude float default(0.5) range(0,1)',
+ '#pragma param u_tint color default(1,1,1,1)',
+ ].join('\n'));
+ expect(entry).toMatchObject({ ref: 'assets/shaders/wave.esshader', label: 'wave.esshader', source: 'project' });
+ expect(entry.params.map((p) => p.name)).toEqual(['u_amplitude', 'u_tint']);
+ expect(entry.params[0].range).toEqual({ min: 0, max: 1 });
+ });
+});