@wildshard/sdk 0.3.1 → 0.3.3
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 +19 -6
- package/bin/wildshard.mjs +4 -0
- package/docs/api/EXPORT-TIERS.md +3 -2
- package/lint/export-tiers.json +1 -0
- package/lint/sdk-plugin.d.mts +2 -0
- package/lint/sdk-plugin.mjs +39 -1
- package/package.json +10 -9
- package/scripts/capture-hero.mjs +48 -18
- package/scripts/ci21-sdk-tail-lint.mjs +95 -0
- package/scripts/keep-copy.mjs +172 -0
- package/scripts/land.mjs +34 -4
- package/scripts/lane-live.mjs +136 -0
- package/scripts/leftovers-report.mjs +47 -0
- package/scripts/lint-dispatch.mjs +5 -0
- package/scripts/music/export-midi.mjs +3 -2
- package/scripts/prepare-product.mjs +3 -2
- package/scripts/scratch-dir.d.mts +3 -0
- package/scripts/scratch-dir.mjs +33 -14
- package/scripts/scratch-sweep.mjs +15 -23
- package/scripts/typecheck.mjs +15 -0
- package/scripts/worktree-reap.mjs +46 -104
- package/scripts/worktree.mjs +35 -13
- package/skills/wildshard/SKILL.md +3 -1
- package/src/cli/content-command.ts +44 -0
- package/src/cli/content.ts +287 -0
- package/src/cli/help.ts +7 -2
- package/src/cli/hero/hero.ts +51 -3
- package/src/cli/hero/scene-card.ts +46 -0
- package/src/cli/hero/stamp.ts +5 -3
- package/src/sharddev/authorManifest.ts +20 -2
- package/src/sharddev/cli.ts +1 -1
- package/src/sharddev/dev.ts +23 -4
- package/src/sharddev/newProject.ts +27 -8
- package/src/sharddev/project.ts +2 -2
- package/src/sharddev/refusals.ts +1 -0
- package/src/sharddev/scene/author.ts +22 -1
- package/src/sharddev/scene/budget.ts +87 -0
- package/src/sharddev/scene/creature.ts +171 -0
- package/src/sharddev/scene/description.ts +41 -0
- package/src/sharddev/scene/lower.ts +127 -3
- package/src/sharddev/scene/shardfile.ts +222 -20
- package/src/sharddev/shardSource.ts +2 -2
- package/src/sharddev/test/diskScriptScenario.ts +4 -2
- package/src/sharddev/test/ownedScratch.ts +14 -0
- package/src/sharddev/test/scriptScenario.ts +18 -13
- package/src/sharddev/tsconfig.json +3 -0
- package/src/sharddev/watch/pageEntry.ts +1 -19
- package/src/sharddev/watch/parity-baseline.json +8 -8
- package/src/sharddev/watch/parity.mjs +24 -0
- package/src/sharddev/watch/watch.ts +10 -2
- package/src/shards/_template/behaviour/boss.as +13 -4
- package/src/shards/_template/behaviour/door.as +8 -3
- package/src/shards/_template/behaviour/hooks.json +35 -0
- 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/bossDecision.json +11 -1
- package/src/shards/_template/data/card.json +49 -1
- package/src/shards/_template/data/clientScripts.json +411 -0
- package/src/shards/_template/data/creatures.json +280 -2
- package/src/shards/_template/data/items.json +1 -1
- package/src/shards/_template/data/layout.json +32 -1
- package/src/shards/_template/data/ledger.json +45 -0
- package/src/shards/_template/data/npcs/hermit.json +72 -0
- package/src/shards/_template/data/quests.json +297 -11
- package/src/shards/_template/data/rows.json +154 -0
- package/src/shards/_template/data/skins.json +14 -0
- package/src/shards/_template/data/targets.json +47 -0
- package/src/shards/_template/data/text.json +4 -1
- package/src/shards/_template/generators/lift.ts +71 -0
- package/src/shards/_template/generators/product.ts +19 -5
- package/src/shards/_template/generators/templatePropsSource.ts +5 -4
- package/src/shards/_template/generators/terrain.ts +10 -2
- package/src/shards/_template/generators/world.ts +42 -7
- package/src/shards/_template/hero.json +6 -6
- package/src/shards/_template/manifest.json +49 -1
- package/src/shards/authoring-slice/generators/shard.ts +2 -1
- package/src/shards/authoring-slice/generators/world.ts +8 -1
- package/tsconfig.author.json +24 -0
package/src/sharddev/project.ts
CHANGED
|
@@ -38,7 +38,7 @@ import type { ScriptAdmissionRows } from '@wildshard/format/scriptContract';
|
|
|
38
38
|
import { readCookInput, type CookInput } from './cookInput';
|
|
39
39
|
import { audioEncodeLine, encodeMountAudio, readStereoMarks } from './audioEncode';
|
|
40
40
|
import { engineMusicLine } from './engineMusic';
|
|
41
|
-
import { AUTHOR_BUDGETS, AUTHOR_BUDGETS_MODULE, authorManifest } from './authorManifest';
|
|
41
|
+
import { AUTHOR_BUDGETS, AUTHOR_BUDGETS_MODULE, authorManifest, sceneCardUrls } from './authorManifest';
|
|
42
42
|
import { discoveryDocument, discoveryUrl } from './discoveryDocument';
|
|
43
43
|
import { outputScriptAdmissionRows, outputPlatformPayloads, clearOutputProduct, writeOutputProduct, type OutputProductOptions } from './outputProduct';
|
|
44
44
|
import { prepareProjectOutput, mergeProjectBlobs, projectMirrors, type PreparedProjectOutput } from './projectOutput';
|
|
@@ -282,7 +282,7 @@ export async function buildProject(project: string, output?: string, options: {
|
|
|
282
282
|
try {
|
|
283
283
|
const runtime = options.copyRuntime === true || clientPlan ? writeRuntimeFiles(project, destination) : undefined;
|
|
284
284
|
const encoded = await encodedCookInput(project, shard.identity.slug);
|
|
285
|
-
const cook = await withDiscovery(project, shard.manifest ?? options.manifest?.composed ?? authorManifest(shard), loaded.output.discovery, encoded?.input, assets);
|
|
285
|
+
const cook = await withDiscovery(project, shard.manifest ?? options.manifest?.composed ?? authorManifest(shard, sceneCardUrls(project, shardFolderName(project))), loaded.output.discovery, encoded?.input, assets);
|
|
286
286
|
descriptor = writeOutputProduct(shard, assets, destination, { ...loaded.output, ...(runtime === undefined ? {} : { runtime }), ...(cook === undefined ? {} : { cook }) });
|
|
287
287
|
assertNoRenamedAudioNames(destination, encoded?.renamed ?? new Map());
|
|
288
288
|
phase('product-write');
|
package/src/sharddev/refusals.ts
CHANGED
|
@@ -208,6 +208,7 @@ export const REFUSAL_RULES: readonly RefusalRule[] = [
|
|
|
208
208
|
/** Wildshard's lint rules an author's source can hit (`.oxlintrc.author.json`), with the fix for each. */
|
|
209
209
|
const LINT_FIXES: Readonly<Record<string, string>> = {
|
|
210
210
|
'wildshard-sdk/generator-imports': 'Import Wildshard code only through @wildshard/sdk\'s exports; copy what another shard has instead of importing it.',
|
|
211
|
+
'wildshard-sdk/no-hand-graph': 'Write the graph in TSL with graph() from @wildshard/sdk/materials; it compiles to the graph IR.',
|
|
211
212
|
'wildshard/engine-internal': 'Use the shard-facing SDK export instead of the game-only engine export.',
|
|
212
213
|
'wildshard/engine-sides': 'Keep client, server and shared code apart: import the shared module, not the other side\'s.',
|
|
213
214
|
'wildshard/engine-words': 'Move Wildshard words (shard and game names) out of engine code into content data.',
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DataTexture, LinearFilter, LinearMipmapLinearFilter, Mesh, MeshStandardMaterial, RepeatWrapping, SRGBColorSpace, ShapeGeometry, LinearSRGBColorSpace, type ColorRepresentation, type Group, type Object3D, type Scene, type Shape } from 'three';
|
|
1
|
+
import { DataTexture, type InstancedMesh, LinearFilter, LinearMipmapLinearFilter, Mesh, MeshStandardMaterial, RepeatWrapping, SRGBColorSpace, ShapeGeometry, LinearSRGBColorSpace, type ColorRepresentation, type Group, type Object3D, type Scene, type Shape } from 'three';
|
|
2
2
|
import { positionLocal } from 'three/tsl';
|
|
3
3
|
import type { DetailLayer } from '@wildshard/format/detail-layer';
|
|
4
4
|
import type { GraphValue } from '../materials';
|
|
@@ -41,8 +41,29 @@ export interface ShardWorld {
|
|
|
41
41
|
post: (settings: Partial<Omit<ScenePost, 'bloom'>> & { bloom?: ScenePost['bloom'] }) => void;
|
|
42
42
|
/** Where a player enters. */
|
|
43
43
|
spawn: (x: number, y: number, z: number, yaw?: number) => void;
|
|
44
|
+
/**
|
|
45
|
+
* AP25a: a region trigger round `at`'s world position (read once the build has run, so a node moved later still counts):
|
|
46
|
+
* entering `radius` metres of it sets quest flag `flag` (default `id`). Written into the shard's `quests.triggers` beside
|
|
47
|
+
* any `extend` declares, so a quest's place is typed once, in the scene.
|
|
48
|
+
*/
|
|
49
|
+
trigger: (id: string, at: Object3D, options: { radius: number; flag?: string }) => void;
|
|
50
|
+
/**
|
|
51
|
+
* AP25b: a use prompt at `at`'s world position: within `radius` metres the player sees `label`, and using it runs the
|
|
52
|
+
* shard scene `scene` (format `targets.interactions`; `unless` names the hooks condition that spends it).
|
|
53
|
+
*/
|
|
54
|
+
interact: (id: string, at: Object3D, options: { label: string; radius: number; scene: string; unless?: string }) => void;
|
|
55
|
+
/**
|
|
56
|
+
* AP32c: grass, ferns and small clutter as a detail layer (format `look.details`). Build the clumps as a cleanroom does,
|
|
57
|
+
* one InstancedMesh of a small card (at most 2,000 triangles), and hand it here: the shard keeps the card once and how
|
|
58
|
+
* many clumps stand in each `cell`-metre square (and their mean height), not the copies, and the engine scatters them
|
|
59
|
+
* within `radius` metres of the camera (half on a phone), with a seeded yaw and a lean, size and tint inside the ranges
|
|
60
|
+
* the copies span. The mesh may sit in the scene or not; it is never drawn as copies. `sway` moves the cards' tops on
|
|
61
|
+
* the wind (`amount` 0 to 1, `rate` in cycles a second).
|
|
62
|
+
*/
|
|
63
|
+
detail: (id: string, mesh: InstancedMesh, options: { cell: number; radius: number; sway?: { amount: number; rate: number }; shadow?: boolean }) => void;
|
|
44
64
|
}
|
|
45
65
|
|
|
66
|
+
|
|
46
67
|
/** AP14: the view ray through a sky pixel (unit, world axes, y up): the dome is centred on the camera. */
|
|
47
68
|
export const skyRay: ReturnType<typeof positionLocal.normalize> = positionLocal.normalize();
|
|
48
69
|
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// SHARD-SOURCE AP9a: budgets are a report. `wildshard build` and `check` print one table for a scene shard: each part's
|
|
2
|
+
// triangles, materials (its view draws: the engine draws a material once across tiles, AP8) and the fine tile it fills
|
|
3
|
+
// most, against each tier's caps; every tile over a tier's cap is named with the parts that fill it, the largest first.
|
|
4
|
+
// Caps are reported, not enforced (J338). The desktop tier has no tile triangle cap until AP9b gives the format one.
|
|
5
|
+
import { CONTENT_CAPS } from '@wildshard/format/contentBounds';
|
|
6
|
+
import { VIEW_DRAWS } from '@wildshard/format/viewDraws';
|
|
7
|
+
import type { ShardScene } from './description';
|
|
8
|
+
|
|
9
|
+
/** A tier's caps: triangles in one fine (L0) tile, and the draws one view may cost. `null`: no cap on that tier yet. */
|
|
10
|
+
export interface TierCaps { readonly tileTriangles: number | null; readonly viewDraws: number }
|
|
11
|
+
/** The caps each tier is reported against (format `CONTENT_CAPS` and `VIEW_DRAWS`). */
|
|
12
|
+
export const TIER_CAPS: Readonly<Record<'phone' | 'desktop', TierCaps>> = {
|
|
13
|
+
phone: { tileTriangles: CONTENT_CAPS.l0.triangles, viewDraws: VIEW_DRAWS.phone },
|
|
14
|
+
desktop: { tileTriangles: null, viewDraws: VIEW_DRAWS.desktop },
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/** One part's share of the budget. Tile triangles are counted at each mesh or instance's origin, so a share is close. */
|
|
18
|
+
export interface PartBudget {
|
|
19
|
+
readonly part: string;
|
|
20
|
+
readonly triangles: number;
|
|
21
|
+
readonly materials: number;
|
|
22
|
+
/** triangles per fine tile (`0/x/z`), counted at each copy's origin */
|
|
23
|
+
readonly tiles: ReadonlyMap<string, number>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A built tile as the back end measured it (merged and clipped). */
|
|
27
|
+
export interface BuiltTile { readonly tile: string; readonly triangles: number; readonly draws: number }
|
|
28
|
+
|
|
29
|
+
const TILE = 62.5, HALF = 250;
|
|
30
|
+
const tileOf = (value: number): number => Math.min(7, Math.max(0, Math.floor((value + HALF) / TILE)));
|
|
31
|
+
const address = (x: number, z: number): string => `0/${String(tileOf(x))}/${String(tileOf(z))}`;
|
|
32
|
+
|
|
33
|
+
/** Every part's triangles, materials and per-tile triangles. */
|
|
34
|
+
export function partBudgets(scene: Pick<ShardScene, 'parts' | 'geometries'>): PartBudget[] {
|
|
35
|
+
return scene.parts.map((part) => {
|
|
36
|
+
const tiles = new Map<string, number>(), add = (tile: string, n: number): void => { tiles.set(tile, (tiles.get(tile) ?? 0) + n); };
|
|
37
|
+
let triangles = 0;
|
|
38
|
+
for (const draw of part.draws) {
|
|
39
|
+
const one = scene.geometries[draw.geometry]?.triangles ?? 0, m = draw.matrix;
|
|
40
|
+
if (draw.instances === null) { triangles += one; add(address(m[12] ?? 0, m[14] ?? 0), one); continue; }
|
|
41
|
+
const { count, matrices } = draw.instances;
|
|
42
|
+
triangles += one * count;
|
|
43
|
+
for (let i = 0; i < count; i++) {
|
|
44
|
+
// the instance's origin in world space: the mesh's matrix times the instance's translation
|
|
45
|
+
const lx = matrices[i * 16 + 12] ?? 0, ly = matrices[i * 16 + 13] ?? 0, lz = matrices[i * 16 + 14] ?? 0;
|
|
46
|
+
const wx = (m[0] ?? 1) * lx + (m[4] ?? 0) * ly + (m[8] ?? 0) * lz + (m[12] ?? 0);
|
|
47
|
+
const wz = (m[2] ?? 0) * lx + (m[6] ?? 0) * ly + (m[10] ?? 1) * lz + (m[14] ?? 0);
|
|
48
|
+
add(address(wx, wz), one);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
for (const sprite of part.sprites) { triangles += 2; add(address(sprite.position[0], sprite.position[2]), 2); }
|
|
52
|
+
for (const cloud of part.points) for (let i = 0; i < cloud.positions.length; i += 3) { triangles += 2; add(address(cloud.positions[i] ?? 0, cloud.positions[i + 2] ?? 0), 2); }
|
|
53
|
+
return { part: part.panel ?? part.name, triangles, materials: new Set(part.draws.map((d) => d.material)).size, tiles };
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const n = (value: number): string => value.toLocaleString('en-US');
|
|
58
|
+
|
|
59
|
+
/** The report's lines: the per-part table, then each overrun by tier, naming the tile and the parts that fill it. */
|
|
60
|
+
export function budgetReport(parts: readonly PartBudget[], built: readonly BuiltTile[], caps: Readonly<Record<string, TierCaps>> = TIER_CAPS): string[] {
|
|
61
|
+
const sorted = [...parts].sort((a, b) => b.triangles - a.triangles || a.part.localeCompare(b.part));
|
|
62
|
+
const worst = (p: PartBudget): [string, number] => [...p.tiles].reduce<[string, number]>((best, t) => (t[1] > best[1] ? t : best), ['-', 0]);
|
|
63
|
+
const tiers = Object.keys(caps);
|
|
64
|
+
const head = ['part', 'triangles', 'materials', 'worst tile', ...tiers];
|
|
65
|
+
const rows = sorted.map((p) => {
|
|
66
|
+
const [tile, tris] = worst(p);
|
|
67
|
+
const verdicts = tiers.map((tier) => {
|
|
68
|
+
const cap = caps[tier]; if (cap === undefined) return '';
|
|
69
|
+
const over = [cap.tileTriangles !== null && tris > cap.tileTriangles ? 'tile tris' : null, p.materials > cap.viewDraws ? 'draws' : null].filter((x) => x !== null);
|
|
70
|
+
return over.length === 0 ? 'ok' : `over: ${over.join(', ')}`;
|
|
71
|
+
});
|
|
72
|
+
return [p.part, n(p.triangles), String(p.materials), tile === '-' ? '-' : `${tile} ${n(tris)}`].concat(verdicts);
|
|
73
|
+
});
|
|
74
|
+
const total = parts.reduce((s, p) => s + p.materials, 0);
|
|
75
|
+
rows.push(['(all parts)', n(parts.reduce((s, p) => s + p.triangles, 0)), String(total), '', ...tiers.map((tier) => { const cap = caps[tier]; return cap === undefined || total <= cap.viewDraws ? 'ok' : `over: draws ${String(total)} > ${String(cap.viewDraws)}`; })]);
|
|
76
|
+
const widths = head.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)));
|
|
77
|
+
const line = (cells: readonly string[]): string => cells.map((c, i) => (i === 1 || i === 2 ? c.padStart(widths[i] ?? 0) : c.padEnd(widths[i] ?? 0))).join(' ').trimEnd();
|
|
78
|
+
const out = [`budget (AP9): ${String(parts.length)} parts; caps ${tiers.map((tier) => { const cap = caps[tier]; return cap === undefined ? tier : `${tier} ${cap.tileTriangles === null ? 'no tile cap' : `${n(cap.tileTriangles)} tris a tile`}, ${String(cap.viewDraws)} draws a view`; }).join('; ')} (reported, J338)`, ` ${line(head)}`, ...rows.map((r) => ` ${line(r)}`)];
|
|
79
|
+
for (const tier of tiers) {
|
|
80
|
+
const cap = caps[tier]; if (cap === undefined || cap.tileTriangles === null) continue;
|
|
81
|
+
for (const t of built.filter((b) => b.triangles > (cap.tileTriangles ?? Infinity)).sort((a, b) => b.triangles - a.triangles)) {
|
|
82
|
+
const fill = parts.map((p) => [p.part, p.tiles.get(t.tile) ?? 0] as const).filter(([, v]) => v > 0).sort((a, b) => b[1] - a[1]);
|
|
83
|
+
out.push(`over ${tier}: tile ${t.tile} ${n(t.triangles)} tris > ${n(cap.tileTriangles)}: ${fill.slice(0, 4).map(([p, v]) => `${p} ${n(v)}`).join(', ')}${fill.length > 4 ? `, ${String(fill.length - 4)} more` : ''}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SHARD-SOURCE AP23a (CUSTOM-CREATURES CC24a): a creature written as three.js, compiled to a skinned GLB rig.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import * as THREE from 'three';
|
|
6
|
+
* import { creatureGlb } from '@wildshard/sdk/scene/creature';
|
|
7
|
+
* const body = new THREE.Group(); body.name = 'bandit';
|
|
8
|
+
* const hips = new THREE.Group(); hips.name = 'hips'; hips.position.y = 0.9; body.add(hips);
|
|
9
|
+
* hips.add(new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.5, 0.25), cloth));
|
|
10
|
+
* const walk = new THREE.AnimationClip('walk', 1, [new THREE.QuaternionKeyframeTrack('hips.quaternion', [0, 0.5, 1], [...])]);
|
|
11
|
+
* const { glb } = creatureGlb(body, { clips: [walk] });
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* The group is the creature's frame (its own transform is not read). Its bones are the named nodes under it that are not
|
|
15
|
+
* meshes, each at its rest position in that frame (a bone with no bone above it is a root). A mesh is bound rigidly to its
|
|
16
|
+
* nearest bone ancestor:
|
|
17
|
+
* it moves only with that bone. Clips keep their names and their `<bone>.position|quaternion|scale` tracks. A bone rests
|
|
18
|
+
* unrotated and unscaled (the rig's bind pose is translations only, as every rig the engine loads), so put a rest rotation
|
|
19
|
+
* on the mesh under it instead. Compile time only, like the scene.
|
|
20
|
+
*/
|
|
21
|
+
import { BufferAttribute, Matrix4, MeshStandardMaterial, Quaternion, Vector3, type AnimationClip, type BufferGeometry, type Mesh, type Object3D, type PointLight } from 'three';
|
|
22
|
+
import { parseGlb } from '@wildshard/format/shardfileAssets';
|
|
23
|
+
import { hashImmutableBytes } from '../immutable';
|
|
24
|
+
import { skinnedGlb, type SkinnedBone, type SkinnedPart } from '../bake/skinned';
|
|
25
|
+
import { SceneRefusalError } from './lower';
|
|
26
|
+
|
|
27
|
+
export interface CreatureOptions {
|
|
28
|
+
/** Bone animations, by name (`walk`, `attack`); each track names a bone of the rig. */
|
|
29
|
+
readonly clips?: readonly AnimationClip[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** AP24c: a `PointLight` under a bone, as an offset in that bone's frame (bones rest unrotated, so the creature's axes). */
|
|
33
|
+
export interface CreatureLamp {
|
|
34
|
+
readonly bone: string;
|
|
35
|
+
readonly at: readonly [number, number, number];
|
|
36
|
+
/** linear RGB, as three holds a light's colour */
|
|
37
|
+
readonly colour: readonly [number, number, number];
|
|
38
|
+
readonly intensity: number;
|
|
39
|
+
readonly distance: number;
|
|
40
|
+
readonly decay: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CreatureRig {
|
|
44
|
+
readonly glb: Uint8Array;
|
|
45
|
+
/** AP24c: the rig's lights, each riding its nearest bone (`creatureLampRows` writes them as following look lamps) */
|
|
46
|
+
readonly lamps: readonly CreatureLamp[];
|
|
47
|
+
/** The joints in skin order, each with its parent and rest position in the creature's frame. */
|
|
48
|
+
readonly bones: readonly SkinnedBone[];
|
|
49
|
+
readonly clips: readonly string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const EPS = 1e-6;
|
|
53
|
+
const isMesh = (o: Object3D): o is Mesh => (o as Mesh).isMesh === true;
|
|
54
|
+
const isPointLight = (o: Object3D): o is PointLight => (o as PointLight).isPointLight === true;
|
|
55
|
+
const isLight = (o: Object3D): boolean => (o as PointLight).isLight === true;
|
|
56
|
+
|
|
57
|
+
/** Compile `root` (a `Group` of bone nodes and meshes) to a skinned GLB rig. */
|
|
58
|
+
export function creatureGlb(root: Object3D, options: CreatureOptions = {}): CreatureRig {
|
|
59
|
+
const name = root.name === '' ? 'creature' : root.name;
|
|
60
|
+
root.updateMatrixWorld(true);
|
|
61
|
+
const toFrame = new Matrix4().copy(root.matrixWorld).invert();
|
|
62
|
+
const bones: SkinnedBone[] = [], index = new Map<Object3D, number>();
|
|
63
|
+
const at = (o: Object3D): [number, number, number] => {
|
|
64
|
+
const p = new Vector3().setFromMatrixPosition(new Matrix4().multiplyMatrices(toFrame, o.matrixWorld));
|
|
65
|
+
return [p.x, p.y, p.z];
|
|
66
|
+
};
|
|
67
|
+
const visit = (node: Object3D, parentBone: string | null): void => {
|
|
68
|
+
const bone = node !== root && !isMesh(node) && !isLight(node) && node.name !== '';
|
|
69
|
+
let next = parentBone;
|
|
70
|
+
if (bone) {
|
|
71
|
+
const boneName = node.name;
|
|
72
|
+
if (bones.some((b) => b.name === boneName)) throw new SceneRefusalError(`${name}/${boneName}`, 'two bones share this name', 'Give every bone node its own name');
|
|
73
|
+
if ((Math.abs(1 - Math.abs(node.quaternion.dot(new Quaternion()))) > EPS || node.scale.distanceTo(new Vector3(1, 1, 1)) > EPS)) {
|
|
74
|
+
throw new SceneRefusalError(`${name}/${boneName}`, 'a bone rests rotated or scaled', 'Leave the bone unrotated and unscaled at rest; rotate or scale the mesh under it');
|
|
75
|
+
}
|
|
76
|
+
index.set(node, bones.length); bones.push({ name: boneName, parent: parentBone, pos: at(node) });
|
|
77
|
+
next = boneName;
|
|
78
|
+
}
|
|
79
|
+
for (const child of node.children) visit(child, next);
|
|
80
|
+
};
|
|
81
|
+
visit(root, null);
|
|
82
|
+
|
|
83
|
+
const parts: SkinnedPart[] = [];
|
|
84
|
+
root.traverse((o) => {
|
|
85
|
+
if (!isMesh(o)) return;
|
|
86
|
+
let owner: Object3D | null = o.parent;
|
|
87
|
+
while (owner !== null && !index.has(owner)) owner = owner.parent;
|
|
88
|
+
const bone = owner === null ? undefined : index.get(owner);
|
|
89
|
+
if (bone === undefined) throw new SceneRefusalError(`${name}/${o.name || 'Mesh'}`, 'a creature part hangs under no bone', 'Put the mesh under a named bone node');
|
|
90
|
+
const material = o.material;
|
|
91
|
+
if (Array.isArray(material) || !(material instanceof MeshStandardMaterial)) throw new SceneRefusalError(`${name}/${o.name || 'Mesh'}`, 'a creature part draws with one MeshStandardMaterial', 'Give the mesh one MeshStandardMaterial');
|
|
92
|
+
if (material.map !== null) throw new SceneRefusalError(`${name}/${o.name || 'Mesh'}`, 'a creature part\'s map has no lowering yet', 'Colour it with the material colour or vertex colours');
|
|
93
|
+
const geometry = (o.geometry.index === null ? o.geometry.clone() : o.geometry.toNonIndexed()) as BufferGeometry;
|
|
94
|
+
for (const key of Object.keys(geometry.attributes)) if (!['position', 'normal', 'color'].includes(key)) geometry.deleteAttribute(key);
|
|
95
|
+
geometry.applyMatrix4(new Matrix4().multiplyMatrices(toFrame, o.matrixWorld));
|
|
96
|
+
const count = geometry.getAttribute('position').count, joints = new Uint16Array(count * 4), weights = new Float32Array(count * 4);
|
|
97
|
+
for (let v = 0; v < count; v++) { joints[v * 4] = bone; weights[v * 4] = 1; }
|
|
98
|
+
geometry.setAttribute('skinIndex', new BufferAttribute(joints, 4)); geometry.setAttribute('skinWeight', new BufferAttribute(weights, 4));
|
|
99
|
+
parts.push({ geometry, material, name: `${name}.${o.name === '' ? parts.length : o.name}` });
|
|
100
|
+
});
|
|
101
|
+
if (bones.length === 0) throw new SceneRefusalError(name, 'a creature has no bones', 'Name the nodes its meshes hang from (`body`, `head`): a named node that is not a mesh is a bone');
|
|
102
|
+
if (parts.length === 0) throw new SceneRefusalError(name, 'a creature draws nothing', 'Add a mesh under one of its bones');
|
|
103
|
+
|
|
104
|
+
const lamps: CreatureLamp[] = [];
|
|
105
|
+
root.traverse((o) => {
|
|
106
|
+
if (!isLight(o)) return;
|
|
107
|
+
if (!isPointLight(o)) throw new SceneRefusalError(`${name}/${o.name || o.type}`, 'a creature carries only point lights', 'Use a PointLight; the look\'s sun and fill stay in the scene');
|
|
108
|
+
let owner: Object3D | null = o.parent;
|
|
109
|
+
while (owner !== null && !index.has(owner)) owner = owner.parent;
|
|
110
|
+
const bone = owner === null ? undefined : bones[index.get(owner) ?? -1];
|
|
111
|
+
if (bone === undefined) throw new SceneRefusalError(`${name}/${o.name || 'PointLight'}`, 'a creature light hangs under no bone', 'Put the light under a named bone node');
|
|
112
|
+
const p = at(o);
|
|
113
|
+
lamps.push({ bone: bone.name, at: [p[0] - bone.pos[0], p[1] - bone.pos[1], p[2] - bone.pos[2]], colour: [o.color.r, o.color.g, o.color.b], intensity: o.intensity, distance: o.distance, decay: o.decay });
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
const clips = options.clips ?? [];
|
|
117
|
+
for (const clip of clips) for (const track of clip.tracks) {
|
|
118
|
+
const bone = track.name.slice(0, track.name.lastIndexOf('.'));
|
|
119
|
+
if (!bones.some((b) => b.name === bone)) throw new SceneRefusalError(`${name}/${clip.name}`, `track ${track.name} names no bone of the rig`, `Name a bone node \`${bone}\`, or retarget the track`);
|
|
120
|
+
}
|
|
121
|
+
return { glb: skinnedGlb({ name, bones, parts, clips }).glb, bones, lamps, clips: clips.map((clip) => clip.name) };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** The `platform.skin` look's binding beside a rig row (shard-brasscap `src/sources/bandit.skin.json` has the shape). */
|
|
125
|
+
export interface CreatureBinding {
|
|
126
|
+
/** Clips that loop (`idle`, `walk`); the rest play once. */
|
|
127
|
+
readonly loops: readonly string[];
|
|
128
|
+
/** The skin's material entry (a look material family row). */
|
|
129
|
+
readonly material: Readonly<Record<string, unknown>>;
|
|
130
|
+
/** A GLB material name to a look material id (`{ Eye: 'glow' }`). */
|
|
131
|
+
readonly materials?: Readonly<Record<string, string>>;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* AP23b: the skin file for a compiled rig, as a species' skin names it: the rig row (its GLB's cost and hash, clips, joints as
|
|
136
|
+
* parent and child pairs, every bone a socket) and its binding. No species, kind or brain row is written: a species binds
|
|
137
|
+
* the skin by `id` as it binds a hand-written one.
|
|
138
|
+
*/
|
|
139
|
+
export function creatureSkin(rig: CreatureRig, options: { id: string; family?: 'toon' | 'pbr' | 'painterly'; binding: CreatureBinding }): { row: Record<string, unknown>; binding: Record<string, unknown> } {
|
|
140
|
+
const cost = parseGlb(rig.glb);
|
|
141
|
+
for (const loop of options.binding.loops) if (!rig.clips.includes(loop)) throw new SceneRefusalError(options.id, `loop ${loop} is not one of the rig's clips`, `Loop one of ${rig.clips.join(', ')}`);
|
|
142
|
+
return {
|
|
143
|
+
row: {
|
|
144
|
+
cost: { decoded: cost.decoded, draws: cost.draws, gpu: cost.gpu, triangles: cost.triangles }, family: options.family ?? 'toon', file: hashImmutableBytes(rig.glb), id: options.id,
|
|
145
|
+
rig: { clips: [...rig.clips], joints: rig.bones.filter((b) => b.parent !== null).map((b) => [b.parent, b.name]), skeleton: options.id, sockets: rig.bones.map((b) => b.name) },
|
|
146
|
+
},
|
|
147
|
+
binding: { loops: [...options.binding.loops], material: { ...options.binding.material }, ...(options.binding.materials === undefined ? {} : { materials: { ...options.binding.materials } }), skin: options.id },
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A `look.light.lamps` row that follows an actor's bone (shard-format v0.5.9 `lamps[].follow`, SHARD-SOURCE AP24a). */
|
|
152
|
+
export interface FollowingLampRow {
|
|
153
|
+
readonly at: [number, number, number];
|
|
154
|
+
readonly colour: [number, number, number];
|
|
155
|
+
readonly intensity: number;
|
|
156
|
+
readonly distance: number;
|
|
157
|
+
readonly decay: number;
|
|
158
|
+
readonly follow: { readonly actor: string; readonly bone: string };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* AP24c: the rig's lights as look lamps that ride `actor` (a creature spawn or boss id): the eyes and core of a boss light
|
|
163
|
+
* the ground as it walks. A three.js `distance` of 0 (no cut-off) has no look row, so it is refused.
|
|
164
|
+
*/
|
|
165
|
+
export function creatureLampRows(rig: CreatureRig, actor: string): FollowingLampRow[] {
|
|
166
|
+
return rig.lamps.map((lamp) => {
|
|
167
|
+
if (lamp.distance < 0.1 || lamp.distance > 50) throw new SceneRefusalError(`${actor}/${lamp.bone}`, 'a following lamp needs a distance of 0.1 to 50 m', 'Give the PointLight a distance in metres (its light ends there)');
|
|
168
|
+
if (lamp.intensity > 100) throw new SceneRefusalError(`${actor}/${lamp.bone}`, 'a following lamp is at most 100 cd', 'Lower the PointLight\'s intensity');
|
|
169
|
+
return { at: [...lamp.at], colour: [...lamp.colour], intensity: lamp.intensity, distance: lamp.distance, decay: lamp.decay, follow: { actor, bone: lamp.bone } };
|
|
170
|
+
});
|
|
171
|
+
}
|
|
@@ -220,4 +220,45 @@ export interface ShardScene {
|
|
|
220
220
|
readonly look: SceneLook;
|
|
221
221
|
readonly ground: SceneGround | null;
|
|
222
222
|
readonly spawn: { readonly position: Vec3; readonly yaw: number };
|
|
223
|
+
/** AP25: gameplay rows placed at scene nodes (`world.trigger`, `world.interact`), their positions read from the nodes */
|
|
224
|
+
readonly anchored: SceneAnchored;
|
|
225
|
+
/** AP32c: `world.detail` layers (format `look.details`), counted from their InstancedMeshes; absent or empty: none */
|
|
226
|
+
readonly details?: readonly SceneDetailScatter[];
|
|
223
227
|
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* SHARD-SOURCE AP32c: one `world.detail` layer, what its InstancedMesh's copies become: a card mesh and a count of clumps
|
|
231
|
+
* per mask cell, which the engine scatters round the camera (format `look.details`) instead of shipping every matrix.
|
|
232
|
+
*/
|
|
233
|
+
export interface SceneDetailScatter {
|
|
234
|
+
readonly id: string;
|
|
235
|
+
/** the InstancedMesh's path, for refusals and the build log */
|
|
236
|
+
readonly path: string;
|
|
237
|
+
/** the card, a `geometries` key */
|
|
238
|
+
readonly geometry: string;
|
|
239
|
+
/** the card's material, a `materials` key */
|
|
240
|
+
readonly material: string;
|
|
241
|
+
readonly region: { readonly corner: readonly [number, number]; readonly cell: number; readonly columns: number; readonly rows: number; readonly span: readonly [number, number] };
|
|
242
|
+
/** one byte per cell, row by row from the low corner: 255 is `clumps` clumps */
|
|
243
|
+
readonly mask: Uint8Array;
|
|
244
|
+
/** one u16 (little-endian) per cell: the mean height of the cell's clumps over `region.span` */
|
|
245
|
+
readonly heights: Uint8Array;
|
|
246
|
+
/** clumps in the fullest cell */
|
|
247
|
+
readonly clumps: number;
|
|
248
|
+
readonly scale: readonly [number, number];
|
|
249
|
+
/** the most a clump leans, radians */
|
|
250
|
+
readonly tilt: number;
|
|
251
|
+
/** the lowest and highest instance colour per channel (linear), or white */
|
|
252
|
+
readonly tint: readonly [Rgb, Rgb];
|
|
253
|
+
readonly sway: { readonly amount: number; readonly rate: number } | null;
|
|
254
|
+
readonly radius: number;
|
|
255
|
+
readonly shadow: boolean;
|
|
256
|
+
/** how many copies the InstancedMesh held */
|
|
257
|
+
readonly instances: number;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** AP25a: a region trigger (format `quests.triggers`, kind `region`) at a node's world x and z. */
|
|
261
|
+
export interface SceneTrigger { readonly id: string; readonly kind: 'region'; readonly flag: string; readonly x: number; readonly z: number; readonly radius: number }
|
|
262
|
+
/** AP25b: a use prompt (format `targets.interactions`) at a node's world position. */
|
|
263
|
+
export interface SceneInteraction { readonly id: string; readonly at: Vec3; readonly radius: number; readonly label: string; readonly scene: string; readonly unless?: string }
|
|
264
|
+
export interface SceneAnchored { readonly triggers: readonly SceneTrigger[]; readonly interactions: readonly SceneInteraction[] }
|
|
@@ -9,7 +9,7 @@ import { LOOK_SKY_BUDGET } from '@wildshard/format/look-sky';
|
|
|
9
9
|
import { isSolid, motionOf, paintedPixels, Water, type ShardWorld } from './author';
|
|
10
10
|
import type {
|
|
11
11
|
Rgb, SceneCollider, SceneDraw, SceneSky, SceneGeometry, SceneGround, SceneLight, SceneLook, SceneMaterial, SceneMotion, ScenePart, ScenePoints, ScenePost, SceneSprite, SceneTexture,
|
|
12
|
-
SceneWater, ShardIdentityInput, ShardScene, Vec3,
|
|
12
|
+
SceneDetailScatter, SceneWater, ShardIdentityInput, ShardScene, Vec3,
|
|
13
13
|
} from './description';
|
|
14
14
|
import { ContentHash, hashOf } from './hash';
|
|
15
15
|
|
|
@@ -34,6 +34,8 @@ const v3 = (v: Vector3): Vec3 => [v.x, v.y, v.z];
|
|
|
34
34
|
interface Tables {
|
|
35
35
|
materials: Map<string, SceneMaterial>; textures: Map<string, SceneTexture>; geometries: Map<string, SceneGeometry>;
|
|
36
36
|
geometryKeys: WeakMap<BufferGeometry, string>; materialKeys: WeakMap<Material, string>; textureKeys: WeakMap<Texture, string>;
|
|
37
|
+
/** AP32c: this lowering's world.detail meshes, which the walker leaves out (per call: a mesh reused later draws) */
|
|
38
|
+
details: ReadonlySet<Object3D>;
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
function floats(attribute: BufferAttribute | InterleavedBufferAttribute, width: number): Float32Array {
|
|
@@ -185,6 +187,8 @@ function refuseGraphMotion(path: string, key: string, tables: Tables, what: stri
|
|
|
185
187
|
function lowerPart(root: Object3D, tables: Tables, panel?: string): ScenePart {
|
|
186
188
|
const draws: SceneDraw[] = [], sprites: SceneSprite[] = [], lights: SceneLight[] = [], colliders: SceneCollider[] = [], water: SceneWater[] = [], points: ScenePoints[] = [];
|
|
187
189
|
const visit = (object: Object3D): void => {
|
|
190
|
+
// AP32c: a world.detail mesh is its layer's, never copies in a tile
|
|
191
|
+
if (tables.details.has(object)) return;
|
|
188
192
|
const path = pathOf(object, root);
|
|
189
193
|
if (!object.visible) {
|
|
190
194
|
// an invisible solid is a collider only: said once, drawn never
|
|
@@ -274,11 +278,94 @@ function groundHash(heightAt: (x: number, z: number) => number, colourAt: SceneG
|
|
|
274
278
|
|
|
275
279
|
const DEFAULT_POST: ScenePost = { tone: 'aces', exposure: 1, bloom: null, vignette: 0 };
|
|
276
280
|
|
|
281
|
+
/** Format `look.details` limits (shard-format `look-details.ts`): a refusal names them before the schema would. */
|
|
282
|
+
const DETAIL_LIMITS = { layers: 8, side: 512, clumps: 64, triangles: 2000, vertices: 6000, cell: [0.5, 8], radius: [4, 200], scale: [0.05, 20], rate: [0.05, 10] } as const;
|
|
283
|
+
|
|
284
|
+
interface DetailRequest { readonly id: string; readonly mesh: InstancedMesh; readonly cell: number; readonly radius: number; readonly sway: { amount: number; rate: number } | null; readonly shadow: boolean }
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* AP32c: one `world.detail` InstancedMesh as a detail layer. Its copies' world seats are counted per `cell`-metre square of
|
|
288
|
+
* the box round them (the mask: the fullest cell is 255, `clumps` clumps), their mean height per cell (u16 over the
|
|
289
|
+
* span), and the ranges their scale (the matrix's mean axis length), lean (the copy's up from world up) and colour span.
|
|
290
|
+
*/
|
|
291
|
+
function lowerDetail(request: DetailRequest, tables: Tables): SceneDetailScatter {
|
|
292
|
+
const { id, mesh, cell } = request, path = `detail ${id}`;
|
|
293
|
+
if (Array.isArray(mesh.material)) throw new SceneRefusalError(path, 'its mesh has several materials', 'Give a detail card one material');
|
|
294
|
+
const material = lowerMaterial(mesh.material, path, tables), entry = tables.materials.get(material);
|
|
295
|
+
if (entry?.entry !== null && entry?.entry !== undefined) throw new SceneRefusalError(path, 'a graph material on a detail card has no lowering yet', 'Draw the card with a MeshStandardMaterial');
|
|
296
|
+
if (entry?.kind !== 'standard') throw new SceneRefusalError(path, `its card's ${mesh.material.type} has no detail lowering (a layer draws lit PBR cards)`, 'Draw the card with a MeshStandardMaterial');
|
|
297
|
+
const geometry = lowerGeometry(mesh.geometry, path, tables), card = tables.geometries.get(geometry);
|
|
298
|
+
const vertices = (card?.position.length ?? 0) / 3, triangles = card?.triangles ?? 0;
|
|
299
|
+
if (triangles > DETAIL_LIMITS.triangles || vertices > DETAIL_LIMITS.vertices) throw new SceneRefusalError(path, `its card has ${triangles} triangles and ${vertices} vertices, over ${DETAIL_LIMITS.triangles} and ${DETAIL_LIMITS.vertices}`, 'Draw the clump as a few crossed cards');
|
|
300
|
+
if (!(cell >= DETAIL_LIMITS.cell[0] && cell <= DETAIL_LIMITS.cell[1])) throw new SceneRefusalError(path, `its cell ${cell} m is outside ${DETAIL_LIMITS.cell[0]} to ${DETAIL_LIMITS.cell[1]} m`, 'Count clumps per 0.5 to 8 m square');
|
|
301
|
+
if (!(request.radius >= DETAIL_LIMITS.radius[0] && request.radius <= DETAIL_LIMITS.radius[1])) throw new SceneRefusalError(path, `its radius ${request.radius} m is outside ${DETAIL_LIMITS.radius[0]} to ${DETAIL_LIMITS.radius[1]} m`, 'Grow it 4 to 200 m round the camera');
|
|
302
|
+
const sway = request.sway;
|
|
303
|
+
if (sway !== null && !(sway.amount >= 0 && sway.amount <= 1 && sway.rate >= DETAIL_LIMITS.rate[0] && sway.rate <= DETAIL_LIMITS.rate[1])) throw new SceneRefusalError(path, 'its sway is outside amount 0 to 1 and rate 0.05 to 10', 'Give sway an amount 0 to 1 and a rate in cycles a second');
|
|
304
|
+
const count = mesh.count;
|
|
305
|
+
if (count === 0) throw new SceneRefusalError(path, 'its InstancedMesh holds no copies', 'Fill the mesh before handing it to world.detail');
|
|
306
|
+
// every copy's world matrix: the mesh's own (it may sit in a part) times the copy's
|
|
307
|
+
mesh.updateMatrixWorld(true);
|
|
308
|
+
const seat = new Matrix4(), local = new Matrix4(), position = new Vector3(), rotation = new Quaternion(), size = new Vector3(), up = new Vector3();
|
|
309
|
+
const xs = new Float64Array(count), ys = new Float64Array(count), zs = new Float64Array(count);
|
|
310
|
+
let scaleLow = Infinity, scaleHigh = 0, tilt = 0;
|
|
311
|
+
for (let i = 0; i < count; i++) {
|
|
312
|
+
seat.multiplyMatrices(mesh.matrixWorld, local.fromArray(mesh.instanceMatrix.array, i * 16));
|
|
313
|
+
seat.decompose(position, rotation, size);
|
|
314
|
+
xs[i] = position.x; ys[i] = position.y; zs[i] = position.z;
|
|
315
|
+
const s = (Math.abs(size.x) + Math.abs(size.y) + Math.abs(size.z)) / 3;
|
|
316
|
+
scaleLow = Math.min(scaleLow, s); scaleHigh = Math.max(scaleHigh, s);
|
|
317
|
+
tilt = Math.max(tilt, Math.acos(Math.min(1, Math.max(-1, up.set(0, 1, 0).applyQuaternion(rotation).y))));
|
|
318
|
+
}
|
|
319
|
+
if (scaleLow < DETAIL_LIMITS.scale[0] || scaleHigh > DETAIL_LIMITS.scale[1]) throw new SceneRefusalError(path, `its copies scale ${scaleLow.toFixed(3)} to ${scaleHigh.toFixed(3)}, outside 0.05 to 20`, 'Size the card so its copies scale 0.05 to 20');
|
|
320
|
+
// the grid: whole cells from the low corner of the copies' box, at most 512 a side
|
|
321
|
+
let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity;
|
|
322
|
+
for (let i = 0; i < count; i++) { minX = Math.min(minX, xs[i] ?? 0); maxX = Math.max(maxX, xs[i] ?? 0); minZ = Math.min(minZ, zs[i] ?? 0); maxZ = Math.max(maxZ, zs[i] ?? 0); }
|
|
323
|
+
const corner: [number, number] = [Math.floor(minX / cell) * cell, Math.floor(minZ / cell) * cell];
|
|
324
|
+
const columns = Math.floor((maxX - corner[0]) / cell) + 1, rows = Math.floor((maxZ - corner[1]) / cell) + 1;
|
|
325
|
+
if (columns > DETAIL_LIMITS.side || rows > DETAIL_LIMITS.side) throw new SceneRefusalError(path, `its copies span ${columns} × ${rows} cells of ${cell} m, over ${DETAIL_LIMITS.side} a side`, 'Use a bigger cell, or split the clumps into two layers');
|
|
326
|
+
const counts = new Uint32Array(columns * rows), sums = new Float64Array(columns * rows);
|
|
327
|
+
for (let i = 0; i < count; i++) {
|
|
328
|
+
const c = Math.min(columns - 1, Math.floor(((xs[i] ?? 0) - corner[0]) / cell)), r = Math.min(rows - 1, Math.floor(((zs[i] ?? 0) - corner[1]) / cell)), at = r * columns + c;
|
|
329
|
+
counts[at] = (counts[at] ?? 0) + 1; sums[at] = (sums[at] ?? 0) + (ys[i] ?? 0);
|
|
330
|
+
}
|
|
331
|
+
let clumps = 0;
|
|
332
|
+
for (const n of counts) clumps = Math.max(clumps, n);
|
|
333
|
+
if (clumps > DETAIL_LIMITS.clumps) throw new SceneRefusalError(path, `its fullest ${cell} m cell holds ${clumps} copies, over ${DETAIL_LIMITS.clumps}`, 'Use a smaller cell, or fewer, bigger clumps');
|
|
334
|
+
let low = Infinity, high = -Infinity;
|
|
335
|
+
for (let at = 0; at < counts.length; at++) if ((counts[at] ?? 0) > 0) { const mean = (sums[at] ?? 0) / (counts[at] ?? 1); low = Math.min(low, mean); high = Math.max(high, mean); }
|
|
336
|
+
const mask = new Uint8Array(counts.length), heights = new Uint8Array(counts.length * 2), view = new DataView(heights.buffer);
|
|
337
|
+
for (let at = 0; at < counts.length; at++) {
|
|
338
|
+
const n = counts[at] ?? 0; mask[at] = Math.round((n / clumps) * 255);
|
|
339
|
+
const mean = n > 0 ? (sums[at] ?? 0) / n : low;
|
|
340
|
+
view.setUint16(at * 2, high > low ? Math.round(((mean - low) / (high - low)) * 65535) : 0, true);
|
|
341
|
+
}
|
|
342
|
+
// tint: each channel's lowest and highest instance colour (linear), or white
|
|
343
|
+
let tint: [Rgb, Rgb] = [[1, 1, 1], [1, 1, 1]];
|
|
344
|
+
const colours = mesh.instanceColor?.array;
|
|
345
|
+
if (colours !== undefined) {
|
|
346
|
+
const lo = [Infinity, Infinity, Infinity], hi = [-Infinity, -Infinity, -Infinity];
|
|
347
|
+
for (let i = 0; i < count; i++) for (let k = 0; k < 3; k++) { const v = colours[i * 3 + k] ?? 1; lo[k] = Math.min(lo[k] ?? v, v); hi[k] = Math.max(hi[k] ?? v, v); }
|
|
348
|
+
tint = [[lo[0] ?? 1, lo[1] ?? 1, lo[2] ?? 1], [hi[0] ?? 1, hi[1] ?? 1, hi[2] ?? 1]];
|
|
349
|
+
}
|
|
350
|
+
return {
|
|
351
|
+
id, path: mesh.name === '' ? path : mesh.name, geometry, material, region: { corner, cell, columns, rows, span: [low, Math.max(low, high)] }, mask, heights, clumps,
|
|
352
|
+
scale: [scaleLow, scaleHigh], tilt: Math.min(1, tilt), tint, sway, radius: request.radius, shadow: request.shadow, instances: count,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
277
356
|
/** Run the author's build on a fresh scene and read it. Parts come in authored order; `scene` holds anything outside one. */
|
|
278
357
|
export function lowerShard(identity: ShardIdentityInput, build: (world: ShardWorld) => void): ShardScene {
|
|
279
358
|
const scene = new Scene(), parts: Group[] = [], panels = new Map<Object3D, string>();
|
|
280
359
|
let sky: SceneSky | null = null;
|
|
281
360
|
let ground: SceneGround | null = null, post: ScenePost | null = null, spawn: ShardScene['spawn'] = { position: [0, 0, 0], yaw: 0 };
|
|
361
|
+
// AP25: rows placed at nodes; read once the build has run and every matrix is current
|
|
362
|
+
const triggers: { id: string; at: Object3D; radius: number; flag: string }[] = [], interactions: { id: string; at: Object3D; radius: number; label: string; scene: string; unless?: string }[] = [];
|
|
363
|
+
const anchorIds = new Set<string>(), detailRequests: DetailRequest[] = [];
|
|
364
|
+
const anchor = (kind: string, id: string): void => {
|
|
365
|
+
if (!/^[a-z][a-zA-Z0-9.-]{0,127}$/u.test(id)) throw new SceneRefusalError(id, `a ${kind} id is not a shardfile id`, 'Name it like `slice.pond`: a lower-case letter, then letters, digits, dots and dashes');
|
|
366
|
+
if (anchorIds.has(`${kind}:${id}`)) throw new SceneRefusalError(id, `two ${kind}s share this id`, `Give every world.${kind} its own id`);
|
|
367
|
+
anchorIds.add(`${kind}:${id}`);
|
|
368
|
+
};
|
|
282
369
|
const world: ShardWorld = {
|
|
283
370
|
scene,
|
|
284
371
|
part: (name, fill, options = {}) => {
|
|
@@ -312,6 +399,24 @@ export function lowerShard(identity: ShardIdentityInput, build: (world: ShardWor
|
|
|
312
399
|
environment: env === undefined ? null : { intensity: env.intensity, ground: [env.ground[0], env.ground[1], env.ground[2]] } };
|
|
313
400
|
},
|
|
314
401
|
spawn: (x, y, z, yaw = 0) => { spawn = { position: [x, y, z], yaw }; },
|
|
402
|
+
trigger: (id, at, options) => {
|
|
403
|
+
anchor('trigger', id);
|
|
404
|
+
if (!(options.radius >= 0.01 && options.radius <= 500)) throw new SceneRefusalError(id, `a trigger's radius ${options.radius} is outside 0.01 to 500 m`, 'Give it a radius in metres between 0.01 and 500');
|
|
405
|
+
triggers.push({ id, at, radius: options.radius, flag: options.flag ?? id });
|
|
406
|
+
},
|
|
407
|
+
interact: (id, at, options) => {
|
|
408
|
+
anchor('interact', id);
|
|
409
|
+
if (!(options.radius >= 0.1 && options.radius <= 8)) throw new SceneRefusalError(id, `a use prompt's radius ${options.radius} is outside 0.1 to 8 m`, 'Give it a reach in metres between 0.1 and 8');
|
|
410
|
+
if (options.label.length === 0 || options.label.length > 128) throw new SceneRefusalError(id, 'a use prompt\'s label is 1 to 128 characters', 'Shorten the label');
|
|
411
|
+
interactions.push({ id, at, ...options });
|
|
412
|
+
},
|
|
413
|
+
detail: (id, mesh, options) => {
|
|
414
|
+
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/u.test(id)) throw new SceneRefusalError(id, 'a detail id is not a look id', 'Name it like `moss-grass`: lower case, digits, dots, dashes and underscores');
|
|
415
|
+
if (detailRequests.some((d) => d.id === id)) throw new SceneRefusalError(id, 'two detail layers share this id', 'Give every world.detail its own id');
|
|
416
|
+
if (detailRequests.length >= DETAIL_LIMITS.layers) throw new SceneRefusalError(id, `a look holds at most ${DETAIL_LIMITS.layers} detail layers`, 'Merge layers that share a card');
|
|
417
|
+
if (!(mesh instanceof InstancedMesh)) throw new SceneRefusalError(id, 'world.detail takes an InstancedMesh', 'Build the clumps as one InstancedMesh of a small card');
|
|
418
|
+
detailRequests.push({ id, mesh, cell: options.cell, radius: options.radius, sway: options.sway ?? null, shadow: options.shadow ?? false });
|
|
419
|
+
},
|
|
315
420
|
};
|
|
316
421
|
build(world);
|
|
317
422
|
scene.updateMatrixWorld(true);
|
|
@@ -320,14 +425,33 @@ export function lowerShard(identity: ShardIdentityInput, build: (world: ShardWor
|
|
|
320
425
|
for (const child of scene.children.slice()) if (!parts.includes(child as Group)) loose.add(child);
|
|
321
426
|
const roots = loose.children.length > 0 ? [...parts, loose] : parts;
|
|
322
427
|
scene.add(loose); scene.updateMatrixWorld(true);
|
|
323
|
-
const tables: Tables = { materials: new Map(), textures: new Map(), geometries: new Map(), geometryKeys: new WeakMap(), materialKeys: new WeakMap(), textureKeys: new WeakMap()
|
|
428
|
+
const tables: Tables = { materials: new Map(), textures: new Map(), geometries: new Map(), geometryKeys: new WeakMap(), materialKeys: new WeakMap(), textureKeys: new WeakMap(),
|
|
429
|
+
details: new Set(detailRequests.map((request) => request.mesh)) };
|
|
324
430
|
const lowered = roots.map((root) => lowerPart(root, tables, panels.get(root)));
|
|
431
|
+
const details = detailRequests.map((request) => lowerDetail(request, tables));
|
|
325
432
|
const fog: SceneLook['fog'] = scene.fog instanceof FogExp2 ? { kind: 'exp2', colour: rgb(scene.fog.color), density: scene.fog.density }
|
|
326
433
|
: scene.fog instanceof Fog ? { kind: 'linear', colour: rgb(scene.fog.color), near: scene.fog.near, far: scene.fog.far } : null;
|
|
327
434
|
const background = scene.background !== null && typeof scene.background === 'object' && 'isColor' in scene.background ? rgb(scene.background as Color) : null;
|
|
435
|
+
const placed = (id: string, at: Object3D): Vector3 => {
|
|
436
|
+
let root: Object3D = at; while (root.parent !== null) root = root.parent;
|
|
437
|
+
if (root !== scene) throw new SceneRefusalError(id, 'its node is not in the scene', 'Add the node to a part (or the scene) before the build returns');
|
|
438
|
+
const p = at.getWorldPosition(new Vector3());
|
|
439
|
+
if (Math.abs(p.x) > 250 || Math.abs(p.z) > 250 || Math.abs(p.y) > 250) throw new SceneRefusalError(id, 'its node stands outside the 500 m cell', 'Move the node inside the cell (x, y and z within 250 m)');
|
|
440
|
+
return p;
|
|
441
|
+
};
|
|
442
|
+
const r3 = (n: number): number => Math.round(n * 1000) / 1000;
|
|
443
|
+
const anchored: ShardScene['anchored'] = {
|
|
444
|
+
triggers: triggers.map((t) => { const p = placed(t.id, t.at); return { id: t.id, kind: 'region' as const, flag: t.flag, x: r3(p.x), z: r3(p.z), radius: t.radius }; }),
|
|
445
|
+
interactions: interactions.map((i) => {
|
|
446
|
+
const p = placed(i.id, i.at), row: { id: string; at: readonly [number, number, number]; radius: number; label: string; scene: string; unless?: string } = { id: i.id, at: [r3(p.x), r3(p.y), r3(p.z)], radius: i.radius, label: i.label, scene: i.scene };
|
|
447
|
+
if (i.unless !== undefined) row.unless = i.unless;
|
|
448
|
+
return row;
|
|
449
|
+
}),
|
|
450
|
+
};
|
|
328
451
|
return {
|
|
329
452
|
identity, parts: lowered, materials: Object.fromEntries(tables.materials), textures: Object.fromEntries(tables.textures),
|
|
330
|
-
geometries: Object.fromEntries(tables.geometries), look: { fog, background, post, sky }, ground, spawn,
|
|
453
|
+
geometries: Object.fromEntries(tables.geometries), look: { fog, background, post, sky }, ground, spawn, anchored,
|
|
454
|
+
...(details.length === 0 ? {} : { details }),
|
|
331
455
|
};
|
|
332
456
|
}
|
|
333
457
|
|