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(render): geometry a project can make without a modelling package

yhhd4e61856d584
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3be17adf3..9b9d55087 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,30 @@ published separately; it ships inside the editor.
### Added
+- **Geometry you can make without a modelling package.** The engine drew meshes
+ and loaded exactly one way to get one: import a glTF or an FBX. There was no cube.
+ `examples/physics-3d` is the evidence — a scene of stacked crates, stairs and a
+ swinging door with **not one mesh in it**, showing its own collision wireframe,
+ because putting a box on screen meant leaving the editor to go author one.
+
+ Seven primitives now answer to a `builtin:` mesh ref — cube, sphere, capsule,
+ cylinder, cone, plane, quad — each built in code at load time. **Create → Cube**
+ makes one, and the same seven head the picker on any `Mesh2D.mesh` field. They
+ cost no bytes in a package and add no dependency to a scene that uses one; a
+ capsule is the shape `CapsuleCollider3D` describes, and all seven are the size a
+ new `ShapeRenderer` is, so one is visible where it lands.
+
+ Closed shapes are created opaque and back-face culled, which is what lets meshes
+ occlude each other; `plane` and `quad` stay two-sided. **Create → Sun** joins
+ them: `Create → Light` gives a Point light at the entity's position, which lights
+ a mesh from inside it, and nothing in the picker offered the directional key light
+ shaded geometry actually wants.
+
+ `builtin:` was already the way a material names a stock shader and a tilemap layer
+ names the collision palette, spelled out separately in four places. It is now one
+ predicate the ref resolver, the loaders and the cook share — a built-in ref names
+ code, so it has to be recognized *before* anything tries to turn it into a path.
+
- **A sun can be aimed out of the plane.** A directional light's aim had two
components and a third the shader supplied as a constant, so every scene the
engine could express was lit from in front: the sun's elevation followed from
diff --git a/desktop/public/scenes/mesh-builtin.esscene b/desktop/public/scenes/mesh-builtin.esscene
new file mode 100644
index 000000000..8534f2f16
--- /dev/null
+++ b/desktop/public/scenes/mesh-builtin.esscene
@@ -0,0 +1,102 @@
+{
+ "version": 1,
+ "name": "MeshBuiltin",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": { "position": { "x": 0, "y": 0, "z": 300 } }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 150,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Cube",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": { "x": -75, "y": 0, "z": 0 },
+ "rotation": { "x": 0, "y": -0.3826834324, "z": 0, "w": 0.9238795325 }
+ }
+ },
+ {
+ "type": "Mesh2D",
+ "data": {
+ "mesh": "builtin:cube",
+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Sphere",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": { "position": { "x": 75, "y": 0, "z": 0 } }
+ },
+ {
+ "type": "Mesh2D",
+ "data": {
+ "mesh": "builtin:sphere",
+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },
+ "lit": true,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "Sun",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": { "position": { "x": 0, "y": 0, "z": 0 } }
+ },
+ {
+ "type": "Light2D",
+ "data": {
+ "type": 1,
+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },
+ "intensity": 1,
+ "direction": { "x": -0.4142135624, "y": 0 },
+ "directionZ": -1
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/desktop/src/components/icons.tsx b/desktop/src/components/icons.tsx
index f944b55f9..47aae5064 100644
--- a/desktop/src/components/icons.tsx
+++ b/desktop/src/components/icons.tsx
@@ -18,6 +18,11 @@ import {
Hexagon,
Link2,
MapPin,
+ Globe,
+ Pill,
+ Cylinder,
+ Cone,
+ Frame,
type LucideIcon,
} from 'lucide-react';
import type { NodeKind, AssetType } from '@/types';
@@ -82,3 +87,18 @@ export function ComponentIcon({ name, size = 14 }: { name: string; size?: number
const Glyph = componentGlyph(name);
return <Glyph size={size} strokeWidth={1.75} />;
}
+
+// Built-in mesh id → glyph, for the Create picker and the mesh asset slot.
+const PRIMITIVE_ICON: Record<string, LucideIcon> = {
+ cube: Box,
+ sphere: Globe,
+ capsule: Pill,
+ cylinder: Cylinder,
+ cone: Cone,
+ plane: Square,
+ quad: Frame,
+};
+
+export function primitiveGlyph(id: string): LucideIcon {
+ return PRIMITIVE_ICON[id] ?? Box;
+}
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index 00b070150..b341598c4 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -16,12 +16,12 @@
*/
import { projectPrefabSources, projectDesignSeed } from './projectSeams';
import type { LucideIcon } from 'lucide-react';
-import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText, AppWindow, TextCursorInput, Grid3x3, MapPin, Scan } from 'lucide-react';
-import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, applyThemeToWorld, type PrefabData } from 'esengine';
+import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText, AppWindow, TextCursorInput, Grid3x3, MapPin, Scan, Sun } from 'lucide-react';
+import { BUILTIN_MESH_TEMPLATES, BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, applyThemeToWorld, type PrefabData } from 'esengine';
import type { EntityId } from '@/types';
import { ContributionRegistry } from '@/contrib/ContributionRegistry';
import { componentByName, componentDefaults, readonlyFieldsFor, prettyLabel, componentCategory, userComponentNames } from './schema';
-import { componentGlyph } from '@/components/icons';
+import { componentGlyph, primitiveGlyph } from '@/components/icons';
import { SceneCommands } from './SceneCommands';
import { EngineHost } from './EngineHost';
@@ -244,6 +244,24 @@ const ANCHOR_SPECS: { comp: string; label: string; comps: CompSpec[] }[] = [
{ comp: 'AudioSource', label: 'Audio', comps: ['Transform', 'AudioSource'] },
];
+/**
+ * One Create source per built-in mesh. Whether the geometry is closed decides depth
+ * and back-face culling, and the template says which it is; `lit` follows the model
+ * import, where geometry carrying normals was authored to be shaded.
+ */
+function primitiveSources(): EntitySource[] {
+ return BUILTIN_MESH_TEMPLATES.map((tpl) => ({
+ id: `mesh:${tpl.id}`,
+ label: tpl.label,
+ category: componentCategory('Mesh2D'),
+ icon: primitiveGlyph(tpl.id),
+ keywords: ['3d', 'mesh', 'primitive', tpl.id],
+ build: () => preset(tpl.label, [['Transform', {}], ['Mesh2D', {
+ mesh: tpl.ref, lit: true, opaque: tpl.closed, cullBackfaces: tpl.closed,
+ }]]),
+ }));
+}
+
/** Auto-generate one source per anchor component; category + icon come from the
* component-metadata authority so a new anchor needs only a row in ANCHOR_SPECS. */
function anchorSources(): EntitySource[] {
@@ -260,6 +278,12 @@ function anchorSources(): EntitySource[] {
export const ENTITY_SOURCES: EntitySource[] = [
presetSource('empty', 'Empty', 'Basic', CircleDot, ['Transform']),
...anchorSources(),
+ ...primitiveSources(),
+ // A Light is a Point light at the entity's position, which is the 2D default and
+ // lights a mesh from inside it. A key light aimed into the screen is what shaded
+ // geometry needs, and nothing else in the picker offers one.
+ presetSource('sun', 'Sun', componentCategory('Light2D'), Sun,
+ [['Transform', {}], ['Light2D', { type: 1, direction: { x: 0.3, y: -0.5 }, directionZ: -0.8 }]]),
// Tilemap is asset-driven (it needs a tileset + orientation), so it can't build
// synchronously like an anchor — picking it opens the New-Tilemap dialog. Listed here
// anyway so the Create picker stays the one place every entity is born.
diff --git a/desktop/src/panels/inspector/controls.tsx b/desktop/src/panels/inspector/controls.tsx
index a20a88b26..301e13743 100644
--- a/desktop/src/panels/inspector/controls.tsx
+++ b/desktop/src/panels/inspector/controls.tsx
@@ -23,6 +23,7 @@ import { SceneModel } from '@/engine/SceneModel';
import { SceneStore } from '@/engine/SceneStore';
import { prettyLabel, hexToRgba, coerceEnumInput } from '@/engine/schema';
import { AssetRegistry } from '@/project/AssetRegistry';
+import { builtinAssetOption, builtinAssetOptions } from '@/project/builtinAssets';
import { revealAsset } from '@/project/assetReveal';
import { Toasts } from '@/store/Toasts';
import type { FieldUnit } from '@/store/fieldUnits';
@@ -1011,7 +1012,11 @@ export function AssetControl({
const box = useRef<HTMLDivElement>(null);
const pop = usePopover();
const [q, setQ] = useState('');
+ // A built-in binds like an asset but is not one: no file to reveal, and `assetInfo`
+ // answers about files, so a `builtin:` ref read as "None" without asking here too.
+ const builtin = builtinAssetOption(assetType, value);
const info = AssetRegistry.assetInfo(value);
+ const shownName = builtin?.label ?? info?.name ?? null;
// Handle-valued slots clear to 0; path-valued slots (spine skeleton/atlas)
// are string component fields, so "no asset" is the empty string.
const empty = assetType === 'spine-skeleton' || assetType === 'spine-atlas' ? '' : 0;
@@ -1051,15 +1056,15 @@ export function AssetControl({
close();
};
const ql = q.trim().toLowerCase();
- const assets = pop.isOpen
- ? AssetRegistry.listAssets(assetType).filter((a) => !ql || a.name.toLowerCase().includes(ql))
- : [];
+ const matches = (name: string): boolean => !ql || name.toLowerCase().includes(ql);
+ const builtins = pop.isOpen ? builtinAssetOptions(assetType).filter((o) => matches(o.label)) : [];
+ const assets = pop.isOpen ? AssetRegistry.listAssets(assetType).filter((a) => matches(a.name)) : [];
return (
<div
ref={box}
className={`assetref${over ? ' is-over' : ''}`}
- title={info?.path}
+ title={builtin?.description ?? info?.path}
onDragOver={(e) => {
e.preventDefault();
if (!over) setOver(true);
@@ -1083,14 +1088,14 @@ export function AssetControl({
)}
</span>
{/* Multi-select disagreement: "—", not the first entity's asset. */}
- <span className={`an${mixed ? ' dd-none' : ''}`}>{mixed ? '—' : info ? info.name : t('det.none')}</span>
+ <span className={`an${mixed ? ' dd-none' : ''}`}>{mixed ? '—' : shownName ?? t('det.none')}</span>
</button>
{!readOnly && (
<button type="button" className="pk" title={t('det.pickAsset')} onMouseDown={(e) => e.stopPropagation()} onClick={openPick}>
<Search size={11} strokeWidth={2} />
</button>
)}
- {!readOnly && info && (
+ {!readOnly && shownName && (
<button
type="button"
className="pk"
@@ -1108,12 +1113,20 @@ export function AssetControl({
<Popover anchor={pop.anchor} width={Math.max(pop.anchor.width, 240)} onClose={close}>
<SearchField flush className="dd-search" iconSize={12} autoFocus placeholder={t('det.searchAssets')} value={q} onChange={setQ} />
<div className="asset-grid">
- <button type="button" className={`asset-opt${!info ? ' on' : ''}`} onClick={() => pick(empty)}>
+ <button type="button" className={`asset-opt${!shownName ? ' on' : ''}`} onClick={() => pick(empty)}>
<span className="th">
<X size={13} strokeWidth={2} />
</span>
<span className="an">{t('det.none')}</span>
</button>
+ {builtins.map((o) => (
+ <button key={o.ref} type="button" className={`asset-opt${o.ref === value ? ' on' : ''}`} title={o.description} onClick={() => pick(o.ref)}>
+ <span className="th">
+ <o.icon size={18} strokeWidth={1.5} />
+ </span>
+ <span className="an">{o.label}</span>
+ </button>
+ ))}
{assets.map((a) => (
<button key={a.ref} type="button" className={`asset-opt${a.ref === value ? ' on' : ''}`} title={a.path} onClick={() => pick(a.ref)}>
<span className="th">
@@ -1126,7 +1139,8 @@ export function AssetControl({
<span className="an">{a.name}</span>
</button>
))}
- {assets.length === 0 && <div className="empty-line empty-line--sm">{t('det.noMatchingAssets')}</div>}
+ {assets.length === 0 && builtins.length === 0
+ && <div className="empty-line empty-line--sm">{t('det.noMatchingAssets')}</div>}
</div>
</Popover>
)}
diff --git a/desktop/src/project/AssetRegistry.ts b/desktop/src/project/AssetRegistry.ts
index 418ad978e..34eebc72d 100644
--- a/desktop/src/project/AssetRegistry.ts
+++ b/desktop/src/project/AssetRegistry.ts
@@ -9,7 +9,7 @@
* belong to ProjectStore, which feeds results in through {@link rebuild}. The
* dependency runs one way, so a query never reaches back for a project.
*/
-import { Assets, getEditorType, textureImportSettingsFrom, setTextureParams, setTextureSliceBorder, TextureFilter, TextureWrap } from 'esengine';
+import { Assets, getEditorType, isBuiltinMeshRef, textureImportSettingsFrom, setTextureParams, setTextureSliceBorder, TextureFilter, TextureWrap } from 'esengine';
import { EngineHost } from '@/engine/EngineHost';
import { assetTypeOf } from '@/project/assetMeta';
import { ASSET_TYPES, assetTypeDef } from '@/project/assetTypes';
@@ -252,6 +252,7 @@ class AssetRegistryImpl {
* from "registered but its load failed", which a caller cannot tell apart from
* a null path. */
assetRefProblem(ref: string): string | null {
+ if (isBuiltinMeshRef(ref)) return null;
const uuid = refUuid(ref);
const path = uuid !== null ? (this.uuidToPath.get(uuid) ?? null) : ref;
if (path === null) return 'unresolved: no asset with this uuid in the registry';
diff --git a/desktop/src/project/builtinAssets.ts b/desktop/src/project/builtinAssets.ts
new file mode 100644
index 000000000..55f2dc794
--- /dev/null
+++ b/desktop/src/project/builtinAssets.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file builtinAssets.ts — what an asset slot can be bound to that is not a file.
+ * The AssetRegistry answers for files; a `builtin:` ref has none, so it
+ * answers here, and an asset control asks both without knowing either list.
+ */
+import { BUILTIN_MESH_TEMPLATES } from 'esengine';
+import type { LucideIcon } from 'lucide-react';
+import { primitiveGlyph } from '@/components/icons';
+
+/** One pickable built-in, shaped like the picker's project-asset entries. */
+export interface BuiltinAssetOption {
+ ref: string;
+ label: string;
+ description: string;
+ icon: LucideIcon;
+}
+
+const OPTIONS_BY_SLOT: Record<string, readonly BuiltinAssetOption[]> = {
+ mesh: BUILTIN_MESH_TEMPLATES.map((tpl) => ({
+ ref: tpl.ref, label: tpl.label, description: tpl.description, icon: primitiveGlyph(tpl.id),
+ })),
+};
+
+/** Everything built in that an `assetType` slot accepts, in menu order. */
+export function builtinAssetOptions(slot: string | undefined): readonly BuiltinAssetOption[] {
+ return (slot && OPTIONS_BY_SLOT[slot]) || [];
+}
+
+/** The option a bound value names, or null when it names a file (or nothing). */
+export function builtinAssetOption(slot: string | undefined, value: unknown): BuiltinAssetOption | null {
+ if (typeof value !== 'string' || !value) return null;
+ return builtinAssetOptions(slot).find((o) => o.ref === value) ?? null;
+}
diff --git a/desktop/tests/document-ref-cook-deps.test.ts b/desktop/tests/document-ref-cook-deps.test.ts
index d11d22fe0..936238864 100644
--- a/desktop/tests/document-ref-cook-deps.test.ts
+++ b/desktop/tests/document-ref-cook-deps.test.ts
@@ -148,6 +148,38 @@ describe('assets named only inside another document are cooked', () => {
expect(res.warnings.filter((w) => /does not carry/.test(w))).toEqual([]);
});
+ // The mirror image: a `builtin:` ref names code, so the package is right not to
+ // carry it. It has to reach the runtime spelled as authored — rewritten toward a
+ // path, it would resolve to a file nothing ever staged.
+ it('leaves a built-in mesh ref alone rather than calling it dangling', async () => {
+ const lone = mkdtempSync(path.join(tmpdir(), 'estella-builtin-'));
+ const prev = root;
+ root = lone;
+ try {
+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, JSON.stringify({
+ version: '1.0', name: 'm',
+ entities: [{
+ id: 1, name: 'Cube', parent: null, children: [],
+ components: [{ type: 'Mesh2D', data: { mesh: 'builtin:cube', lit: true } }],
+ }],
+ }));
+ const res = await cookAssets(lone, {
+ entryScenes: ['assets/scenes/main.esscene'], outDir: 'build', contentAddressed: true,
+ });
+ expect(res.ok).toBe(true);
+ expect(res.warnings.filter((w) => /does not carry/.test(w))).toEqual([]);
+ const manifest = JSON.parse(readFileSync(res.manifestPath!, 'utf8')) as {
+ entries: Array<{ uuid: string; path: string }>;
+ };
+ const staged = readFileSync(
+ path.join(res.outDir, manifest.entries.find((e) => e.uuid === SCENE)!.path), 'utf8');
+ expect(staged).toContain('builtin:cube');
+ } finally {
+ root = prev;
+ rmSync(lone, { recursive: true, force: true });
+ }
+ });
+
// The backstop for the type nobody has wired up yet: whatever the document is,
// a path it names that the package does not carry is a 404 waiting to happen.
it('reports a staged document that names an asset the package lacks', async () => {
diff --git a/docs/astro/src/content/docs/assets/models.mdx b/docs/astro/src/content/docs/assets/models.mdx
index 1703e2081..15b62f68c 100644
--- a/docs/astro/src/content/docs/assets/models.mdx
+++ b/docs/astro/src/content/docs/assets/models.mdx
@@ -1,6 +1,6 @@
---
title: Models
-description: Importing glTF/GLB and FBX — what the import writes, how a model reaches a scene, the Scale setting, re-importing, which material channels become an .esmaterial, Draco and meshopt, and what is reported rather than imported.
+description: Built-in primitives, importing glTF/GLB and FBX — what the import writes, how a model reaches a scene, the Scale setting, re-importing, which material channels become an .esmaterial, Draco and meshopt, and what is reported rather than imported.
---
import { Aside } from '@astrojs/starlight/components';
@@ -16,6 +16,43 @@ That import is the subject of this page. For the component that draws the result
[the component reference](/docs/reference/components/graphics/); for materials in general see
[Materials](/docs/graphics/materials/).
+## Built-in primitives
+
+Seven shapes need no import and no file. **Create → Cube** (or Sphere, Capsule, Cylinder,
+Cone, Plane, Quad) makes an entity whose `Mesh2D.mesh` holds a `builtin:` ref, and the
+same seven appear at the top of the picker on any `Mesh2D.mesh` field.
+
+| Ref | Shape |
+|---|---|
+| `builtin:cube` | 100-unit box, one flat normal per face |
+| `builtin:sphere` | 100-unit sphere, smooth normals |
+| `builtin:capsule` | 100 units tall — radius 25, 50 of cylinder between the caps, the shape `CapsuleCollider3D` describes |
+| `builtin:cylinder` | 100-unit upright cylinder, flat caps |
+| `builtin:cone` | 100-unit cone standing on its base |
+| `builtin:plane` | 100-unit square in XZ, facing up — a ground |
+| `builtin:quad` | 100-unit square in XY, facing the camera — a backdrop |
+
+They are built in code at load time, so they cost no bytes in a package and a scene that
+references one carries no dependency. All seven are the same size as a new `ShapeRenderer`,
+so one dropped into a scene is visible without being scaled first; give it the size you
+want through the Transform, the way an imported model gets one.
+
+The five closed shapes are created **opaque and back-face culled**, which is what lets them
+hide each other instead of blending in submission order; `plane` and `quad` are flat, so
+they stay two-sided and are still there when seen from behind.
+
+<Aside type="caution" title="A lit mesh needs a light">
+Primitives are created `lit`, like imported geometry carrying normals. Lighting is
+multiplicative and starts at zero, so a scene with no `Light2D` in it draws them black —
+**Create → Sun** adds the directional key light a shaded scene wants. Clearing `lit` gives
+the flat, unshaded look instead.
+</Aside>
+
+A primitive is 100 units **deep** as well as wide, which a camera placed for flat content
+is not far enough back for: leave it at the 2D default and the near half of every solid
+falls in front of the near plane. Put the scene camera a few hundred units away, as the
+3D examples do.
+
## Importing a model
Three doors, one import:
diff --git a/docs/astro/src/content/docs/zh-cn/assets/models.mdx b/docs/astro/src/content/docs/zh-cn/assets/models.mdx
index 2c9438996..aa07a19aa 100644
--- a/docs/astro/src/content/docs/zh-cn/assets/models.mdx
+++ b/docs/astro/src/content/docs/zh-cn/assets/models.mdx
@@ -1,6 +1,6 @@
---
title: 模型
-description: glTF/GLB 与 FBX 导入 —— 导入写出什么、模型怎么进场景、Scale 设置、重新导入、哪些材质通道会变成 .esmaterial、Draco 与 meshopt、以及哪些东西只报告不导入。
+description: 内置图元、glTF/GLB 与 FBX 导入 —— 导入写出什么、模型怎么进场景、Scale 设置、重新导入、哪些材质通道会变成 .esmaterial、Draco 与 meshopt、以及哪些东西只报告不导入。
---
import { Aside } from '@astrojs/starlight/components';
@@ -13,6 +13,38 @@ import { Aside } from '@astrojs/starlight/components';
本页讲的就是这次导入。画出结果的那个组件见[组件参考](/docs/zh-cn/reference/components/graphics/);
材质整体见[材质](/docs/zh-cn/graphics/materials/)。
+## 内置图元
+
+有七个形状不需要导入、也不需要文件。**Create → Cube**(以及 Sphere、Capsule、Cylinder、
+Cone、Plane、Quad)建出的实体,其 `Mesh2D.mesh` 里放的是一个 `builtin:` 引用;同样这七个
+也排在任何 `Mesh2D.mesh` 字段选择器的最前面。
+
+| 引用 | 形状 |
+|---|---|
+| `builtin:cube` | 100 单位的正方体,每个面一个平法线 |
+| `builtin:sphere` | 100 单位的球,平滑法线 |
+| `builtin:capsule` | 高 100 单位 —— 半径 25、两端胶囊之间 50 的圆柱,正是 `CapsuleCollider3D` 描述的形状 |
+| `builtin:cylinder` | 100 单位的竖直圆柱,平顶平底 |
+| `builtin:cone` | 100 单位的圆锥,立在底面上 |
+| `builtin:plane` | XZ 平面上 100 单位的方块,朝上 —— 一块地面 |
+| `builtin:quad` | XY 平面上 100 单位的方块,正对相机 —— 一块背板 |
+
+它们在加载时由代码生成,所以在包里不占任何字节,引用了它的场景也不因此多出依赖。七个都
+和新建的 `ShapeRenderer` 一样大,所以往场景里放一个不用先缩放就看得见;要多大,通过
+Transform 给,和导入的模型一样。
+
+五个封闭形状建出来时是**不透明 + 背面剔除**的——这才让它们互相遮挡,而不是按提交顺序混合;
+`plane` 和 `quad` 是平的,所以保持双面,从背后看也还在。
+
+<Aside type="caution" title="被照亮的 mesh 需要一盏灯">
+图元建出来时是 `lit` 的,和带法线的导入几何一样。光照是乘性的、从零起算,所以场景里没有
+`Light2D` 时它们画出来是黑的 —— **Create → Sun** 会加上一盏有阴影场景想要的平行主光。
+把 `lit` 关掉则得到不受光的平涂外观。
+</Aside>
+
+图元不只是宽 100 单位,**厚**也是 100 单位,而按平面内容摆的相机离得不够远:沿用 2D 的默认
+位置,每个实体的前半截都落在近平面之前。像 3D 示例那样,把场景相机放到几百单位之外。
+
## 导入一个模型
三个入口,同一次导入:
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 04c3e00de..3a348d845 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 73,
- "experimental": 1564,
+ "experimental": 1568,
"deprecated": 3
},
- "total": 1750,
+ "total": 1754,
"subsystems": [
{
"id": "ecs",
diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.ts
index 810636a48..b6135e871 100644
--- a/pipeline/src/assets/cookAssets.ts
+++ b/pipeline/src/assets/cookAssets.ts
@@ -30,7 +30,7 @@ import { readTextureCookSettings } from '../project/importSettings';
// no hand-mirrored copy — so the cook and the runtime agree by construction.
import { contentHashHex } from '../../../sdk/src/asset/contentHash';
import { getAssetTypeEntry } from '../../../sdk/src/assetTypes';
-import { resolveRelativePath, resolveDocumentRef } from '../../../sdk/src/asset/documentRef';
+import { isBuiltinAssetRef, resolveRelativePath, resolveDocumentRef } from '../../../sdk/src/asset/documentRef';
// Single source for the folder→delivery-group model, shared with the editor Play
// realm (sdk/src/asset/assetGroups.ts) so cook and editor never disagree.
import { resolveAssetGroup, resolveAtlas, type AssetGroupsConfig } from '../../../sdk/src/asset/assetGroups';
@@ -190,7 +190,7 @@ function rewriteMaterialRefs(
* anything naming no asset pass through.
*/
function logicalRef(ref: unknown, docPath: string, byPath: Map<string, AssetEntry>): unknown {
- if (typeof ref !== 'string' || ref.startsWith('@uuid:') || ref.startsWith('builtin:') || ref.includes('://')) return ref;
+ if (typeof ref !== 'string' || ref.startsWith('@uuid:') || isBuiltinAssetRef(ref) || ref.includes('://')) return ref;
const norm = ref.replace(/^\.\//, '').replace(/^\//, '');
if (byPath.has(norm)) return ref;
const proj = resolveRelativePath(docPath, ref); // collapses ./ and ../
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2ec4092a8..bdfa7661e 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 66 beta · 1450 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1454 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1055,6 +1055,11 @@ type: "audio"
(...bindings: Binding[]) => ActionDef
```
+## BUILTIN_MESH_TEMPLATES — const @experimental
+```
+readonly BuiltinMeshTemplate[]
+```
+
## BUILTIN_SHADER_TEMPLATES — const @experimental
```
readonly BuiltinShaderTemplate[]
@@ -1361,6 +1366,16 @@ skeletalFields: SkeletalFieldMeta | undefined
transient: boolean
```
+## BuiltinMeshTemplate — interface @experimental
+```
+build: () => MeshData
+closed: boolean
+description: string
+id: string
+label: string
+ref: string
+```
+
## BuiltinShaderTemplate — interface @experimental
```
defaults: Record<string, unknown>
@@ -9363,6 +9378,11 @@ BtPlugin
(asset: TilesetAsset): WangIndices
```
+## builtinMeshTemplate — function @experimental
+```
+(ref: string): BuiltinMeshTemplate | undefined
+```
+
## builtinShaderTemplate — function @experimental
```
(id: string): BuiltinShaderTemplate | undefined
@@ -10428,6 +10448,11 @@ InputRouter
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
```
+## isBuiltinMeshRef — function @experimental
+```
+(ref: string): boolean
+```
+
## isCollisionPaletteRef — function @experimental
```
(refs: readonly string[]): boolean
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index c562c73be..e8b636886 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 71 beta · 1469 experimental · 3 deprecated
+Symbols: 113 public · 71 beta · 1473 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -1055,6 +1055,11 @@ type: "audio"
(...bindings: Binding[]) => ActionDef
```
+## BUILTIN_MESH_TEMPLATES — const @experimental
+```
+readonly BuiltinMeshTemplate[]
+```
+
## BUILTIN_SHADER_TEMPLATES — const @experimental
```
readonly BuiltinShaderTemplate[]
@@ -1361,6 +1366,16 @@ skeletalFields: SkeletalFieldMeta | undefined
transient: boolean
```
+## BuiltinMeshTemplate — interface @experimental
+```
+build: () => MeshData
+closed: boolean
+description: string
+id: string
+label: string
+ref: string
+```
+
## BuiltinShaderTemplate — interface @experimental
```
defaults: Record<string, unknown>
@@ -9571,6 +9586,11 @@ BtPlugin
(asset: TilesetAsset): WangIndices
```
+## builtinMeshTemplate — function @experimental
+```
+(ref: string): BuiltinMeshTemplate | undefined
+```
+
## builtinShaderTemplate — function @experimental
```
(id: string): BuiltinShaderTemplate | undefined
@@ -10671,6 +10691,11 @@ InputRouter
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
```
+## isBuiltinMeshRef — function @experimental
+```
+(ref: string): boolean
+```
+
## isCollisionPaletteRef — function @experimental
```
(refs: readonly string[]): boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index e860ac747..c0600dbfd 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 68 beta · 1449 experimental · 3 deprecated
+Symbols: 113 public · 68 beta · 1453 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1050,6 +1050,11 @@ type: "audio"
(...bindings: Binding[]) => ActionDef
```
+## BUILTIN_MESH_TEMPLATES — const @experimental
+```
+readonly BuiltinMeshTemplate[]
+```
+
## BUILTIN_SHADER_TEMPLATES — const @experimental
```
readonly BuiltinShaderTemplate[]
@@ -1356,6 +1361,16 @@ skeletalFields: SkeletalFieldMeta | undefined
transient: boolean
```
+## BuiltinMeshTemplate — interface @experimental
+```
+build: () => MeshData
+closed: boolean
+description: string
+id: string
+label: string
+ref: string
+```
+
## BuiltinShaderTemplate — interface @experimental
```
defaults: Record<string, unknown>
@@ -9358,6 +9373,11 @@ BtPlugin
(asset: TilesetAsset): WangIndices
```
+## builtinMeshTemplate — function @experimental
+```
+(ref: string): BuiltinMeshTemplate | undefined
+```
+
## builtinShaderTemplate — function @experimental
```
(id: string): BuiltinShaderTemplate | undefined
@@ -10423,6 +10443,11 @@ InputRouter
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
```
+## isBuiltinMeshRef — function @experimental
+```
+(ref: string): boolean
+```
+
## isCollisionPaletteRef — function @experimental
```
(refs: readonly string[]): boolean
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 7fe936285..aecff674e 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 66 beta · 1470 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1474 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1050,6 +1050,11 @@ type: "audio"
(...bindings: Binding[]) => ActionDef
```
+## BUILTIN_MESH_TEMPLATES — const @experimental
+```
+readonly BuiltinMeshTemplate[]
+```
+
## BUILTIN_SHADER_TEMPLATES — const @experimental
```
readonly BuiltinShaderTemplate[]
@@ -1356,6 +1361,16 @@ skeletalFields: SkeletalFieldMeta | undefined
transient: boolean
```
+## BuiltinMeshTemplate — interface @experimental
+```
+build: () => MeshData
+closed: boolean
+description: string
+id: string
+label: string
+ref: string
+```
+
## BuiltinShaderTemplate — interface @experimental
```
defaults: Record<string, unknown>
@@ -9603,6 +9618,11 @@ BtPlugin
(asset: TilesetAsset): WangIndices
```
+## builtinMeshTemplate — function @experimental
+```
+(ref: string): BuiltinMeshTemplate | undefined
+```
+
## builtinShaderTemplate — function @experimental
```
(id: string): BuiltinShaderTemplate | undefined
@@ -10683,6 +10703,11 @@ InputRouter
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
```
+## isBuiltinMeshRef — function @experimental
+```
+(ref: string): boolean
+```
+
## isCollisionPaletteRef — function @experimental
```
(refs: readonly string[]): boolean
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 7766edba7..9a6bbdd05 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 66 beta · 1460 experimental · 3 deprecated
+Symbols: 113 public · 66 beta · 1464 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -1050,6 +1050,11 @@ type: "audio"
(...bindings: Binding[]) => ActionDef
```
+## BUILTIN_MESH_TEMPLATES — const @experimental
+```
+readonly BuiltinMeshTemplate[]
+```
+
## BUILTIN_SHADER_TEMPLATES — const @experimental
```
readonly BuiltinShaderTemplate[]
@@ -1356,6 +1361,16 @@ skeletalFields: SkeletalFieldMeta | undefined
transient: boolean
```
+## BuiltinMeshTemplate — interface @experimental
+```
+build: () => MeshData
+closed: boolean
+description: string
+id: string
+label: string
+ref: string
+```
+
## BuiltinShaderTemplate — interface @experimental
```
defaults: Record<string, unknown>
@@ -9385,6 +9400,11 @@ BtPlugin
(asset: TilesetAsset): WangIndices
```
+## builtinMeshTemplate — function @experimental
+```
+(ref: string): BuiltinMeshTemplate | undefined
+```
+
## builtinShaderTemplate — function @experimental
```
(id: string): BuiltinShaderTemplate | undefined
@@ -10455,6 +10475,11 @@ InputRouter
(comp: AnyComponentDef): comp is BuiltinComponentDef<any>
```
+## isBuiltinMeshRef — function @experimental
+```
+(ref: string): boolean
+```
+
## isCollisionPaletteRef — function @experimental
```
(refs: readonly string[]): boolean
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 2f94f564f..a35836b41 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -22,6 +22,7 @@ import { AssetRefLedger } from './AssetRefLedger';
import { SpineAssetLoader } from './loaders/SpineAssetLoader';
import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';
import { MeshAssetLoader } from './loaders/MeshAssetLoader';
+import { isBuiltinMeshRef } from './builtinMeshes';
import { EnvironmentAssetLoader } from './loaders/EnvironmentAssetLoader';
import { FontAssetLoader } from './loaders/FontAssetLoader';
import { AudioAssetLoader } from './loaders/AudioAssetLoader';
@@ -1636,6 +1637,7 @@ export class Assets {
* unchanged — legacy path-only scenes keep working.
*/
resolveRef(ref: string): string | null {
+ if (isBuiltinMeshRef(ref)) return ref;
if (this.assetRefResolver_) return this.assetRefResolver_(ref);
return ref;
}
@@ -1665,6 +1667,10 @@ export class Assets {
* time — textures silently rendered white. This helper closes that gap.
*/
private resolveLoadPath_(ref: string): string {
+ // Built-in geometry names code, not a file. Every realm's resolver turns a
+ // non-URL ref into one (the play realm prefixes an origin), so a ref that
+ // has nothing to resolve has to say so before resolution, not after.
+ if (isBuiltinMeshRef(ref)) return ref;
// A `remote`-group asset (per the active addressable manifest) resolves to
// its CDN url — so a scene @uuid ref to a remote asset loads from, and
// hot-updates with, the CDN, not just loadGroup'd DLC assets. Gated on a
diff --git a/sdk/src/asset/builtinMeshes.ts b/sdk/src/asset/builtinMeshes.ts
new file mode 100644
index 000000000..57c14399e
--- /dev/null
+++ b/sdk/src/asset/builtinMeshes.ts
@@ -0,0 +1,284 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file builtinMeshes.ts — stock geometry a project references without owning a file.
+ * A `builtin:<id>` mesh ref names one of these; it is built here, not fetched.
+ */
+
+import { BUILTIN_REF_PREFIX, builtinRefId } from './documentRef';
+import { MeshChannel, MeshChannelType, packChannels, type MeshData } from './meshFormat';
+
+/**
+ * The size every primitive is built at, matching `ShapeRenderer.size` — the other
+ * renderable born from a menu rather than an asset. A cube is 100 units on a side,
+ * so one dropped into a default scene is visible without being scaled first.
+ */
+const UNIT = 100;
+
+const SECTORS = 32;
+const STACKS = 16;
+
+export interface BuiltinMeshTemplate {
+ id: string;
+ /** The ref an authored field carries. */
+ ref: string;
+ /** Menu / picker label. */
+ label: string;
+ description: string;
+ /**
+ * Whether the surface encloses a volume. A closed one is drawn opaque and
+ * back-face culled — it can hide what is behind it and has an inside nobody
+ * sees; a flat one stays two-sided, or a ground plane disappears from below.
+ */
+ closed: boolean;
+ build(): MeshData;
+}
+
+interface Builder {
+ pos: number[];
+ uv: number[];
+ nrm: number[];
+ idx: number[];
+}
+
+/** One lathe ring: a circle at `y`, and the normal its vertices carry. */
+interface Ring {
+ y: number;
+ radius: number;
+ /** Radial component of the surface normal. */
+ nr: number;
+ /** Axial component of the surface normal. */
+ ny: number;
+ v: number;
+}
+
+const newBuilder = (): Builder => ({ pos: [], uv: [], nrm: [], idx: [] });
+
+function vertex(b: Builder, p: readonly number[], u: number, v: number, n: readonly number[]): number {
+ const at = b.pos.length / 3;
+ b.pos.push(p[0]!, p[1]!, p[2]!);
+ b.uv.push(u, v);
+ b.nrm.push(n[0]!, n[1]!, n[2]!);
+ return at;
+}
+
+function tri(b: Builder, a: number, c: number, d: number): void {
+ b.idx.push(a, c, d);
+}
+
+/** A flat quad from four corners wound counter-clockwise seen from `n`. */
+function quadFace(b: Builder, corners: readonly (readonly number[])[], n: readonly number[]): void {
+ const a = vertex(b, corners[0]!, 0, 0, n);
+ const c = vertex(b, corners[1]!, 1, 0, n);
+ const d = vertex(b, corners[2]!, 1, 1, n);
+ const e = vertex(b, corners[3]!, 0, 1, n);
+ tri(b, a, c, d);
+ tri(b, a, d, e);
+}
+
+/**
+ * Revolve `rings` around the Y axis and connect consecutive ones. Every curved
+ * surface here is this: a sphere is rings of shrinking radius, a cylinder is two
+ * of equal radius, a cone is one of radius zero above one that is not.
+ */
+function lathe(b: Builder, rings: readonly Ring[], sectors: number): void {
+ const base = b.pos.length / 3;
+ for (const ring of rings) {
+ for (let j = 0; j <= sectors; j++) {
+ const theta = (j / sectors) * Math.PI * 2;
+ const s = Math.sin(theta);
+ const c = Math.cos(theta);
+ const nx = s * ring.nr;
+ const nz = c * ring.nr;
+ const len = Math.hypot(nx, ring.ny, nz) || 1;
+ vertex(b, [s * ring.radius, ring.y, c * ring.radius], j / sectors, ring.v,
+ [nx / len, ring.ny / len, nz / len]);
+ }
+ }
+ const row = sectors + 1;
+ for (let i = 0; i < rings.length - 1; i++) {
+ const upper = rings[i]!;
+ const lower = rings[i + 1]!;
+ for (let j = 0; j < sectors; j++) {
+ const a = base + i * row + j;
+ const d = a + row;
+ if (upper.radius > 0) tri(b, a, d, a + 1);
+ if (lower.radius > 0) tri(b, a + 1, d, d + 1);
+ }
+ }
+}
+
+/** A flat disc at `y` facing `sign * Y`. */
+function disc(b: Builder, y: number, radius: number, sign: number, sectors: number): void {
+ const n = [0, sign, 0];
+ const center = vertex(b, [0, y, 0], 0.5, 0.5, n);
+ const rim: number[] = [];
+ for (let j = 0; j <= sectors; j++) {
+ const theta = (j / sectors) * Math.PI * 2;
+ const s = Math.sin(theta);
+ const c = Math.cos(theta);
+ rim.push(vertex(b, [s * radius, y, c * radius], 0.5 + s * 0.5, 0.5 + c * 0.5, n));
+ }
+ for (let j = 0; j < sectors; j++) {
+ if (sign > 0) tri(b, center, rim[j]!, rim[j + 1]!);
+ else tri(b, center, rim[j + 1]!, rim[j]!);
+ }
+}
+
+/** Rings tracing a hemisphere from `phiFrom` to `phiTo`, centred at `centerY`. */
+function capRings(centerY: number, radius: number, phiFrom: number, phiTo: number,
+ stacks: number, vFrom: number, vTo: number): Ring[] {
+ const out: Ring[] = [];
+ for (let i = 0; i <= stacks; i++) {
+ const t = i / stacks;
+ const phi = phiFrom + (phiTo - phiFrom) * t;
+ out.push({
+ y: centerY + Math.cos(phi) * radius,
+ radius: Math.sin(phi) * radius,
+ nr: Math.sin(phi),
+ ny: Math.cos(phi),
+ v: vFrom + (vTo - vFrom) * t,
+ });
+ }
+ return out;
+}
+
+function box(sx: number, sy: number, sz: number): Builder {
+ const b = newBuilder();
+ const x = sx / 2, y = sy / 2, z = sz / 2;
+ quadFace(b, [[-x, -y, z], [x, -y, z], [x, y, z], [-x, y, z]], [0, 0, 1]);
+ quadFace(b, [[x, -y, -z], [-x, -y, -z], [-x, y, -z], [x, y, -z]], [0, 0, -1]);
+ quadFace(b, [[x, -y, z], [x, -y, -z], [x, y, -z], [x, y, z]], [1, 0, 0]);
+ quadFace(b, [[-x, -y, -z], [-x, -y, z], [-x, y, z], [-x, y, -z]], [-1, 0, 0]);
+ quadFace(b, [[-x, y, z], [x, y, z], [x, y, -z], [-x, y, -z]], [0, 1, 0]);
+ quadFace(b, [[-x, -y, -z], [x, -y, -z], [x, -y, z], [-x, -y, z]], [0, -1, 0]);
+ return b;
+}
+
+function sphere(radius: number): Builder {
+ const b = newBuilder();
+ lathe(b, capRings(0, radius, 0, Math.PI, STACKS, 0, 1), SECTORS);
+ return b;
+}
+
+function cylinder(radius: number, height: number): Builder {
+ const b = newBuilder();
+ const h = height / 2;
+ lathe(b, [{ y: h, radius, nr: 1, ny: 0, v: 0 }, { y: -h, radius, nr: 1, ny: 0, v: 1 }], SECTORS);
+ disc(b, h, radius, 1, SECTORS);
+ disc(b, -h, radius, -1, SECTORS);
+ return b;
+}
+
+function cone(radius: number, height: number): Builder {
+ const b = newBuilder();
+ const h = height / 2;
+ const slant = Math.hypot(radius, height) || 1;
+ const nr = height / slant;
+ const ny = radius / slant;
+ lathe(b, [{ y: h, radius: 0, nr, ny, v: 0 }, { y: -h, radius, nr, ny, v: 1 }], SECTORS);
+ disc(b, -h, radius, -1, SECTORS);
+ return b;
+}
+
+/** Total height is `2*radius + cylinderHeight`, the shape CapsuleCollider3D describes. */
+function capsule(radius: number, cylinderHeight: number): Builder {
+ const b = newBuilder();
+ const h = cylinderHeight / 2;
+ const stacks = Math.max(2, STACKS / 2);
+ lathe(b, [
+ ...capRings(h, radius, 0, Math.PI / 2, stacks, 0, 0.3),
+ ...capRings(-h, radius, Math.PI / 2, Math.PI, stacks, 0.7, 1),
+ ], SECTORS);
+ return b;
+}
+
+function plane(size: number): Builder {
+ const b = newBuilder();
+ const h = size / 2;
+ quadFace(b, [[-h, 0, h], [h, 0, h], [h, 0, -h], [-h, 0, -h]], [0, 1, 0]);
+ return b;
+}
+
+function quad(size: number): Builder {
+ const b = newBuilder();
+ const h = size / 2;
+ quadFace(b, [[-h, -h, 0], [h, -h, 0], [h, h, 0], [-h, h, 0]], [0, 0, 1]);
+ return b;
+}
+
+/**
+ * Pack a builder into the channel layout the model import writes, so built-in and
+ * imported geometry reach the renderer as the same kind of thing.
+ */
+function toMeshData(b: Builder): MeshData {
+ const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32 },
+ ]);
+ const vertexCount = b.pos.length / 3;
+ const vertices = new Uint8Array(vertexCount * vertexStride);
+ const view = new DataView(vertices.buffer);
+ const posAt = channels[0]!.offset;
+ const uvAt = channels[1]!.offset;
+ const colorAt = channels[2]!.offset;
+ const normalAt = channels[3]!.offset;
+ const min: [number, number, number] = [Infinity, Infinity, Infinity];
+ const max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
+
+ for (let i = 0; i < vertexCount; i++) {
+ const at = i * vertexStride;
+ for (let k = 0; k < 3; k++) {
+ const value = b.pos[i * 3 + k]!;
+ view.setFloat32(at + posAt + k * 4, value, true);
+ view.setFloat32(at + normalAt + k * 4, b.nrm[i * 3 + k]!, true);
+ if (value < min[k]!) min[k] = value;
+ if (value > max[k]!) max[k] = value;
+ }
+ view.setFloat32(at + uvAt, b.uv[i * 2]!, true);
+ view.setFloat32(at + uvAt + 4, b.uv[i * 2 + 1]!, true);
+ view.setUint32(at + colorAt, 0xffffffff, true);
+ }
+
+ return {
+ channels, vertexStride, vertexCount, vertices,
+ indices: new Uint32Array(b.idx),
+ aabbMin: min, aabbMax: max,
+ };
+}
+
+const template = (
+ id: string, label: string, description: string, closed: boolean, build: () => Builder,
+): BuiltinMeshTemplate =>
+ ({ id, ref: BUILTIN_REF_PREFIX + id, label, description, closed, build: () => toMeshData(build()) });
+
+export const BUILTIN_MESH_TEMPLATES: readonly BuiltinMeshTemplate[] = [
+ template('cube', 'Cube', `A ${UNIT}-unit box, one flat normal per face.`, true,
+ () => box(UNIT, UNIT, UNIT)),
+ template('sphere', 'Sphere', `A ${UNIT}-unit sphere with smooth normals.`, true,
+ () => sphere(UNIT / 2)),
+ template('capsule', 'Capsule', `A ${UNIT}-unit upright capsule — what CapsuleCollider3D describes.`, true,
+ () => capsule(UNIT / 4, UNIT / 2)),
+ template('cylinder', 'Cylinder', `A ${UNIT}-unit upright cylinder with flat caps.`, true,
+ () => cylinder(UNIT / 2, UNIT)),
+ template('cone', 'Cone', `A ${UNIT}-unit cone standing on its base.`, true,
+ () => cone(UNIT / 2, UNIT)),
+ template('plane', 'Plane', `A ${UNIT}-unit ground square in XZ, facing up.`, false,
+ () => plane(UNIT)),
+ template('quad', 'Quad', `A ${UNIT}-unit square in XY, facing the camera.`, false,
+ () => quad(UNIT)),
+];
+
+const byId = new Map(BUILTIN_MESH_TEMPLATES.map((t) => [t.id, t]));
+
+/** The template a ref (or a bare id) names, or undefined for anything else. */
+export function builtinMeshTemplate(ref: string): BuiltinMeshTemplate | undefined {
+ return byId.get(builtinRefId(ref) ?? ref);
+}
+
+/** Whether `ref` names built-in geometry rather than a project file. */
+export function isBuiltinMeshRef(ref: string): boolean {
+ return builtinRefId(ref) !== null && builtinMeshTemplate(ref) !== undefined;
+}
diff --git a/sdk/src/asset/documentRef.ts b/sdk/src/asset/documentRef.ts
index 01a9e72ea..04b968e8b 100644
--- a/sdk/src/asset/documentRef.ts
+++ b/sdk/src/asset/documentRef.ts
@@ -32,6 +32,27 @@ export function isLogicalAssetRef(ref: string): boolean {
return ref.startsWith('/') || ref.startsWith('assets/');
}
+/**
+ * Prefix of a ref the engine answers in CODE — a stock shader, stock geometry, the
+ * tilemap collision palette. Such a ref names no file, so every stage that turns a
+ * ref into a path (resolution, the cook's rewrite, a dependency walk) has to
+ * recognize it BEFORE resolving, and they have to recognize the same thing.
+ */
+export const BUILTIN_REF_PREFIX = 'builtin:';
+
+/** Whether `ref` names something built in rather than a file. */
+export function isBuiltinAssetRef(ref: string): boolean {
+ return ref.startsWith(BUILTIN_REF_PREFIX);
+}
+
+/** The id a built-in ref names, minus any `?query` it carries, or null. */
+export function builtinRefId(ref: string): string | null {
+ if (!isBuiltinAssetRef(ref)) return null;
+ const body = ref.slice(BUILTIN_REF_PREFIX.length);
+ const query = body.indexOf('?');
+ return query < 0 ? body : body.slice(0, query);
+}
+
/**
* Resolve a ref one document carries about another asset: a logical project path
* stands as it is, anything else is relative to the document. Every loader whose
diff --git a/sdk/src/asset/loaders/MaterialAssetLoader.ts b/sdk/src/asset/loaders/MaterialAssetLoader.ts
index ce86a0c3e..05306bcd9 100644
--- a/sdk/src/asset/loaders/MaterialAssetLoader.ts
+++ b/sdk/src/asset/loaders/MaterialAssetLoader.ts
@@ -1,18 +1,13 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { AssetLoader, LoadContext, MaterialResult } from '../AssetLoader';
-import { resolveDocumentRef } from '../documentRef';
+import { BUILTIN_REF_PREFIX, isBuiltinAssetRef, resolveDocumentRef } from '../documentRef';
import type { MaterialAssetData, ShaderHandle } from '../../render/material';
import { Material } from '../../render/material';
import { builtinShaderTemplate } from '../../render/builtinShaders';
import { AsyncCache } from '../AsyncCache';
import { log } from '../../util/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'];
@@ -95,7 +90,7 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {
// 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 isBuiltin = isBuiltinAssetRef(ref);
const key = isBuiltin ? ref : resolveDocumentRef(matPath, ref);
const cacheKey = features.length ? `${key}#${features.join('|')}` : key;
const cached = this.shaderCache_.get(cacheKey);
@@ -104,7 +99,7 @@ export class MaterialAssetLoader implements AssetLoader<MaterialResult> {
return this.shaderCache_.getOrLoad(cacheKey, async () => {
let content: string;
if (isBuiltin) {
- const template = builtinShaderTemplate(ref.slice(BUILTIN_SHADER_PREFIX.length));
+ const template = builtinShaderTemplate(ref.slice(BUILTIN_REF_PREFIX.length));
if (!template) {
throw new Error(`Unknown built-in shader: ${ref}`);
}
diff --git a/sdk/src/asset/loaders/MeshAssetLoader.ts b/sdk/src/asset/loaders/MeshAssetLoader.ts
index ee758b974..ee1e090a9 100644
--- a/sdk/src/asset/loaders/MeshAssetLoader.ts
+++ b/sdk/src/asset/loaders/MeshAssetLoader.ts
@@ -4,6 +4,7 @@ import type { AssetLoader, LoadContext } from '../AssetLoader';
import type { ESEngineModule } from '../../wasm';
import { withScratch } from '../../wasm/wasmScratch';
import { decodeMesh, encodeChannelTable } from '../meshFormat';
+import { builtinMeshTemplate, isBuiltinMeshRef } from '../builtinMeshes';
import { extractPositions, registerMeshCollision, releaseMeshCollision } from '../meshCollision';
/** A mesh uploaded to the GPU, named by the handle everything else references. */
@@ -17,6 +18,9 @@ export interface MeshResult {
* The file describes its own channels, and that table crosses to the engine in
* the file's own byte layout: this layer owns the format, the engine owns the
* vertex layout it becomes, and neither restates the other.
+ *
+ * A `builtin:<id>` ref is the same geometry with no file under it — built here,
+ * in the layout the model import writes, and uploaded down the identical path.
*/
export class MeshAssetLoader implements AssetLoader<MeshResult> {
readonly type = 'mesh';
@@ -26,8 +30,10 @@ export class MeshAssetLoader implements AssetLoader<MeshResult> {
constructor(private readonly module_: () => ESEngineModule | null) {}
async load(path: string, ctx: LoadContext): Promise<MeshResult> {
- const bytes = new Uint8Array(await ctx.loadBinary(ctx.catalog.getBuildPath(path)));
- const mesh = decodeMesh(bytes);
+ const builtin = isBuiltinMeshRef(path) ? builtinMeshTemplate(path) : undefined;
+ const mesh = builtin
+ ? builtin.build()
+ : decodeMesh(new Uint8Array(await ctx.loadBinary(ctx.catalog.getBuildPath(path))));
const table = encodeChannelTable(mesh.channels);
const m = this.module_();
if (!m?.mesh_createFromChannels) {
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 5b449402e..83a025ebd 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -118,6 +118,16 @@ export {
type MeshChannelDesc, type MeshData,
} from './asset/meshFormat';
export type { MeshResult } from './asset/loaders/MeshAssetLoader';
+/**
+ * Stock geometry a `builtin:<id>` mesh ref names. Public because the editor's
+ * pickers and Create menu are built from this list. `@beta`.
+ *
+ * @beta
+ */
+export {
+ BUILTIN_MESH_TEMPLATES, builtinMeshTemplate, isBuiltinMeshRef,
+ type BuiltinMeshTemplate,
+} from './asset/builtinMeshes';
export { createCanvasTexture, type CanvasTexture } from './asset/canvasTexture';
export type { GlImageSource } from './asset/glTextureUpload';
diff --git a/sdk/src/tilemap/collisionPalette.ts b/sdk/src/tilemap/collisionPalette.ts
index d46690a27..27e3bda2b 100644
--- a/sdk/src/tilemap/collisionPalette.ts
+++ b/sdk/src/tilemap/collisionPalette.ts
@@ -20,12 +20,13 @@
* id → shape mapping is a serialization contract. Only APPEND brushes; never renumber or
* repurpose an existing id, or existing collision maps silently change shape.
*/
+import { BUILTIN_REF_PREFIX } from '../asset/documentRef';
import type { ResolvedTileCollision, TilesetModel } from './tilesetResolve';
/** The sentinel tileset ref that turns a TilemapLayer into a collision (obstacle) layer.
- * Mirrors the `builtin:<id>` shader convention — resolved in code, never a project asset.
- * A per-layer physics material rides as a query string: `builtin:collision?friction=0.1`. */
-export const COLLISION_PALETTE_REF = 'builtin:collision';
+ * One of the `builtin:<id>` refs — resolved in code, never a project asset. A per-layer
+ * physics material rides as a query string: `builtin:collision?friction=0.1`. */
+export const COLLISION_PALETTE_REF = `${BUILTIN_REF_PREFIX}collision`;
/** A collision layer's whole-layer physics material (absent = engine default). */
export interface CollisionMaterial {
diff --git a/sdk/tests/builtin-meshes.test.ts b/sdk/tests/builtin-meshes.test.ts
new file mode 100644
index 000000000..7eceb18fb
--- /dev/null
+++ b/sdk/tests/builtin-meshes.test.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The stock primitives a `builtin:<id>` mesh ref names.
+ *
+ * What matters about generated geometry is not that it exists but which way it
+ * faces: a primitive whose winding disagrees with its normals is invisible under
+ * `cullBackfaces` and lit from the inside under `lit`, and neither reads as a
+ * geometry bug when you meet it.
+ */
+import { describe, it, expect } from 'vitest';
+import { BUILTIN_MESH_TEMPLATES, builtinMeshTemplate, isBuiltinMeshRef } from '../src/asset/builtinMeshes';
+import { MeshChannel, MeshChannelType, type MeshData } from '../src/asset/meshFormat';
+
+interface Vec { x: number; y: number; z: number }
+
+function readVertex(mesh: MeshData, index: number): { p: Vec; n: Vec } {
+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset, mesh.vertices.byteLength);
+ const at = index * mesh.vertexStride;
+ const pos = mesh.channels.find((c) => c.semantic === MeshChannel.Position)!;
+ const nrm = mesh.channels.find((c) => c.semantic === MeshChannel.Normal)!;
+ const read = (offset: number): Vec => ({
+ x: view.getFloat32(at + offset, true),
+ y: view.getFloat32(at + offset + 4, true),
+ z: view.getFloat32(at + offset + 8, true),
+ });
+ return { p: read(pos.offset), n: read(nrm.offset) };
+}
+
+const sub = (a: Vec, b: Vec): Vec => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });
+const dot = (a: Vec, b: Vec): number => a.x * b.x + a.y * b.y + a.z * b.z;
+const cross = (a: Vec, b: Vec): Vec => ({
+ x: a.y * b.z - a.z * b.y,
+ y: a.z * b.x - a.x * b.z,
+ z: a.x * b.y - a.y * b.x,
+});
+
+describe('built-in meshes', () => {
+ it('offers every primitive under a builtin: ref', () => {
+ expect(BUILTIN_MESH_TEMPLATES.map((t) => t.id).sort())
+ .toEqual(['capsule', 'cone', 'cube', 'cylinder', 'plane', 'quad', 'sphere']);
+ for (const t of BUILTIN_MESH_TEMPLATES) {
+ expect(t.ref).toBe(`builtin:${t.id}`);
+ expect(isBuiltinMeshRef(t.ref)).toBe(true);
+ expect(builtinMeshTemplate(t.ref)).toBe(t);
+ }
+ });
+
+ // A misspelled built-in must stay a path, so the loader 404s it by name rather
+ // than the ref quietly resolving to nothing at all.
+ it('does not claim a ref it cannot build', () => {
+ expect(isBuiltinMeshRef('builtin:teapot')).toBe(false);
+ expect(isBuiltinMeshRef('assets/models/hero.esmesh')).toBe(false);
+ expect(builtinMeshTemplate('builtin:teapot')).toBeUndefined();
+ });
+
+ it('writes the channel layout the model import writes', () => {
+ for (const t of BUILTIN_MESH_TEMPLATES) {
+ const mesh = t.build();
+ expect(mesh.channels.map((c) => c.semantic)).toEqual([
+ MeshChannel.Position, MeshChannel.TexCoord0, MeshChannel.Color, MeshChannel.Normal,
+ ]);
+ expect(mesh.channels.find((c) => c.semantic === MeshChannel.Color)!.type)
+ .toBe(MeshChannelType.UNorm8);
+ expect(mesh.vertexCount).toBeGreaterThan(0);
+ expect(mesh.indices.length % 3).toBe(0);
+ expect(mesh.inverseBindMatrices).toBeUndefined();
+ for (const i of mesh.indices) expect(i).toBeLessThan(mesh.vertexCount);
+ }
+ });
+
+ it('winds every triangle to agree with its own normals', () => {
+ for (const t of BUILTIN_MESH_TEMPLATES) {
+ const mesh = t.build();
+ for (let i = 0; i < mesh.indices.length; i += 3) {
+ const a = readVertex(mesh, mesh.indices[i]!);
+ const b = readVertex(mesh, mesh.indices[i + 1]!);
+ const c = readVertex(mesh, mesh.indices[i + 2]!);
+ const face = cross(sub(b.p, a.p), sub(c.p, a.p));
+ const shaded = { x: a.n.x + b.n.x + c.n.x, y: a.n.y + b.n.y + c.n.y, z: a.n.z + b.n.z + c.n.z };
+ expect(`${t.id}#${i / 3}: ${dot(face, shaded) > 0}`).toBe(`${t.id}#${i / 3}: true`);
+ }
+ }
+ });
+
+ // "Outward" only means something for geometry enclosing a volume, which is the
+ // same distinction `closed` makes for depth and back-face culling.
+ it('points a closed primitive\'s normals away from its middle', () => {
+ const closed = BUILTIN_MESH_TEMPLATES.filter((t) => t.closed);
+ expect(closed.length).toBe(5);
+ for (const t of closed) {
+ const mesh = t.build();
+ for (let i = 0; i < mesh.vertexCount; i++) {
+ const { p, n } = readVertex(mesh, i);
+ expect(`${t.id}#${i}: ${dot(p, n) > 0}`).toBe(`${t.id}#${i}: true`);
+ }
+ }
+ });
+
+ it('builds each primitive 100 units across, centred on the origin', () => {
+ for (const t of BUILTIN_MESH_TEMPLATES) {
+ const mesh = t.build();
+ for (let k = 0; k < 3; k++) {
+ expect(mesh.aabbMin[k]).toBeCloseTo(-mesh.aabbMax[k]!, 4);
+ expect(mesh.aabbMax[k]).toBeLessThanOrEqual(50.0001);
+ }
+ const size = Math.max(...mesh.aabbMax.map((v, k) => v - mesh.aabbMin[k]!));
+ expect(size).toBeCloseTo(100, 4);
+ }
+ });
+});
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index 081034f06..d975c8619 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -69,6 +69,10 @@ export const SCENES = [
// Hand-derived, 255·NdotL·atten: 224 under it and 101 at world +200, where the
// plane's convention reads 255 and 200.
{ id: "mesh-point-3d", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-point-3d.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[224,224,224],\"tol\":20},{\"x\":0.833,\"y\":0.5,\"rgb\":[102,102,102],\"tol\":20}]" } },
+ // Geometry with no file under it. Sun 22.5° off the view axis: the cube's two faces
+ // read 255·cos22.5 and 255·cos67.5, swapped if the winding is inside out; the sphere
+ // reads 155 at -25 against 236 at its middle, which a flat quad could not.
+ { id: "mesh-builtin", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-builtin.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.3667,\"y\":0.5,\"rgb\":[236,236,236],\"tol\":20},{\"x\":0.1333,\"y\":0.5,\"rgb\":[98,98,98],\"tol\":20},{\"x\":0.75,\"y\":0.5,\"rgb\":[236,236,236],\"tol\":20},{\"x\":0.6667,\"y\":0.5,\"rgb\":[155,155,155],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },
// A baked panorama lighting a surface BY DIRECTION: two coplanar triangles, one
// white colour, normals up and down under a sky blue above and red below. A flat
// ambient term draws the halves identically, which is why the probes invert.