@wildshard/sdk 0.2.13 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GUIDE.md +26 -13
- package/bin/wildshard.mjs +2 -1
- package/docs/api/EXPORT-TIERS.md +16 -4
- package/lint/export-tiers.json +12 -0
- package/lint/host-callbacks.mjs +1 -1
- package/package.json +22 -6
- package/scripts/bake/template-skins.mjs +6 -3
- package/scripts/bake/template-warden.mjs +25 -0
- package/scripts/build-shardfiles.mjs +7 -2
- package/scripts/export-ci21-guests.mjs +89 -0
- package/scripts/prepare-product.mjs +2 -2
- package/scripts/scratch-sweep.mjs +182 -0
- package/scripts/wildshard.mjs +1 -1
- package/skills/wildshard-mockup-to-model/SKILL.md +5 -3
- package/skills/wildshard-upgrade/SKILL.md +4 -4
- package/src/cli/help.ts +9 -5
- package/src/cli/upload/validate.ts +7 -5
- package/src/sharddev/as/prelude.ts +67 -0
- package/src/sharddev/assets.ts +1 -1
- package/src/sharddev/authorLint.ts +45 -0
- package/src/sharddev/bake/compactGlb.ts +1 -1
- package/src/sharddev/bake/compileScript.ts +6 -0
- package/src/sharddev/bake/glbCompression.ts +1 -1
- package/src/sharddev/bake/gltfSource.ts +1 -1
- package/src/sharddev/bake/placeholders.ts +1 -1
- package/src/sharddev/bake/terrain.ts +12 -3
- package/src/sharddev/blobBytes.ts +1 -1
- package/src/sharddev/blobs.ts +2 -2
- package/src/sharddev/checkProject.ts +7 -18
- package/src/sharddev/cli.ts +17 -4
- package/src/sharddev/engineMusic.ts +23 -0
- package/src/sharddev/formatJsonSchema.ts +1 -1
- package/src/sharddev/materialGraphFiles.ts +1 -1
- package/src/sharddev/materials.ts +7 -3
- package/src/sharddev/newProject.ts +18 -10
- package/src/sharddev/outputProduct.ts +2 -2
- package/src/sharddev/productOutput.ts +2 -2
- package/src/sharddev/project.ts +6 -1
- package/src/sharddev/projectMap.ts +1 -1
- package/src/sharddev/refusals.ts +5 -3
- package/src/sharddev/reportCard.ts +1 -1
- package/src/sharddev/scene/author.ts +184 -0
- package/src/sharddev/scene/canvas.ts +212 -0
- package/src/sharddev/scene/description.ts +223 -0
- package/src/sharddev/scene/hash.ts +23 -0
- package/src/sharddev/scene/lower.ts +341 -0
- package/src/sharddev/scene/shard.ts +41 -0
- package/src/sharddev/scene/shardfile.ts +621 -0
- package/src/sharddev/threeGate.mjs +14 -0
- package/src/sharddev/threePin.mjs +40 -0
- package/src/sharddev/watch/page.ts +284 -0
- package/src/sharddev/watch/pageEntry.ts +59 -0
- package/src/sharddev/watch/parity-baseline.json +22 -0
- package/src/sharddev/watch/parity.mjs +168 -0
- package/src/sharddev/watch/proof.mjs +199 -0
- package/src/sharddev/watch/protocol.ts +166 -0
- package/src/sharddev/watch/socket.ts +57 -0
- package/src/sharddev/watch/watch.ts +373 -0
- package/src/shards/_template/assets/3058c100bc477fd6fe8268f33b53756b8a2556e7e41c58b2216c703ca7b042c6 +1 -0
- package/src/shards/_template/assets/8a0440f392737a31cf0926a3c7dc011c320144972882945a5462c893e817d94a +0 -0
- package/src/shards/_template/behaviour/door.as +16 -26
- package/src/shards/_template/card/landscape.jpg +0 -0
- package/src/shards/_template/card/portrait.jpg +0 -0
- package/src/shards/_template/card/thumb.jpg +0 -0
- package/src/shards/_template/data/clientScripts.json +43 -43
- package/src/shards/_template/data/creatures.json +2 -2
- package/src/shards/_template/data/look.json +141 -13
- package/src/shards/_template/data/rows.json +20 -2
- package/src/shards/_template/data/skins.json +32 -0
- package/src/shards/_template/data/water.json +18 -0
- package/src/shards/_template/generators/product.ts +5 -1
- package/src/shards/_template/generators/warden.ts +273 -0
- package/src/shards/_template/generators/world.ts +52 -21
- package/src/shards/_template/hero.json +6 -6
- package/src/shards/authoring-slice/generators/shard.ts +14 -0
- package/src/shards/authoring-slice/generators/sky.ts +64 -0
- package/src/shards/authoring-slice/generators/template-sky.ts +27 -0
- package/src/shards/authoring-slice/generators/textures.ts +232 -0
- package/src/shards/authoring-slice/generators/world.ts +518 -0
- package/src/shards/authoring-slice/shard.config.ts +7 -0
- package/src/shards/mossgate/generators/shard.ts +6 -0
- package/src/shards/mossgate/generators/sky.ts +64 -0
- package/src/shards/mossgate/generators/textures.ts +249 -0
- package/src/shards/mossgate/generators/world.ts +998 -0
- package/src/shards/mossgate/shard.config.ts +7 -0
- package/scripts/shard-output-report.d.mts +0 -9
- package/scripts/shard-output-report.mjs +0 -85
- package/scripts/shard-platform-cli.mjs +0 -93
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
import { Box3, BufferAttribute, BufferGeometry, Color, Float32BufferAttribute, Matrix3, Matrix4, MeshStandardMaterial, Quaternion, Vector3 } from 'three';
|
|
2
|
+
import type { PoolSurface } from '@wildshard/format/pool-surface';
|
|
3
|
+
import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
|
|
4
|
+
import { emptyShardfile } from '../author';
|
|
5
|
+
import { parseGlb, parseKtx2 } from '../assets';
|
|
6
|
+
import { hashImmutableBytes } from '../immutable';
|
|
7
|
+
import type { GeneratedProject, ProjectGenerationContext } from '../projectGeneration';
|
|
8
|
+
import { staticGlb, type GlbPrimitive } from '../bake/glb';
|
|
9
|
+
import { bakeTerrain, groundLattice } from '../bake/terrain';
|
|
10
|
+
import { encodeTerrainTile } from '@wildshard/format/terrainTileBytes';
|
|
11
|
+
import { bakeRawColourPixels } from '../bake/rawTexture';
|
|
12
|
+
import type { Rgb, SceneCollider, SceneDraw, SceneGeometry, SceneLight, SceneMaterial, SceneMotion, ScenePart, ShardScene } from './description';
|
|
13
|
+
import { SceneRefusalError } from './lower';
|
|
14
|
+
import { hashOf } from './hash';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* AUTHORING-PARITY AP2, AP3, AP4: the shardfile back end. It reads only the scene description and writes the sections an
|
|
18
|
+
* author types by hand today:
|
|
19
|
+
*
|
|
20
|
+
* - **static parts** (AP2): every `Mesh`, merged per material per 62.5 m tile (the map's repeat and offset in the uvs), one
|
|
21
|
+
* named GLB material per scene material, a generated `look.materials` entry and `props.materials` binding for each,
|
|
22
|
+
* painted textures as RGBA8 KTX2 slots; an `InstancedMesh` with no motion stays instanced (SHARD-SOURCE AP15): its
|
|
23
|
+
* geometry once per tile, its copies as `EXT_mesh_gpu_instancing` rows in the tile of their seat (a swaying or carded
|
|
24
|
+
* one is still expanded: the engine's sway reads the mesh's own frame);
|
|
25
|
+
* - **light and look** (AP3): `PointLight`s to `look.light.lamps` (the 16 brightest), the brightest `DirectionalLight` to
|
|
26
|
+
* the sun key, a `HemisphereLight` to the ambient key, `scene.fog`, `world.post`;
|
|
27
|
+
* - **ground, colliders, water** (AP4): `world.ground(heightAt)` to the terrain bake, `solid(mesh)` to collider boxes, each
|
|
28
|
+
* `Water` to a `water[]` pool row whose outline is its own geometry's.
|
|
29
|
+
* - **panels** (AP16): a `world.part(name, build, { panel })` is one library GLB of its own (`props.panels`, every entry
|
|
30
|
+
* merged whole) and one collider bound to it, so a `targets.panels` row hides both by state (a gate that opens).
|
|
31
|
+
*
|
|
32
|
+
* - **cards** (AP11): every `Sprite` and every point of a `Points` cloud as a camera-facing quad (its seat in `position`, its
|
|
33
|
+
* corner in the `_CORNER` channel), merged per material and motion per tile: one draw a tile, an emissive `card` entry;
|
|
34
|
+
* - **declared motion** (AP12): a light's `flicker` to its lamp row, a card's `pulse` / `drift` / `rise` to its entry's
|
|
35
|
+
* `motion`, a mesh's `sway` to its entry's `sway` plus a `_SWAY` channel (metres, growing with the square of the height
|
|
36
|
+
* over the mesh's own bounds), a mesh's `uvScroll` to its entry's `uvScroll`.
|
|
37
|
+
*
|
|
38
|
+
* Phone tile caps are reported, not enforced (J338: this shard may use up to 50 MB): AP9 turns them into a per-part table.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
export interface ShardfileOptions {
|
|
42
|
+
/** extra rows merged into the generated shardfile (manifest, card, quests...) */
|
|
43
|
+
readonly extend?: (shard: Shardfile) => Shardfile;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const TILE = 62.5, HALF = 250;
|
|
47
|
+
/** AP15: how far an instanced copy may hang past the cell's edge (format `props.overhang`, at most 1 m). */
|
|
48
|
+
const OVERHANG = 1;
|
|
49
|
+
const glbName = (material: SceneMaterial, taken: Map<string, string>): string => {
|
|
50
|
+
const wanted = material.name.replaceAll(/[^\w.-]/gu, '-').slice(0, 96) || material.key;
|
|
51
|
+
const owner = taken.get(wanted);
|
|
52
|
+
const name = owner === undefined || owner === material.key ? wanted : `${wanted}-${material.key}`;
|
|
53
|
+
taken.set(name, material.key); return name;
|
|
54
|
+
};
|
|
55
|
+
const lookId = (key: string): string => `scene.${key}`;
|
|
56
|
+
/** A point's card width per metre of `PointsMaterial.size` (three's size attenuation at the cleanrooms' 72° view: tan 36°). */
|
|
57
|
+
const POINT_CARD = 0.7265;
|
|
58
|
+
/** One merge's material: the scene material, the motion its draws declare, and whether it is a card. */
|
|
59
|
+
interface Entry { readonly material: SceneMaterial; readonly motion: SceneMotion | null; readonly card: boolean }
|
|
60
|
+
const entryKey = (material: string, motion: SceneMotion | null, card = false): string =>
|
|
61
|
+
motion === null && !card ? material : `${material}${card ? '.card' : ''}${motion === null ? '' : `.${hashOf((h) => h.json(motion))}`}`;
|
|
62
|
+
const luminance = ([r, g, b]: Rgb): number => 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
|
63
|
+
const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));
|
|
64
|
+
const round = (value: number, digits = 4): number => { const k = 10 ** digits; const out = Math.round(value * k) / k; return out === 0 ? 0 : out; };
|
|
65
|
+
const rgb01 = (colour: Rgb): [number, number, number] => [round(clamp01(colour[0])), round(clamp01(colour[1])), round(clamp01(colour[2]))];
|
|
66
|
+
/** A linear channel as sRGB (three's `LinearToSRGB`). */
|
|
67
|
+
const toSrgb = (c: number): number => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055);
|
|
68
|
+
/**
|
|
69
|
+
* ss4d: a linear colour (every scene colour, as three.js holds it) as the format's sRGB material colour (`look.materials`
|
|
70
|
+
* `colour`, `emissive` and a detail layer's moss are sRGB: what an artist picks; engine `families/pbr.ts` reads them with
|
|
71
|
+
* `SRGBColorSpace`). Lamps, fog, sky keys, pool tints and the environment ground stay linear, as the format says.
|
|
72
|
+
*/
|
|
73
|
+
const srgb01 = (colour: Rgb): [number, number, number] => [round(clamp01(toSrgb(clamp01(colour[0])))), round(clamp01(toSrgb(clamp01(colour[1])))), round(clamp01(toSrgb(clamp01(colour[2]))))];
|
|
74
|
+
/** ss4d: the ground's PBR material id (the terrain family; the format's default `toon` drew a lit scene's ground flat). */
|
|
75
|
+
export const GROUND_MATERIAL = 'scene.ground';
|
|
76
|
+
|
|
77
|
+
/** One tile's growing merge for one material: world-space vertices and an index (a copy inside one tile keeps its
|
|
78
|
+
* own index; a triangle cut at a tile seam adds its clipped corners). */
|
|
79
|
+
interface Merge { position: number[]; normal: number[]; uv: number[]; colour: number[]; index: number[]; sway: number[]; corner: number[] }
|
|
80
|
+
const emptyMerge = (): Merge => ({ position: [], normal: [], uv: [], colour: [], index: [], sway: [], corner: [] });
|
|
81
|
+
|
|
82
|
+
/** The tiles a world box touches, by L0 address. */
|
|
83
|
+
const tileOf = (value: number): number => Math.min(7, Math.max(0, Math.floor((value + HALF) / TILE)));
|
|
84
|
+
|
|
85
|
+
interface Vertex { p: Vector3; n: Vector3; u: number; v: number; c: Vector3; s: number }
|
|
86
|
+
function clipToTile(triangle: readonly Vertex[], x: number, z: number): Vertex[] {
|
|
87
|
+
const x0 = -HALF + x * TILE, z0 = -HALF + z * TILE;
|
|
88
|
+
let polygon = [...triangle];
|
|
89
|
+
for (const [axis, limit, direction] of [['x', x0, 1], ['x', x0 + TILE, -1], ['z', z0, 1], ['z', z0 + TILE, -1]] as const) {
|
|
90
|
+
const input = polygon; polygon = [];
|
|
91
|
+
for (let i = 0; i < input.length; i++) {
|
|
92
|
+
const a = input[i], b = input[(i + 1) % input.length]; if (a === undefined || b === undefined) continue;
|
|
93
|
+
const da = (a.p[axis] - limit) * direction, db = (b.p[axis] - limit) * direction;
|
|
94
|
+
if (da >= 0) polygon.push(a);
|
|
95
|
+
if ((da < 0) !== (db < 0)) { const t = da / (da - db); polygon.push({ p: a.p.clone().lerp(b.p, t), n: a.n.clone().lerp(b.n, t).normalize(), u: a.u + (b.u - a.u) * t, v: a.v + (b.v - a.v) * t, c: a.c.clone().lerp(b.c, t), s: a.s + (b.s - a.s) * t }); }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return polygon;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Expand every draw of one entry into per-tile world triangles. */
|
|
102
|
+
function mergeDraws(key: string, draws: readonly SceneDraw[], scene: ShardScene, tiles: Map<string, Map<string, Merge>>): void {
|
|
103
|
+
const p = new Vector3(), n = new Vector3(), world = new Matrix4(), local = new Matrix4(), normalMatrix = new Matrix3();
|
|
104
|
+
for (const draw of draws) {
|
|
105
|
+
const geometry = scene.geometries[draw.geometry], material = scene.materials[draw.material];
|
|
106
|
+
if (geometry === undefined || material === undefined) continue;
|
|
107
|
+
const base = new Matrix4().fromArray(draw.matrix), copies = draw.instances?.count ?? 1;
|
|
108
|
+
for (let copy = 0; copy < copies; copy++) {
|
|
109
|
+
world.copy(base); if (draw.instances !== null) world.multiply(local.fromArray(draw.instances.matrices, copy * 16));
|
|
110
|
+
normalMatrix.getNormalMatrix(world);
|
|
111
|
+
const flip = world.determinant() < 0;
|
|
112
|
+
const tint = draw.instances?.colours ? new Vector3(draw.instances.colours[copy * 3] ?? 1, draw.instances.colours[copy * 3 + 1] ?? 1, draw.instances.colours[copy * 3 + 2] ?? 1) : new Vector3(1, 1, 1);
|
|
113
|
+
appendCopy(geometry, material, world, normalMatrix, flip, tint, key, tiles, p, n, draw.motion?.kind === 'sway' ? draw.motion.amount : 0);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** AP15: one instanced draw's copies in one tile: its base geometry (local, uvs and vertex colours as the merge writes
|
|
119
|
+
* them) once, each copy's world matrix and its colour. */
|
|
120
|
+
interface InstancedGroup { key: string; geometry: BufferGeometry; matrices: Matrix4[]; colours: Color[] | null; castShadow: boolean; box: Box3 }
|
|
121
|
+
/** The fewest copies a draw needs to stay instanced (below it the merge is as small). */
|
|
122
|
+
const INSTANCE_MIN = 2, INSTANCE_CAP = 10_000;
|
|
123
|
+
|
|
124
|
+
/** A copy the engine's loader can place: translation, rotation and a positive scale, no shear (the loader reads instance
|
|
125
|
+
* TRS rows; an exact `_MATRIX` row loads as the identity there). */
|
|
126
|
+
function isTrs(matrix: Matrix4): boolean {
|
|
127
|
+
const position = new Vector3(), rotation = new Quaternion(), scale = new Vector3();
|
|
128
|
+
matrix.decompose(position, rotation, scale);
|
|
129
|
+
const composed = new Matrix4().compose(position, rotation, scale);
|
|
130
|
+
return scale.x > 0 && scale.y > 0 && scale.z > 0 && matrix.elements.every((n, i) => Number.isFinite(n) && Math.abs(n - (composed.elements[i] ?? Infinity)) <= 1e-6);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** AP15: an `InstancedMesh` with no motion as per-tile instance groups, or null when a copy is mirrored or sheared (the
|
|
134
|
+
* merge takes it). Instance colours over 1 are folded into the base colours (glTF instance colours are 0 to 1). */
|
|
135
|
+
function instanceGroups(key: string, draw: SceneDraw, scene: ShardScene): Map<string, InstancedGroup> | null {
|
|
136
|
+
const geometry = scene.geometries[draw.geometry], material = scene.materials[draw.material], instances = draw.instances;
|
|
137
|
+
if (geometry === undefined || material === undefined || instances === null) return null;
|
|
138
|
+
const base = new Matrix4().fromArray(draw.matrix), worlds: Matrix4[] = [];
|
|
139
|
+
for (let copy = 0; copy < instances.count; copy++) {
|
|
140
|
+
const world = base.clone().multiply(new Matrix4().fromArray(instances.matrices, copy * 16));
|
|
141
|
+
if (!(world.determinant() > 0) || !isTrs(world)) return null;
|
|
142
|
+
worlds.push(world);
|
|
143
|
+
}
|
|
144
|
+
const tints = instances.colours; let peak = 1; if (tints !== null) for (const tint of tints) peak = Math.max(peak, tint);
|
|
145
|
+
const count = geometry.position.length / 3, uv = new Float32Array(count * 2), colour = new Float32Array(count * 3);
|
|
146
|
+
for (let at = 0; at < count; at++) {
|
|
147
|
+
uv[at * 2] = (geometry.uv?.[at * 2] ?? 0) * material.repeat[0] + material.offset[0];
|
|
148
|
+
uv[at * 2 + 1] = (geometry.uv?.[at * 2 + 1] ?? 0) * material.repeat[1] + material.offset[1];
|
|
149
|
+
for (let c = 0; c < 3; c++) colour[at * 3 + c] = (material.vertexColours && geometry.colour !== null ? geometry.colour[at * 3 + c] ?? 1 : 1) * peak;
|
|
150
|
+
}
|
|
151
|
+
const shape = new BufferGeometry().setAttribute('position', new Float32BufferAttribute(geometry.position, 3)).setAttribute('normal', new Float32BufferAttribute(geometry.normal, 3))
|
|
152
|
+
.setAttribute('uv', new Float32BufferAttribute(uv, 2)).setAttribute('color', new BufferAttribute(colour, 3));
|
|
153
|
+
if (geometry.index !== null) shape.setIndex([...geometry.index]);
|
|
154
|
+
shape.computeBoundingBox();
|
|
155
|
+
const local = shape.boundingBox ?? new Box3(), groups = new Map<string, InstancedGroup>();
|
|
156
|
+
worlds.forEach((world, copy) => {
|
|
157
|
+
const tile = `${tileOf(world.elements[12] ?? 0)}/${tileOf(world.elements[14] ?? 0)}`;
|
|
158
|
+
let group = groups.get(tile);
|
|
159
|
+
if (group === undefined) { group = { key, geometry: shape, matrices: [], colours: tints === null ? null : [], castShadow: draw.castShadow, box: new Box3() }; groups.set(tile, group); }
|
|
160
|
+
group.matrices.push(world);
|
|
161
|
+
if (tints !== null) group.colours?.push(new Color((tints[copy * 3] ?? 1) / peak, (tints[copy * 3 + 1] ?? 1) / peak, (tints[copy * 3 + 2] ?? 1) / peak));
|
|
162
|
+
group.box.union(local.clone().applyMatrix4(world));
|
|
163
|
+
});
|
|
164
|
+
return groups;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function appendCopy(geometry: SceneGeometry, material: SceneMaterial, world: Matrix4, normalMatrix: Matrix3, flip: boolean, tint: Vector3, key: string, tiles: Map<string, Map<string, Merge>>, p: Vector3, n: Vector3, sway = 0): void {
|
|
168
|
+
const count = geometry.index?.length ?? geometry.position.length / 3;
|
|
169
|
+
// AP12: sway grows with the square of the height over the geometry's own bounds (0 at its root)
|
|
170
|
+
let low = Infinity, high = -Infinity;
|
|
171
|
+
if (sway > 0) for (let i = 1; i < geometry.position.length; i += 3) { const y = geometry.position[i] ?? 0; low = Math.min(low, y); high = Math.max(high, y); }
|
|
172
|
+
const swayAt = (at: number): number => (sway > 0 && high > low ? sway * (((geometry.position[at * 3 + 1] ?? low) - low) / (high - low)) ** 2 : 0);
|
|
173
|
+
const vertex = (at: number): Vertex => ({ // world-space corner
|
|
174
|
+
p: p.fromArray(geometry.position, at * 3).applyMatrix4(world).clone(),
|
|
175
|
+
n: n.fromArray(geometry.normal, at * 3).applyMatrix3(normalMatrix).normalize().clone(),
|
|
176
|
+
u: (geometry.uv?.[at * 2] ?? 0) * material.repeat[0] + material.offset[0], v: (geometry.uv?.[at * 2 + 1] ?? 0) * material.repeat[1] + material.offset[1],
|
|
177
|
+
c: (material.vertexColours && geometry.colour !== null ? new Vector3().fromArray(geometry.colour, at * 3) : new Vector3(1, 1, 1)).multiply(tint),
|
|
178
|
+
s: swayAt(at),
|
|
179
|
+
});
|
|
180
|
+
const mergeOf = (tile: string): Merge => {
|
|
181
|
+
const merges = tiles.get(tile) ?? new Map<string, Merge>(); tiles.set(tile, merges);
|
|
182
|
+
const merge = merges.get(key) ?? emptyMerge(); merges.set(key, merge);
|
|
183
|
+
return merge;
|
|
184
|
+
};
|
|
185
|
+
const push = (merge: Merge, corner: Vertex): number => {
|
|
186
|
+
merge.position.push(corner.p.x, corner.p.y, corner.p.z); merge.normal.push(corner.n.x, corner.n.y, corner.n.z);
|
|
187
|
+
merge.uv.push(corner.u, corner.v); merge.colour.push(corner.c.x, corner.c.y, corner.c.z); merge.sway.push(corner.s);
|
|
188
|
+
return merge.position.length / 3 - 1;
|
|
189
|
+
};
|
|
190
|
+
const vertexCount = geometry.position.length / 3, corners = Array.from({ length: vertexCount }, (_, at) => vertex(at));
|
|
191
|
+
const xs = corners.map((c) => tileOf(c.p.x)), zs = corners.map((c) => tileOf(c.p.z));
|
|
192
|
+
const order = (i: number): [number, number, number] => {
|
|
193
|
+
const a = geometry.index?.[i] ?? i, b = geometry.index?.[i + 1] ?? i + 1, c = geometry.index?.[i + 2] ?? i + 2;
|
|
194
|
+
return flip ? [a, c, b] : [a, b, c];
|
|
195
|
+
};
|
|
196
|
+
if (xs.every((x) => x === xs[0]) && zs.every((z) => z === zs[0])) {
|
|
197
|
+
// the whole copy is in one tile: its vertices once, its index offset
|
|
198
|
+
const merge = mergeOf(`${xs[0] ?? 0}/${zs[0] ?? 0}`), base = merge.position.length / 3;
|
|
199
|
+
for (const corner of corners) push(merge, corner);
|
|
200
|
+
for (let i = 0; i < count; i += 3) merge.index.push(...order(i).map((at) => at + base));
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
for (let i = 0; i < count; i += 3) {
|
|
204
|
+
const ids = order(i), triangle = ids.map((at) => corners[at]).filter((c) => c !== undefined);
|
|
205
|
+
const txs = ids.map((at) => xs[at] ?? 0), tzs = ids.map((at) => zs[at] ?? 0);
|
|
206
|
+
for (let x = Math.min(...txs); x <= Math.max(...txs); x++) for (let z = Math.min(...tzs); z <= Math.max(...tzs); z++) {
|
|
207
|
+
const polygon = txs.every((value) => value === x) && tzs.every((value) => value === z) ? triangle : clipToTile(triangle, x, z);
|
|
208
|
+
if (polygon.length < 3) continue;
|
|
209
|
+
const merge = mergeOf(`${x}/${z}`), at = polygon.map((corner) => push(merge, corner));
|
|
210
|
+
for (let k = 1; k + 1 < at.length; k++) merge.index.push(at[0] ?? 0, at[k] ?? 0, at[k + 1] ?? 0);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** AP11: one camera-facing quad per card, into its seat's tile: `position` the seat, `_CORNER` the view-space offset. */
|
|
216
|
+
function appendCard(key: string, seat: readonly [number, number, number], size: readonly [number, number], centre: readonly [number, number], tiles: Map<string, Map<string, Merge>>): void {
|
|
217
|
+
const tile = `${tileOf(seat[0])}/${tileOf(seat[2])}`, merges = tiles.get(tile) ?? new Map<string, Merge>(); tiles.set(tile, merges);
|
|
218
|
+
const merge = merges.get(key) ?? emptyMerge(); merges.set(key, merge);
|
|
219
|
+
const base = merge.position.length / 3;
|
|
220
|
+
for (const [u, v] of [[0, 0], [1, 0], [1, 1], [0, 1]] as const) {
|
|
221
|
+
merge.position.push(seat[0], seat[1], seat[2]); merge.normal.push(0, 0, 1); merge.uv.push(u, v); merge.colour.push(1, 1, 1); merge.sway.push(0);
|
|
222
|
+
merge.corner.push((u - centre[0]) * size[0], (v - centre[1]) * size[1]);
|
|
223
|
+
}
|
|
224
|
+
merge.index.push(base, base + 1, base + 2, base, base + 2, base + 3);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** A merge cut into primitives of at most 200,000 vertices, each with its own compact vertex list. */
|
|
228
|
+
/** One entry's merge as GLB primitives: a card's corners and a swaying surface's amplitude ride their own channels (AP11, AP12). */
|
|
229
|
+
function primitivesOf(merge: Merge, entry: Entry, name: string, castShadow: boolean): GlbPrimitive[] {
|
|
230
|
+
const swaying = entry.motion?.kind === 'sway';
|
|
231
|
+
return chunks(merge).map((chunk) => {
|
|
232
|
+
const geometry = new BufferGeometry().setAttribute('position', new Float32BufferAttribute(chunk.position, 3)).setAttribute('normal', new Float32BufferAttribute(chunk.normal, 3))
|
|
233
|
+
.setAttribute('uv', new Float32BufferAttribute(chunk.uv, 2)).setAttribute('color', new BufferAttribute(new Float32Array(chunk.colour), 3)).setIndex(chunk.index);
|
|
234
|
+
if (entry.card) geometry.setAttribute('corner', new Float32BufferAttribute(chunk.corner, 2));
|
|
235
|
+
if (swaying) geometry.setAttribute('sway', new Float32BufferAttribute(chunk.sway, 1));
|
|
236
|
+
const material = new MeshStandardMaterial({ color: 0xffffff, vertexColors: true }); material.name = name;
|
|
237
|
+
const primitive: GlbPrimitive = { geometry, material, castShadow: entry.card ? false : castShadow };
|
|
238
|
+
if (entry.card) primitive.customAttributes = { _CORNER: 'corner' }; else if (swaying) primitive.customAttributes = { _SWAY: 'sway' };
|
|
239
|
+
return primitive;
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** AP16: what the library roots cost with their dependencies (format asset admission's `budgets.library` check). */
|
|
244
|
+
function libraryCost(files: Shardfile['files'], roots: readonly string[]): { resident: number; compressed: number } {
|
|
245
|
+
const byHash = new Map(files.map((f) => [f.hash, f])), seen = new Set<string>(), pending = [...roots];
|
|
246
|
+
let resident = 0, compressed = 0;
|
|
247
|
+
while (pending.length > 0) {
|
|
248
|
+
const hash = pending.pop(); if (hash === undefined || seen.has(hash)) continue;
|
|
249
|
+
seen.add(hash); const file = byHash.get(hash); if (file === undefined) continue;
|
|
250
|
+
resident += file.decoded + file.gpu; compressed += file.compressed; pending.push(...file.dependencies);
|
|
251
|
+
}
|
|
252
|
+
return { resident, compressed };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function chunks(merge: Merge, limit = 200_000): Merge[] {
|
|
256
|
+
if (merge.position.length / 3 <= limit) return [merge];
|
|
257
|
+
const out: Merge[] = []; let current: Merge | null = null, remap = new Map<number, number>();
|
|
258
|
+
for (let i = 0; i < merge.index.length; i += 3) {
|
|
259
|
+
if (current === null || current.position.length / 3 + 3 > limit) { current = emptyMerge(); out.push(current); remap = new Map(); }
|
|
260
|
+
for (let k = 0; k < 3; k++) {
|
|
261
|
+
const from = merge.index[i + k] ?? 0; let to = remap.get(from);
|
|
262
|
+
if (to === undefined) {
|
|
263
|
+
to = current.position.length / 3; remap.set(from, to);
|
|
264
|
+
current.position.push(...merge.position.slice(from * 3, from * 3 + 3)); current.normal.push(...merge.normal.slice(from * 3, from * 3 + 3));
|
|
265
|
+
current.uv.push(...merge.uv.slice(from * 2, from * 2 + 2)); current.colour.push(...merge.colour.slice(from * 3, from * 3 + 3));
|
|
266
|
+
current.sway.push(merge.sway[from] ?? 0); current.corner.push(...merge.corner.slice(from * 2, from * 2 + 2));
|
|
267
|
+
}
|
|
268
|
+
current.index.push(to);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** A collider box row: yaw-only rotations keep their yaw; any other tilt becomes its world bounding box. */
|
|
275
|
+
function boxRow(collider: SceneCollider): { kind: 'box'; x: number; y: number; z: number; hx: number; hy: number; hz: number; yaw?: number } {
|
|
276
|
+
const q = new Quaternion(...collider.rotation), up = new Vector3(0, 1, 0).applyQuaternion(q);
|
|
277
|
+
const [x, y, z] = collider.centre.map((value) => round(value, 3)) as [number, number, number];
|
|
278
|
+
if (up.y > 0.9999) {
|
|
279
|
+
const forward = new Vector3(1, 0, 0).applyQuaternion(q), yaw = round(Math.atan2(-forward.z, forward.x), 4);
|
|
280
|
+
return { kind: 'box', x, y, z, hx: round(collider.half[0], 3), hy: round(collider.half[1], 3), hz: round(collider.half[2], 3), ...(yaw === 0 ? {} : { yaw }) };
|
|
281
|
+
}
|
|
282
|
+
const half = new Vector3(...collider.half), extent = new Vector3();
|
|
283
|
+
// world AABB of the oriented box: sum of |R| * half per axis
|
|
284
|
+
const m = new Matrix4().makeRotationFromQuaternion(q).elements;
|
|
285
|
+
extent.set(
|
|
286
|
+
Math.abs(m[0] ?? 0) * half.x + Math.abs(m[4] ?? 0) * half.y + Math.abs(m[8] ?? 0) * half.z,
|
|
287
|
+
Math.abs(m[1] ?? 0) * half.x + Math.abs(m[5] ?? 0) * half.y + Math.abs(m[9] ?? 0) * half.z,
|
|
288
|
+
Math.abs(m[2] ?? 0) * half.x + Math.abs(m[6] ?? 0) * half.y + Math.abs(m[10] ?? 0) * half.z);
|
|
289
|
+
return { kind: 'box', x, y, z, hx: round(extent.x, 3), hy: round(extent.y, 3), hz: round(extent.z, 3) };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Point lights as the look's lamp rows (`look.light.lamps`): what a baked shard and a watched part (the dev hook) both draw. */
|
|
293
|
+
export function lampRows(lights: readonly SceneLight[]): { at: [number, number, number]; colour: [number, number, number]; intensity: number; distance: number; decay?: number; flicker?: { rate: number; amount: number } }[] {
|
|
294
|
+
type LampRow = ReturnType<typeof lampRows>[number];
|
|
295
|
+
const rows: LampRow[] = [];
|
|
296
|
+
for (const l of lights) {
|
|
297
|
+
if (l.kind !== 'point') continue;
|
|
298
|
+
const row: LampRow = { at: [round(l.position[0], 3), round(l.position[1], 3), round(l.position[2], 3)], colour: rgb01(l.colour), intensity: round(Math.min(100, l.intensity), 3),
|
|
299
|
+
distance: round(Math.min(50, Math.max(0.1, l.distance === 0 ? 50 : l.distance)), 3) };
|
|
300
|
+
if (l.decay !== 2) row.decay = round(clamp01(l.decay / 2) * 2, 3);
|
|
301
|
+
// AP12: the light's declared flicker, played by the engine's lamps (format `lamps[].flicker`)
|
|
302
|
+
if (l.motion?.kind === 'flicker') row.flicker = { rate: round(Math.min(30, l.motion.rate), 3), amount: round(clamp01(l.motion.amount), 3) };
|
|
303
|
+
rows.push(row);
|
|
304
|
+
}
|
|
305
|
+
return rows;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** A part's `Water` surfaces as the shardfile's water rows (AP4): the outline is the Water's own geometry. */
|
|
309
|
+
export function waterRows(part: ScenePart): { id: string; kind: 'pool'; level: number; shape: { kind: 'polygon'; points: [number, number][] }; surface: PoolSurface }[] {
|
|
310
|
+
return part.water.map((w, i) => ({
|
|
311
|
+
id: `scene.${part.name}.water${i === 0 ? '' : `-${i}`}`, kind: 'pool', level: round(w.level, 3),
|
|
312
|
+
shape: { kind: 'polygon', points: w.outline.map(([px, pz]) => [round(px, 3), round(pz, 3)]) },
|
|
313
|
+
// AP14: the Water's own reflection and deep tint (format pool-surface, TEMPLATES-CLEANROOM M4.6): the cleanroom pond's
|
|
314
|
+
// Fresnel 0.35 + 0.65 (1 - v.y)^3 and its 1024 mirror; a planar mirror shows the painted sky, a phone's sky reflection too
|
|
315
|
+
surface: { reflect: w.reflect, tint: rgb01(w.tint), fresnel: [0.35, 3], ripple: { scale: 3, amplitude: 0.0022, speed: 1 }, resolution: 1024 },
|
|
316
|
+
}));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** The look a scene declares (AP3), over the format's day-key model fixed at one time of day. The engine sets its
|
|
320
|
+
* hemisphere light's intensity to the ambient key's (engine `dataLook.ts`), so the key is the HemisphereLight's own
|
|
321
|
+
* number (ss4d: it was x pi, a ground three times brighter than its cleanroom's). */
|
|
322
|
+
export function sceneLook(scene: ShardScene, lights: readonly SceneLight[], materials: Record<string, unknown>): Shardfile['look'] {
|
|
323
|
+
const directional = lights.filter((l) => l.kind === 'directional').sort((a, b) => b.intensity - a.intensity);
|
|
324
|
+
const sun = directional[0], hemisphere = lights.find((l) => l.kind === 'hemisphere'), ambient = lights.find((l) => l.kind === 'ambient');
|
|
325
|
+
const lamps = lights.filter((l) => l.kind === 'point').sort((a, b) => b.intensity - a.intensity).slice(0, 16);
|
|
326
|
+
// the sun's heading and height from its position over its target
|
|
327
|
+
const toSun = sun === undefined ? new Vector3(0.3, 1, 0.4) : new Vector3(...sun.position).sub(new Vector3(...sun.target ?? [0, 0, 0]));
|
|
328
|
+
toSun.normalize();
|
|
329
|
+
const elevation = Math.asin(clamp01(toSun.y)) * 180 / Math.PI, azimuth = Math.atan2(toSun.x, -toSun.z) * 180 / Math.PI;
|
|
330
|
+
const fog = scene.look.fog, post = scene.look.post, sky = scene.look.sky ?? null;
|
|
331
|
+
const skyColour: Rgb = hemisphere?.colour ?? ambient?.colour ?? [0.5, 0.5, 0.6], groundColour: Rgb = hemisphere?.groundColour ?? skyColour;
|
|
332
|
+
const fogColour: Rgb = fog?.colour ?? scene.look.background ?? skyColour;
|
|
333
|
+
return {
|
|
334
|
+
families: ['pbr', 'emissive'], materials: materials as Shardfile['look']['materials'],
|
|
335
|
+
...(post?.passes === undefined || post.passes.length === 0 ? {} : { post: post.passes.map((graph) => ({ graph })) }),
|
|
336
|
+
// AP14: the painted sky on the dome; the engine filters its environment from the same dome
|
|
337
|
+
...(sky === null ? {} : { sky: { graph: sky.graph } }),
|
|
338
|
+
grade: { exposure: round(Math.log2(post?.exposure ?? 1), 3), saturation: 1, contrast: 1, lut: null,
|
|
339
|
+
...(post?.bloom === null || post?.bloom === undefined ? {} : { bloom: { intensity: round(Math.min(4, post.bloom.strength * 1.5), 3), threshold: round(post.bloom.threshold, 3), radius: round(clamp01(post.bloom.radius), 3) } }),
|
|
340
|
+
...(post?.tone === 'neutral' || post?.tone === 'aces' ? { tone: post.tone } : {}) },
|
|
341
|
+
clock: 'engine', day: { minutes: 12, start: 0.5, maxElevation: round(Math.max(5, elevation), 2), azimuth: round(azimuth, 2) }, dayOverride: 0.5,
|
|
342
|
+
keys: [{ time: 0, sky: { zenith: rgb01(skyColour), horizon: rgb01(fogColour) },
|
|
343
|
+
fog: fog?.kind === 'linear' ? { colour: rgb01(fog.colour), density: 0, near: fog.near, far: fog.far } : { colour: rgb01(fogColour), density: round(fog?.kind === 'exp2' ? fog.density : 0, 5) },
|
|
344
|
+
sun: { colour: rgb01(sun?.colour ?? [1, 1, 1]), intensity: round(sun?.intensity ?? 0, 3) },
|
|
345
|
+
ambient: { sky: rgb01(skyColour), ground: rgb01(groundColour), intensity: round(hemisphere?.intensity ?? ambient?.intensity ?? 0.5, 3) } }],
|
|
346
|
+
light: { ...(lamps.length === 0 ? {} : { lamps: lampRows(lamps) }),
|
|
347
|
+
...(sky?.environment === null || sky === null ? {} : { environment: { intensity: round(Math.min(4, sky.environment.intensity), 3), ground: rgb01(sky.environment.ground) } }) },
|
|
348
|
+
} as Shardfile['look'];
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** A linear HDR colour as an sRGB tint (0..1) and the gain that restores it. */
|
|
352
|
+
function tintAndGain(colour: Rgb): { tint: [number, number, number]; gain: number } {
|
|
353
|
+
const peak = Math.max(colour[0], colour[1], colour[2], 1e-6);
|
|
354
|
+
return { tint: srgb01([colour[0] / peak, colour[1] / peak, colour[2] / peak]), gain: peak };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** A card's motion as the format's (AP12): only a card's kinds reach here. */
|
|
358
|
+
function cardMotion(motion: SceneMotion | null): Record<string, unknown> {
|
|
359
|
+
if (motion === null) return {};
|
|
360
|
+
if (motion.kind === 'pulse') return { motion: { kind: 'pulse', rate: round(Math.min(30, motion.rate), 3), amount: round(clamp01(motion.amount), 3) } };
|
|
361
|
+
if (motion.kind === 'drift') return { motion: { kind: 'drift', rate: round(Math.min(30, motion.rate), 3), radius: round(Math.min(10, motion.radius), 3) } };
|
|
362
|
+
if (motion.kind === 'rise') return { motion: { kind: 'rise', rate: round(Math.min(30, motion.rate), 3), height: round(Math.min(50, motion.height), 3), spread: round(Math.min(10, motion.spread), 3) } };
|
|
363
|
+
return {};
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* A look.materials entry for one scene material (AP2, AP10 to AP12): pbr for lit surfaces (with their own glow, alpha,
|
|
368
|
+
* decal offset, sway and uv scroll), emissive for unlit ones, an emissive card for a sprite or a point.
|
|
369
|
+
*/
|
|
370
|
+
function materialEntry({ material, motion, card }: Entry): Record<string, unknown> {
|
|
371
|
+
const doubleSided = material.side === 'double' ? { doubleSided: true } : {};
|
|
372
|
+
if (material.entry !== null) return { ...material.entry };
|
|
373
|
+
if (card) {
|
|
374
|
+
const { tint, gain } = tintAndGain(material.colour);
|
|
375
|
+
return { family: 'emissive', card: true, colour: tint, intensity: round(Math.min(64, gain * material.opacity), 3), blend: material.blending === 'additive' ? 'additive' : 'alpha',
|
|
376
|
+
fog: material.fog ? 1 : 0, ...cardMotion(motion) };
|
|
377
|
+
}
|
|
378
|
+
if (material.kind === 'basic') {
|
|
379
|
+
const { tint, gain } = tintAndGain(material.colour);
|
|
380
|
+
return { family: 'emissive', colour: tint, intensity: round(Math.min(64, gain * (material.blending === 'additive' ? material.opacity : 1)), 3), vertexColours: true, ...doubleSided,
|
|
381
|
+
...(material.blending === 'additive' ? { blend: 'additive' } : material.transparent ? { blend: 'alpha' } : {}), ...(material.fog ? {} : { fog: 0 }) };
|
|
382
|
+
}
|
|
383
|
+
const glow = luminance(material.emissive) * material.emissiveIntensity, emissive = glow > 0 ? tintAndGain(material.emissive) : null;
|
|
384
|
+
const alpha = material.transparent && material.blending === 'normal';
|
|
385
|
+
return { family: 'pbr', colour: srgb01(material.colour), roughness: round(clamp01(material.roughness), 3), metalness: round(clamp01(material.metalness), 3), vertexColours: true, ...doubleSided,
|
|
386
|
+
...(material.alphaTest > 0 ? { alphaCutoff: round(clamp01(material.alphaTest), 3) } : {}),
|
|
387
|
+
// M4.3: a lit surface's own glow (lamp glass, candles) stays lit by the sun and lamps
|
|
388
|
+
...(emissive === null ? {} : { emissive: emissive.tint, emissiveIntensity: round(Math.min(64, emissive.gain * material.emissiveIntensity), 3) }),
|
|
389
|
+
// AP10: a see-through surface sorts after the opaque world; a polygon offset pulls a decal off its wall
|
|
390
|
+
...(alpha ? { blend: 'alpha', ...(material.opacity < 1 ? { opacity: round(clamp01(material.opacity), 3) } : {}) } : {}),
|
|
391
|
+
...(material.polygonOffset === 0 ? {} : { depthOffset: round(Math.min(16, Math.max(-16, material.polygonOffset)), 3) }),
|
|
392
|
+
// AP12: wind sway (its amplitude rides the _SWAY channel) and a scrolling map
|
|
393
|
+
...(motion?.kind === 'sway' ? { sway: { rate: round(Math.min(8, motion.rate), 3), direction: [round(Math.max(-1, Math.min(1, motion.direction[0])), 3), round(Math.max(-1, Math.min(1, motion.direction[1])), 3)] } } : {}),
|
|
394
|
+
...(motion?.kind === 'uvScroll' ? { uvScroll: [round(Math.max(-10, Math.min(10, motion.u)), 4), round(Math.max(-10, Math.min(10, motion.v)), 4)] } : {}) };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** ss4d: the ground's PBR entry: its vertex colours (`colourAt`, linear) times the material's colour, lit as the cleanroom's
|
|
398
|
+
* ground mesh is; a flat cell is a plain rough surface. */
|
|
399
|
+
export function groundEntry(scene: Pick<ShardScene, 'ground'>): Record<string, unknown> {
|
|
400
|
+
const surface = scene.ground?.surface ?? { colour: [1, 1, 1] as Rgb, roughness: 1, metalness: 0, detail: null };
|
|
401
|
+
return { family: 'pbr', colour: srgb01(surface.colour), roughness: round(clamp01(surface.roughness), 3), metalness: round(clamp01(surface.metalness), 3), vertexColours: true,
|
|
402
|
+
...(surface.detail === null ? {} : { detail: surface.detail }) };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** What the shardfile back end did not write, for the build log (never silent). */
|
|
406
|
+
export interface ShardfileReport { readonly cards: number; readonly lampsDropped: number; readonly tiles: readonly { tile: string; triangles: number; draws: number; bytes: number }[] }
|
|
407
|
+
|
|
408
|
+
/** The shardfile back end: the description in, a generated project out. Runs at compile time. */
|
|
409
|
+
export function compileShardfile(scene: ShardScene, ctx: ProjectGenerationContext, options: ShardfileOptions = {}): Promise<GeneratedProject> {
|
|
410
|
+
const { shard, assets, report } = sceneShardfile(scene, options);
|
|
411
|
+
for (const [hash, bytes] of assets) if (ctx.asset(bytes) !== hash) throw new Error('scene: an asset hash differs from the product store');
|
|
412
|
+
if (report.lampsDropped > 0) console.info(`scene: ${report.lampsDropped} point lights past the 16 brightest are not in the shardfile (AP28)`);
|
|
413
|
+
// AP8: draws are a view's budget now (the engine draws a material once across tiles; format VIEW_DRAWS), not a tile's
|
|
414
|
+
const over = report.tiles.filter((t) => t.triangles > 40_000);
|
|
415
|
+
if (over.length > 0) console.info(`scene: ${over.length} tiles are over the phone tile triangle cap (J338; AP9 turns this into a per-part table): ${over.map((t) => `${t.tile} ${t.triangles} tris ${t.draws} draws`).join(', ')}`);
|
|
416
|
+
return Promise.resolve({ shard, output: {} });
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** The pure half of the back end: shardfile rows and asset bytes by hash. */
|
|
420
|
+
export function sceneShardfile(scene: ShardScene, options: ShardfileOptions = {}): { shard: Shardfile; assets: Map<string, Uint8Array>; report: ShardfileReport } {
|
|
421
|
+
const assets = new Map<string, Uint8Array>(), files: Shardfile['files'] = [];
|
|
422
|
+
const store = (bytes: Uint8Array, kind: 'glb' | 'ktx2', dependencies: string[] = []): Shardfile['files'][number] => {
|
|
423
|
+
const hash = hashImmutableBytes(bytes), cost = kind === 'glb' ? parseGlb(bytes) : parseKtx2(bytes);
|
|
424
|
+
const row = { hash, kind, compressed: bytes.length, ...cost, dependencies, critical: false };
|
|
425
|
+
if (!assets.has(hash)) { assets.set(hash, bytes); files.push(row); }
|
|
426
|
+
return files.find((f) => f.hash === hash) ?? row;
|
|
427
|
+
};
|
|
428
|
+
// ground (AP4): the declared height field, or a flat cell
|
|
429
|
+
const ground = scene.ground;
|
|
430
|
+
const terrain = bakeTerrain({ ...groundSource(scene), family: GROUND_MATERIAL });
|
|
431
|
+
for (const [hash, bytes] of terrain.assets) assets.set(hash, bytes);
|
|
432
|
+
files.push(...terrain.files);
|
|
433
|
+
|
|
434
|
+
// textures (AP2): RGBA8 KTX2, one file per painted raster
|
|
435
|
+
const textureFiles = new Map<string, Shardfile['files'][number]>();
|
|
436
|
+
// only the textures a drawn material or a card samples
|
|
437
|
+
const sampled = new Set(scene.parts.flatMap((part) => [...part.draws.map((d) => d.material), ...part.sprites.map((c) => c.material), ...part.points.map((c) => c.material)].map((key) => scene.materials[key]?.map)).filter((key) => typeof key === 'string'));
|
|
438
|
+
for (const texture of Object.values(scene.textures).filter((t) => sampled.has(t.key))) {
|
|
439
|
+
const bytes = bakeRawColourPixels({ width: texture.width, height: texture.height, pixels: new Uint8ClampedArray(texture.rgba) }, { colourSpace: texture.colourSpace });
|
|
440
|
+
textureFiles.set(texture.key, store(bytes, 'ktx2'));
|
|
441
|
+
}
|
|
442
|
+
// static parts (AP2): merged per entry (a material and the motion its draws declare) per tile
|
|
443
|
+
const draws = scene.parts.filter((part) => part.panel === undefined).flatMap((part) => part.draws), byEntry = new Map<string, SceneDraw[]>(), entries = new Map<string, Entry>();
|
|
444
|
+
const entryOf = (material: string, motion: SceneMotion | null, card = false): string | null => {
|
|
445
|
+
const found = scene.materials[material]; if (found === undefined) return null;
|
|
446
|
+
const key = entryKey(material, motion, card); if (!entries.has(key)) entries.set(key, { material: found, motion, card }); return key;
|
|
447
|
+
};
|
|
448
|
+
const instanced = new Map<string, InstancedGroup[]>();
|
|
449
|
+
for (const draw of draws) {
|
|
450
|
+
const key = entryOf(draw.material, draw.motion); if (key === null) continue;
|
|
451
|
+
// AP15: a still InstancedMesh stays instanced, its copies in the tiles of their seats
|
|
452
|
+
const groups = draw.motion === null && (draw.instances?.count ?? 0) >= INSTANCE_MIN ? instanceGroups(key, draw, scene) : null;
|
|
453
|
+
if (groups !== null) { for (const [tile, group] of groups) { const list = instanced.get(tile) ?? []; list.push(group); instanced.set(tile, list); } continue; }
|
|
454
|
+
const list = byEntry.get(key) ?? []; list.push(draw); byEntry.set(key, list);
|
|
455
|
+
}
|
|
456
|
+
const tiles = new Map<string, Map<string, Merge>>();
|
|
457
|
+
for (const [key, list] of byEntry) mergeDraws(key, list, scene, tiles);
|
|
458
|
+
// cards (AP11): every sprite and every point a camera-facing quad in its seat's tile
|
|
459
|
+
let cards = 0;
|
|
460
|
+
for (const part of scene.parts) {
|
|
461
|
+
for (const sprite of part.sprites) { const key = entryOf(sprite.material, sprite.motion, true); if (key === null) continue; appendCard(key, sprite.position, sprite.scale, sprite.center, tiles); cards++; }
|
|
462
|
+
for (const cloud of part.points) {
|
|
463
|
+
const key = entryOf(cloud.material, cloud.motion, true), size = (scene.materials[cloud.material]?.pointSize ?? 0) * POINT_CARD; if (key === null) continue;
|
|
464
|
+
for (let i = 0; i < cloud.positions.length; i += 3) { appendCard(key, [cloud.positions[i] ?? 0, cloud.positions[i + 1] ?? 0, cloud.positions[i + 2] ?? 0], [size, size], [0.5, 0.5], tiles); cards++; }
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
// AP16: each panel part's entries, merged whole (the tile split only cuts its triangles; the panel is one GLB)
|
|
468
|
+
const panelParts = scene.parts.filter((part) => part.panel !== undefined).map((part) => {
|
|
469
|
+
const merges = new Map<string, Map<string, Merge>>(), shadows = new Map<string, boolean>(), byKey = new Map<string, SceneDraw[]>();
|
|
470
|
+
for (const draw of part.draws) {
|
|
471
|
+
const key = entryOf(draw.material, draw.motion); if (key === null) continue;
|
|
472
|
+
const list = byKey.get(key) ?? []; list.push(draw); byKey.set(key, list); shadows.set(key, (shadows.get(key) ?? false) || draw.castShadow);
|
|
473
|
+
}
|
|
474
|
+
for (const [key, list] of byKey) mergeDraws(key, list, scene, merges);
|
|
475
|
+
return { id: part.panel ?? part.name, merges, shadows };
|
|
476
|
+
});
|
|
477
|
+
const names = new Map<string, string>(), glbNames = new Map([...entries].map(([key, entry]) => [key, glbName({ ...entry.material, key, name: entry.card || entry.motion !== null ? `${entry.material.name}-${key.slice(entry.material.key.length + 1)}` : entry.material.name }, names)]));
|
|
478
|
+
const casts = new Map<string, boolean>(); for (const draw of draws) { const key = entryKey(draw.material, draw.motion); casts.set(key, (casts.get(key) ?? false) || draw.castShadow); }
|
|
479
|
+
const lookMaterials: Record<string, unknown> = {}, propMaterials: Record<string, unknown> = {};
|
|
480
|
+
for (const [key, entry] of entries) {
|
|
481
|
+
const name = glbNames.get(key) ?? key, file = entry.material.map === null ? undefined : textureFiles.get(entry.material.map);
|
|
482
|
+
lookMaterials[lookId(key)] = materialEntry(entry);
|
|
483
|
+
propMaterials[name] = { id: lookId(key), ...(file === undefined ? {} : { colour: { file: file.hash, wrapS: 10497, wrapT: 10497, minFilter: 9987, magFilter: 9729, anisotropy: 4 } }) };
|
|
484
|
+
}
|
|
485
|
+
lookMaterials[GROUND_MATERIAL] = groundEntry(scene);
|
|
486
|
+
const shardTiles = terrain.tiles.map((t) => ({ ...t, files: [...t.files], bounds: { min: [...t.bounds.min] as [number, number, number], max: [...t.bounds.max] as [number, number, number] } }));
|
|
487
|
+
const propTiles: { lod: 0; x: number; z: number; file: string }[] = [], tileReport: { tile: string; triangles: number; draws: number; bytes: number }[] = [];
|
|
488
|
+
const addresses = [...new Set([...tiles.keys(), ...instanced.keys()])].sort((a, b) => a.localeCompare(b));
|
|
489
|
+
for (const address of addresses) {
|
|
490
|
+
const merges = tiles.get(address) ?? new Map<string, Merge>();
|
|
491
|
+
const [x = 0, z = 0] = address.split('/').map(Number);
|
|
492
|
+
const primitives: GlbPrimitive[] = [], dependencies = new Set<string>(), drawn = new Box3();
|
|
493
|
+
for (const [key, merge] of [...merges].sort(([p], [q]) => p.localeCompare(q))) {
|
|
494
|
+
const entry = entries.get(key), material = entry?.material; if (entry === undefined || material === undefined || merge.position.length === 0) continue;
|
|
495
|
+
for (const primitive of primitivesOf(merge, entry, glbNames.get(key) ?? key, casts.get(key) ?? true)) {
|
|
496
|
+
primitives.push(primitive);
|
|
497
|
+
// a card draws past its seats by its corners and its rise: the tile's drawn box holds that reach
|
|
498
|
+
const corner = primitive.geometry.getAttribute('corner');
|
|
499
|
+
if (entry.card && corner !== undefined) {
|
|
500
|
+
const geometry = primitive.geometry; geometry.computeBoundingBox(); let reach = 0; for (const c of corner.array) reach = Math.max(reach, Math.abs(c));
|
|
501
|
+
const motion = entry.motion; if (motion?.kind === 'rise') reach += motion.height + motion.spread; else if (motion?.kind === 'drift') reach += motion.radius;
|
|
502
|
+
if (geometry.boundingBox !== null) drawn.union(geometry.boundingBox.clone().expandByScalar(reach));
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
const file = material.map === null ? undefined : textureFiles.get(material.map); if (file !== undefined) dependencies.add(file.hash);
|
|
506
|
+
}
|
|
507
|
+
for (const primitive of primitives) { primitive.geometry.computeBoundingBox(); if (primitive.geometry.boundingBox !== null) drawn.union(primitive.geometry.boundingBox); }
|
|
508
|
+
// AP15: the tile's instance groups, at most INSTANCE_CAP copies a node
|
|
509
|
+
for (const group of instanced.get(address) ?? []) {
|
|
510
|
+
const entry = entries.get(group.key), material = entry?.material; if (entry === undefined || material === undefined) continue;
|
|
511
|
+
const glbMaterial = new MeshStandardMaterial({ color: 0xffffff, vertexColors: true }); glbMaterial.name = glbNames.get(group.key) ?? group.key;
|
|
512
|
+
for (let from = 0; from < group.matrices.length; from += INSTANCE_CAP) {
|
|
513
|
+
const colours = group.colours?.slice(from, from + INSTANCE_CAP);
|
|
514
|
+
primitives.push({ geometry: group.geometry, material: glbMaterial, castShadow: group.castShadow, instances: group.matrices.slice(from, from + INSTANCE_CAP), ...(colours === undefined ? {} : { instanceColours: colours }) });
|
|
515
|
+
}
|
|
516
|
+
drawn.union(group.box);
|
|
517
|
+
const file = material.map === null ? undefined : textureFiles.get(material.map); if (file !== undefined) dependencies.add(file.hash);
|
|
518
|
+
}
|
|
519
|
+
if (primitives.length === 0) continue;
|
|
520
|
+
// a GLB holds at most 25 MB (shard-format glbCost): batch the primitives into as many files as the tile needs
|
|
521
|
+
const batches: GlbPrimitive[][] = []; let batch: GlbPrimitive[] = [], bytes = 0;
|
|
522
|
+
for (const primitive of primitives) {
|
|
523
|
+
const size = primitive.geometry.getAttribute('position').count * 44 + (primitive.geometry.getIndex()?.count ?? 0) * 4 + (primitive.instances?.length ?? 0) * 76;
|
|
524
|
+
if (batch.length > 0 && bytes + size > 18_000_000) { batches.push(batch); batch = []; bytes = 0; }
|
|
525
|
+
batch.push(primitive); bytes += size;
|
|
526
|
+
}
|
|
527
|
+
batches.push(batch);
|
|
528
|
+
const rows = batches.map((list, i) => store(staticGlb(list, batches.length === 1 ? `scene.${x}.${z}` : `scene.${x}.${z}.${i}`), 'glb', [...dependencies].sort()));
|
|
529
|
+
const [first, ...more] = rows; if (first === undefined) continue;
|
|
530
|
+
propTiles.push({ lod: 0, x, z, file: first.hash, ...(more.length === 0 ? {} : { additionalFiles: more.map((r) => r.hash) }) });
|
|
531
|
+
const tile = shardTiles.find((t) => t.lod === 0 && t.x === x && t.z === z);
|
|
532
|
+
if (tile === undefined) throw new Error(`scene: no terrain tile 0/${x}/${z}`);
|
|
533
|
+
const textures = [...dependencies].map((hash) => files.find((f) => f.hash === hash)).filter((f) => f !== undefined);
|
|
534
|
+
tile.files.push(...rows.map((r) => r.hash), ...textures.map((f) => f.hash).filter((hash) => !tile.files.includes(hash)));
|
|
535
|
+
const sum = (pick: (f: Shardfile['files'][number]) => number): number => rows.reduce((n, f) => n + pick(f), 0) + textures.reduce((n, f) => n + pick(f), 0);
|
|
536
|
+
tile.compressed += sum((f) => f.compressed); tile.decoded += sum((f) => f.decoded); tile.gpu += sum((f) => f.gpu);
|
|
537
|
+
tile.triangles += rows.reduce((n, f) => n + f.triangles, 0); tile.draws += rows.reduce((n, f) => n + f.draws, 0);
|
|
538
|
+
if (!drawn.isEmpty()) {
|
|
539
|
+
tile.bounds.min[1] = Math.min(tile.bounds.min[1], drawn.min.y); tile.bounds.max[1] = Math.max(tile.bounds.max[1], drawn.max.y);
|
|
540
|
+
// AP15: an instanced copy is whole in its seat's tile, so it may hang over the tile's edge: its draw bounds say so
|
|
541
|
+
if (drawn.min.x < tile.bounds.min[0] || drawn.min.z < tile.bounds.min[2] || drawn.max.x > tile.bounds.max[0] || drawn.max.z > tile.bounds.max[2]) {
|
|
542
|
+
const low = (v: number): number => Math.max(-HALF - OVERHANG, Math.floor(v * 1000) / 1000), high = (v: number): number => Math.min(HALF + OVERHANG, Math.ceil(v * 1000) / 1000);
|
|
543
|
+
tile.drawBounds = { min: [low(Math.min(tile.bounds.min[0], drawn.min.x)), tile.bounds.min[1], low(Math.min(tile.bounds.min[2], drawn.min.z))],
|
|
544
|
+
max: [high(Math.max(tile.bounds.max[0], drawn.max.x)), tile.bounds.max[1], high(Math.max(tile.bounds.max[2], drawn.max.z))] };
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
const row = { triangles: rows.reduce((n, f) => n + f.triangles, 0), draws: rows.reduce((n, f) => n + f.draws, 0), compressed: rows.reduce((n, f) => n + f.compressed, 0) };
|
|
548
|
+
tileReport.push({ tile: `0/${x}/${z}`, triangles: row.triangles, draws: row.draws, bytes: row.compressed });
|
|
549
|
+
}
|
|
550
|
+
// panels (AP16): one library GLB each, its texture slots as dependencies
|
|
551
|
+
const panels = panelParts.map(({ id, merges, shadows }) => {
|
|
552
|
+
const primitives: GlbPrimitive[] = [], dependencies = new Set<string>();
|
|
553
|
+
for (const [, tile] of [...merges].sort(([a], [b]) => a.localeCompare(b))) {
|
|
554
|
+
for (const [key, merge] of [...tile].sort(([a], [b]) => a.localeCompare(b))) {
|
|
555
|
+
const entry = entries.get(key); if (entry === undefined || merge.position.length === 0) continue;
|
|
556
|
+
primitives.push(...primitivesOf(merge, entry, glbNames.get(key) ?? key, shadows.get(key) ?? true));
|
|
557
|
+
const file = entry.material.map === null ? undefined : textureFiles.get(entry.material.map); if (file !== undefined) dependencies.add(file.hash);
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
if (primitives.length === 0) throw new SceneRefusalError(id, 'a panel part draws nothing', 'Give the panel part a visible mesh, or drop its panel option');
|
|
561
|
+
return { id, file: store(staticGlb(primitives, `scene.panel.${id}`), 'glb', [...dependencies].sort()).hash, visible: true };
|
|
562
|
+
});
|
|
563
|
+
const library = panels.map((panel) => panel.file);
|
|
564
|
+
// colliders (AP4); a panel part's solids are its panel's one collider (AP16)
|
|
565
|
+
const colliders = scene.parts.filter((part) => part.colliders.length > 0).map((part) => ({ id: part.panel ?? `scene.${part.name}`, panel: part.panel ?? null, initialActive: true, shapes: part.colliders.map(boxRow) }));
|
|
566
|
+
// water (AP4)
|
|
567
|
+
const water = scene.parts.flatMap(waterRows);
|
|
568
|
+
const lights = scene.parts.flatMap((part) => part.lights);
|
|
569
|
+
const base = emptyShardfile({ slug: scene.identity.slug, name: scene.identity.name, author: scene.identity.author ?? 'Wildshard', revision: scene.identity.revision ?? 1, seed: scene.identity.seed ?? 1 });
|
|
570
|
+
const [sx, sy, sz] = scene.spawn.position;
|
|
571
|
+
const spawnY = Math.max(sy, (ground?.heightAt(sx, sz) ?? 0) + 1);
|
|
572
|
+
const product = {
|
|
573
|
+
...base, budgets: { ...base.budgets, library: libraryCost(files, library), sim: { resident: 16_000_000, compressed: 1_000_000 } }, serverBudget: { ...base.serverBudget, tickMicros: 5_000, memory: 16_000_000 },
|
|
574
|
+
look: sceneLook(scene, lights, lookMaterials), spawn: { x: round(sx, 3), y: round(spawnY, 3), z: round(sz, 3), yaw: round(scene.spawn.yaw, 4) },
|
|
575
|
+
terrain: { ...terrain.terrain, shadow: { cast: true, receive: true }, follow: 5 }, tiles: shardTiles, files: files.sort((a, b) => a.hash.localeCompare(b.hash)), edge: terrain.edge,
|
|
576
|
+
critical: [...terrain.critical], far: null, library: [...base.library, ...library],
|
|
577
|
+
props: { version: 1, family: 'pbr', overhang: OVERHANG, tiles: propTiles, panels, models: [], far: null, textures: [], colliders, ...(Object.keys(propMaterials).length === 0 ? {} : { materials: propMaterials }) },
|
|
578
|
+
...(water.length === 0 ? {} : { water }),
|
|
579
|
+
};
|
|
580
|
+
// oxlint-disable-next-line unicorn/prefer-structured-clone -- JSON wire normalization (signed zero), as product.ts does
|
|
581
|
+
let shard = parseShardfile(JSON.parse(JSON.stringify(product)));
|
|
582
|
+
if (options.extend !== undefined) shard = options.extend(shard);
|
|
583
|
+
return { shard, assets, report: { cards, lampsDropped: Math.max(0, lights.filter((l) => l.kind === 'point').length - 16), tiles: tileReport } };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* SHARD-SOURCE AP19: the shardfile sections a watched page restarts its simulation for (engine's dev hook v4,
|
|
588
|
+
* `DEV_GAMEPLAY_SECTIONS` in engine `src/shared/game/devGameplay.ts`: keep the two lists the same).
|
|
589
|
+
*/
|
|
590
|
+
// `questNpcs` and `clientScripts` are the page's alone (the hook rebuilds only the quest views): a change there is a new shell.
|
|
591
|
+
export const GAMEPLAY_SECTIONS = ['quests', 'questHost', 'encounters', 'directors', 'creatures', 'crowds', 'hooks', 'ledger', 'sim'] as const;
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* AP19: what `options.extend` adds to a scene shard, split for `wildshard watch`: the gameplay sections (a soft restart takes
|
|
595
|
+
* them live) and the rest (a change there needs a new shell). Cheap: `extend` runs over an empty shardfile of the scene's
|
|
596
|
+
* identity, never the baked one, so it must not read the scene's rows (none of today's do).
|
|
597
|
+
*/
|
|
598
|
+
export function sceneGameplay(identity: ShardScene['identity'], options: ShardfileOptions = {}): { gameplay: Record<string, unknown>; rest: Record<string, unknown> } {
|
|
599
|
+
const base = parseShardfile(emptyShardfile({ slug: identity.slug, name: identity.name, author: identity.author ?? 'Wildshard', revision: identity.revision ?? 1, seed: identity.seed ?? 1 }));
|
|
600
|
+
// the base as it was, before an `extend` that edits its input in place can change it
|
|
601
|
+
const before = structuredClone(base) as unknown as Record<string, unknown>;
|
|
602
|
+
const shard = options.extend === undefined ? base : options.extend(base) as unknown as Record<string, unknown>;
|
|
603
|
+
const gameplay: Record<string, unknown> = {}, rest: Record<string, unknown> = {};
|
|
604
|
+
for (const key of new Set([...Object.keys(before), ...Object.keys(shard)])) {
|
|
605
|
+
const value = (shard as Record<string, unknown>)[key];
|
|
606
|
+
if ((GAMEPLAY_SECTIONS as readonly string[]).includes(key)) { if (value !== undefined) gameplay[key] = value; }
|
|
607
|
+
else if (JSON.stringify(value) !== JSON.stringify(before[key])) rest[key] = value ?? null;
|
|
608
|
+
}
|
|
609
|
+
return { gameplay, rest };
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** The scene's ground as the terrain bake reads it: the declared height field, or a flat cell. */
|
|
613
|
+
function groundSource(scene: ShardScene): Parameters<typeof bakeTerrain>[0] {
|
|
614
|
+
const ground = scene.ground;
|
|
615
|
+
return { heightAt: ground?.heightAt ?? (() => 0), colourAt: (x, z) => ground?.colourAt?.(x, z) ?? [0.3, 0.36, 0.2] };
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** AP18: the scene's whole ground as one terrain tile's wire bytes (heights and colours), what a watched page's hook swaps in. */
|
|
619
|
+
export function sceneGroundBytes(scene: ShardScene): Uint8Array {
|
|
620
|
+
return encodeTerrainTile(groundLattice(groundSource(scene)));
|
|
621
|
+
}
|