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(modeling): a character wears another model at a joint, through saving and export

yhh9f4795518d03
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2780187db..4e11cf6e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,7 +22,7 @@ published separately; it ships inside the editor.
- **Glyphs can be put on the atlas before they are shown.** The first page of a novel is hundreds of new characters, all landing in one frame. `preloadGlyphs(app, label, text, { budgetMs })` makes them ahead of time, a slice a frame, drawn as that `Text` will draw them, and returns `progress`, `done` and `release()`. On a Snapdragon 8 Elite a book's 2992 characters at 28 px took 145 ms over 25 frames with the worst frame at 9.5 ms, after which the first page's frame went from 49 to 11 ms and no page made a new glyph. Preloaded glyphs hold their atlas pages (4 MB each, a few hundred characters at that size) until `release()`.
- **Voxel GI lights what the camera does not see, and bounces light more than once.** The cache now reads the sun's shadow map back into the world, so a surface the sun lights behind or beside the camera still sends light into the view. Each surface also gives off again the bounce light it received, so a corner or a floor in shade gets light that took two or more bounces to reach it. A ray now brings what it meets at full strength however far it went (it used to fade with distance, 40% at 4 m with 12 cm voxels). Each voxel is weighed by how much of it a surface covers, so a bright patch no longer lights like the whole voxel around it. Together these keep the result close to a path tracer's whatever the voxel size. In a sunlit test room the whole frame carries 0.95 of Cycles' light at the default size and 0.74 at 12 cm voxels; before, it was 0.54 at the default and darker the finer the grid. With the lit patch behind the camera, the walls went from no bounce light to 25–57%. A closed room the sun only lights from outside stays dark. Two inspector controls tune it: **Off-screen Sun Albedo** (the colour the shadow map cannot give, assumed) and **Multi-bounce**. A fine grid no longer drops every voxel: a count truncated by the cache's ageing had kept them below the two samples a ray asks for. The WebGL2 fallback does the same in its own passes: each voxel asks the sun's map whether a sunlit surface stands in it, and traces two rays through last frame's grid for the light it is given. In the test room it carries 1.00 of Cycles' light at the default size (it was 0.56) and 0.80 at 12 cm; with the lit patch behind the camera 0.20 (it was 0). Its voxel pass costs about 1.3 ms more at 720p on a desktop.
-- **An AI building a model can make hair.** A `hair` step grows cards from a scalp, falling around the head, and writes the strand textures and a Hair material. `hairSway` gives them bones that swing as the game runs, and worn under a head joint they follow the character.
+- **An AI building a model can make hair.** A `hair` step grows cards from a scalp, falling around the head, and writes the strand textures and a Hair material. `hairSway` gives them bones that swing as the game runs, and a character's `attach` carries the hair at its head joint, through saving and export.
- **An AI building a model can make things see-through.** `material.alpha` is `cutout` for leaves and lace or `blend` for glass and gauze, and a `stain` can set alpha by a pattern or a shape, which a bake keeps on a thin mesh.
@@ -56,6 +56,8 @@ published separately; it ships inside the editor.
### Fixed
+- **An agent is told when a child it adds inside a prefab instance will not last.** A scene stores an instance as its root and its changes, so such a child lost its parent on saving, and an exported game dropped it, with no word. `apply_scene_ops` now warns, and says what to do instead.
+
- **A material's normal and metal-rough maps are read as data in the editor's Play.** A map named beside its `.esmaterial` missed its import settings there, as Play spells it by URL, so it was decoded as colour: mid-range roughness read far too smooth, and normal maps bent. Filter and wrap settings were lost the same way.
- **A rotation given to an agent as a quaternion is that rotation.** `set_field` and `apply_scene_ops` read `{ w, x, y, z }` as degrees and dropped `w`, so a character meant to turn 90 degrees turned under one, with no error. A joint posed this way looked as if the skin did not follow it.
diff --git a/desktop b/desktop
index ec74562aa..762927009 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit ec74562aaef66e3b8cf363a993510a041875d6ec
+Subproject commit 762927009edd921e909433e24832f0ba46dbd025
diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.ts
index afcc5e4b2..e6fbb13cf 100644
--- a/pipeline/src/modeling/modelSource.ts
+++ b/pipeline/src/modeling/modelSource.ts
@@ -22,7 +22,7 @@ import { decimate, triangleCount } from './decimate';
import { displace, DISPLACE_PATTERNS } from './displace';
import { stain } from './stain';
import { cardsOnly, hair, hasCards, type HairSway } from './hair';
-import { checkAnimations, checkController, checkRig, checkShapes, type AnimationSource, type ControllerSource, type RigSource, type ShapeSource } from './rig';
+import { checkAnimations, checkController, checkRig, checkShapes, resolveJoints, type AnimationSource, type ControllerSource, type RigSource, type ShapeSource } from './rig';
import { compact, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
export const MODEL_SOURCE_VERSION = 1;
@@ -43,6 +43,8 @@ export interface ModelSource {
uvScale?: number;
/** Lay the base UV out so no two triangles share texels: for a texture painted for this one model, where tiling is not wanted. */
uvAtlas?: boolean;
+ /** Other models this one wears: each a prefab, carried at a joint. */
+ attach?: ModelAttachment[];
/** Bones through a hair model's cards, which swing as the game runs. */
hairSway?: HairSway;
/** What every face is made of until a `paint` or `stain` says otherwise. */
@@ -71,6 +73,13 @@ export interface ModelMaterial {
cutoff?: number;
}
+export interface ModelAttachment {
+ /** The joint it follows. */
+ joint: string;
+ /** The prefab, by project path, built in this model's own space. */
+ prefab: string;
+}
+
export interface NormalBakeOcclusion {
/** How far a ray looks, in model units. Default about 6% of the model's diagonal. */
reach?: number;
@@ -343,8 +352,8 @@ export function validateModelSource(raw: unknown): ModelSource {
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) throw new ModelBuildError('a model source must be an object with `steps`', null, null, null);
const source = raw as Record<string, unknown>;
for (const key of Object.keys(source)) {
- if (!['version', 'smoothAngle', 'uvScale', 'uvAtlas', 'material', 'hairSway', 'normalBake', 'rig', 'shapes', 'animations', 'controller', 'steps'].includes(key)) {
- throw new ModelBuildError(`unknown field "${key}"; a model source has version, smoothAngle, uvScale, uvAtlas, material, hairSway, normalBake, rig, shapes, animations, controller, steps`, null, null, null);
+ if (!['version', 'smoothAngle', 'uvScale', 'uvAtlas', 'material', 'hairSway', 'attach', 'normalBake', 'rig', 'shapes', 'animations', 'controller', 'steps'].includes(key)) {
+ throw new ModelBuildError(`unknown field "${key}"; a model source has version, smoothAngle, uvScale, uvAtlas, material, hairSway, attach, normalBake, rig, shapes, animations, controller, steps`, null, null, null);
}
}
if (source.version !== undefined && source.version !== MODEL_SOURCE_VERSION) {
@@ -394,6 +403,18 @@ export function validateModelSource(raw: unknown): ModelSource {
if (source.normalBake !== undefined || source.uvAtlas) throw new ModelBuildError('a hair model\'s cards take their texture where the step puts them, so it has no normalBake or uvAtlas', null, null, null);
if (source.rig !== undefined || source.shapes !== undefined) throw new ModelBuildError('a hair model has no rig or shapes of its own: `hairSway` gives it bones, and placed under a head joint it follows that', null, null, null);
}
+ if (source.attach !== undefined) {
+ const fail = (what: string): never => { throw new ModelBuildError(`attach ${what}`, null, null, null); };
+ if (!Array.isArray(source.attach)) fail('must be an array of { joint, prefab }');
+ if (source.rig === undefined) fail('needs a rig: it is carried by a joint');
+ const names = new Set(resolveJoints(source.rig as RigSource).map((j) => j.name));
+ (source.attach as Record<string, unknown>[]).forEach((a, i) => {
+ if (typeof a !== 'object' || a === null) fail(`[${i}] must be { joint, prefab }`);
+ for (const key of Object.keys(a)) if (key !== 'joint' && key !== 'prefab') fail(`[${i}] has an unknown field "${key}"; it takes joint, prefab`);
+ if (typeof a.joint !== 'string' || !names.has(a.joint)) fail(`[${i}].joint ${JSON.stringify(a.joint)} is no joint of the rig`);
+ if (typeof a.prefab !== 'string' || !a.prefab.endsWith('.esprefab')) fail(`[${i}].prefab must be a project path to an .esprefab`);
+ });
+ }
if (source.hairSway !== undefined) {
const sway = source.hairSway as Record<string, unknown> | null;
const fail = (what: string): never => { throw new ModelBuildError(`hairSway ${what}`, null, null, null); };
@@ -498,7 +519,7 @@ export type ModelEdit =
| { op: 'set'; step: string | number; fields: Record<string, unknown> }
| { op: 'insert'; step: ModelStep; before?: string | number; after?: string | number }
| { op: 'remove'; step: string | number }
- | { op: 'settings'; fields: Pick<ModelSource, 'smoothAngle' | 'uvScale' | 'uvAtlas' | 'material' | 'normalBake' | 'rig' | 'shapes' | 'animations' | 'controller'> };
+ | { op: 'settings'; fields: Pick<ModelSource, 'smoothAngle' | 'uvScale' | 'uvAtlas' | 'material' | 'attach' | 'normalBake' | 'rig' | 'shapes' | 'animations' | 'controller'> };
function indexOfStep(source: ModelSource, ref: string | number): number {
const i = typeof ref === 'number' ? ref : source.steps.findIndex((s) => s.id === ref);
diff --git a/pipeline/src/modeling/rig.ts b/pipeline/src/modeling/rig.ts
index fc71865d7..b13f6cfb5 100644
--- a/pipeline/src/modeling/rig.ts
+++ b/pipeline/src/modeling/rig.ts
@@ -932,7 +932,7 @@ export function timelineOf(animation: AnimationSource, joints: readonly RigJoint
*/
const SWAY_COLLIDER = 'hairCollider';
-export function prefabOf(name: string, meshPath: string, joints: readonly RigJoint[], cullBackfaces: boolean, firstClip: string | null, controller: string | null = null, extra: { goals?: readonly RigGoal[]; shapes?: number; normalMap?: string; texture?: string; material?: string; opaque?: boolean; sway?: { chainRoots: readonly number[]; stiffness?: number; drag?: number; collider?: { at: Vec3; radius: number } } } = {}): Record<string, unknown> {
+export function prefabOf(name: string, meshPath: string, joints: readonly RigJoint[], cullBackfaces: boolean, firstClip: string | null, controller: string | null = null, extra: { goals?: readonly RigGoal[]; shapes?: number; normalMap?: string; texture?: string; material?: string; opaque?: boolean; attach?: readonly { joint: string; prefab: string }[]; sway?: { chainRoots: readonly number[]; stiffness?: number; drag?: number; collider?: { at: Vec3; radius: number } } } = {}): Record<string, unknown> {
const idOf = (i: number): string => `j${i}`;
const goals = extra.goals ?? [];
const entities: Record<string, unknown>[] = [{
@@ -953,7 +953,7 @@ export function prefabOf(name: string, meshPath: string, joints: readonly RigJoi
const rest = j.parent >= 0 ? sub(j.at, joints[j.parent]!.at) : j.at;
entities.push({
prefabEntityId: idOf(i), name: j.name, parent: j.parent >= 0 ? idOf(j.parent) : 'root',
- children: [...j.children.map(idOf), ...goals.flatMap((g, k) => (g.parent === j.name ? [`g${k}`] : []))], visible: true,
+ children: [...j.children.map(idOf), ...goals.flatMap((g, k) => (g.parent === j.name ? [`g${k}`] : [])), ...(extra.attach ?? []).flatMap((a, k) => (a.joint === j.name ? [`a${k}`] : []))], visible: true,
components: [
{ type: 'Transform', data: { position: { x: rest[0], y: rest[1], z: rest[2] } } },
// On a chain's first bone, which stays where it is: the ones below it swing.
@@ -964,6 +964,16 @@ export function prefabOf(name: string, meshPath: string, joints: readonly RigJoi
],
});
});
+ // Inside the prefab and not beside it in a scene, where a parent inside an instance has no way to be written down. Built in this model's
+ // space, so its root goes back by as far as the joint it hangs from is out.
+ (extra.attach ?? []).forEach((a, k) => {
+ const joint = joints.findIndex((j) => j.name === a.joint);
+ const at = joints[joint]!.at;
+ entities.push({
+ prefabEntityId: `a${k}`, name: a.prefab.slice(a.prefab.lastIndexOf('/') + 1, -'.esprefab'.length), parent: idOf(joint), children: [], visible: true, components: [],
+ nestedPrefab: { prefabPath: a.prefab, overrides: [{ prefabEntityId: 'root', type: 'property', componentType: 'Transform', propertyName: 'position', value: { x: -at[0], y: -at[1], z: -at[2] } }] },
+ });
+ });
if (extra.sway?.collider) {
const { at, radius } = extra.sway.collider;
entities.push({
diff --git a/pipeline/tests/modeling-hair.test.ts b/pipeline/tests/modeling-hair.test.ts
index 012a704ed..e6fe81a47 100644
--- a/pipeline/tests/modeling-hair.test.ts
+++ b/pipeline/tests/modeling-hair.test.ts
@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';
import { MeshChannel } from 'esengine';
import { bakeModel, bakeNormalMap, modelMaterialDoc, validateModelSource, type BakedModel, type ModelStep } from '../src/modeling';
import { hairMaps } from '../src/modeling/hair';
+import { prefabOf, resolveJoints } from '../src/modeling/rig';
const head: ModelStep = { op: 'sphere', radius: 1, rings: 24, sides: 48, tag: 'head' };
const scalp = { within: { min: [null, 0.2, null] } };
@@ -195,6 +196,33 @@ describe('hairSway', () => {
});
});
+describe('attach', () => {
+ const rig = { joints: [{ name: 'root', at: [0, 0, 0] }, { name: 'head', at: [0, 1.5, 0.1], parent: 'root' }] };
+ const head2: ModelStep = { op: 'sphere', radius: 1, rings: 8, sides: 12 };
+
+ it('nests the prefab under the joint, drawn back by as far as the joint is out', () => {
+ const joints = resolveJoints(rig as never);
+ const prefab = prefabOf('body', 'body.esmesh', joints, true, null, null, { attach: [{ joint: 'head', prefab: 'assets/wig.esprefab' }] }) as { entities: Record<string, unknown>[] };
+ const worn = prefab.entities.find((e) => e.prefabEntityId === 'a0')!;
+ const head = prefab.entities.find((e) => e.name === 'head')!;
+ expect(worn.parent).toBe(head.prefabEntityId);
+ expect(head.children).toContain('a0');
+ expect(worn.name).toBe('wig');
+ expect(worn.nestedPrefab).toEqual({
+ prefabPath: 'assets/wig.esprefab',
+ overrides: [{ prefabEntityId: 'root', type: 'property', componentType: 'Transform', propertyName: 'position', value: { x: -0, y: -1.5, z: -0.1 } }],
+ });
+ });
+
+ it('refuses what cannot be meant', () => {
+ expect(() => validateModelSource({ steps: [head2], attach: [{ joint: 'head', prefab: 'a.esprefab' }] })).toThrow(/needs a rig/);
+ expect(() => validateModelSource({ steps: [head2], rig, attach: [{ joint: 'tail', prefab: 'a.esprefab' }] })).toThrow(/"tail" is no joint/);
+ expect(() => validateModelSource({ steps: [head2], rig, attach: [{ joint: 'head', prefab: 'a.png' }] })).toThrow(/must be a project path to an .esprefab/);
+ expect(() => validateModelSource({ steps: [head2], rig, attach: [{ joint: 'head', prefab: 'a.esprefab', at: 1 }] })).toThrow(/unknown field "at"/);
+ expect(() => validateModelSource({ steps: [head2], rig, attach: { joint: 'head' } })).toThrow(/must be an array/);
+ });
+});
+
describe('see-through', () => {
const plane: ModelStep = { id: 'form', op: 'plane', size: 2, color: [0.2, 0.6, 0.2] };
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 89232efca..d3fa8c4fc 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3882,6 +3882,10 @@ export const NOTED = {
{"note":"A rotation given to an agent as a quaternion is that rotation."},
"fix(asset): a map a material names keeps its import settings in Play, where it was decoded as colour":
{"note":"A material's normal and metal-rough maps are read as data in the editor's Play."},
+ "feat(modeling): a character wears another model at a joint, through saving and export":
+ {"note":"An AI building a model can make hair."},
+ "fix(mcp): a child added inside a prefab instance is warned about, and a check runs a real package of it all":
+ {"note":"An agent is told when a child it adds inside a prefab instance will not last."},
"feat(modeling): a hair step grows cards from a scalp, and a material can cut holes or let light through":
{"note":"An AI building a model can make hair."},
"feat(mcp): model_write makes hair and see-through surfaces, and a check draws them":