@wildshard/sdk 0.2.12 → 0.3.0
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 +16 -11
- package/bin/wildshard.mjs +2 -1
- package/docs/api/EXPORT-TIERS.md +12 -3
- package/lint/export-tiers.json +9 -0
- package/lint/tile-bake-debt.json +26 -1
- package/package.json +17 -5
- package/scripts/build-shardfiles.mjs +7 -2
- package/scripts/preparation-preview.mjs +6 -1
- package/scripts/prepare-product.mjs +2 -2
- package/scripts/scratch-sweep.mjs +180 -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/assets.ts +1 -1
- package/src/sharddev/bake/compactGlb.ts +1 -1
- 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 +1 -1
- package/src/sharddev/blobBytes.ts +1 -1
- package/src/sharddev/blobs.ts +2 -2
- package/src/sharddev/cli.ts +17 -4
- package/src/sharddev/formatJsonSchema.ts +1 -1
- package/src/sharddev/materialGraphFiles.ts +1 -1
- 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 +1 -1
- package/src/sharddev/projectMap.ts +1 -1
- package/src/sharddev/refusals.ts +4 -2
- package/src/sharddev/reportCard.ts +1 -1
- package/src/sharddev/scene/author.ts +79 -0
- package/src/sharddev/scene/canvas.ts +213 -0
- package/src/sharddev/scene/description.ts +170 -0
- package/src/sharddev/scene/hash.ts +23 -0
- package/src/sharddev/scene/lower.ts +226 -0
- package/src/sharddev/scene/shard.ts +38 -0
- package/src/sharddev/scene/shardfile.ts +328 -0
- package/src/sharddev/threeGate.mjs +14 -0
- package/src/sharddev/threePin.mjs +40 -0
- package/src/sharddev/watch/page.ts +197 -0
- package/src/sharddev/watch/pageEntry.ts +23 -0
- package/src/sharddev/watch/proof.mjs +92 -0
- package/src/sharddev/watch/protocol.ts +108 -0
- package/src/sharddev/watch/socket.ts +57 -0
- package/src/sharddev/watch/watch.ts +209 -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/card.json +21 -14
- package/src/shards/_template/data/clientScripts.json +27 -27
- package/src/shards/_template/data/creatures.json +5 -5
- package/src/shards/_template/data/encounters.json +2 -2
- package/src/shards/_template/data/layout.json +56 -25
- package/src/shards/_template/data/look.json +450 -220
- package/src/shards/_template/data/quests.json +2 -2
- package/src/shards/_template/data/water.json +131 -4
- package/src/shards/_template/generators/landscape.ts +19 -7
- package/src/shards/_template/generators/product.ts +7 -5
- package/src/shards/_template/generators/templatePropsSource.ts +3 -1
- package/src/shards/_template/generators/terrain.ts +28 -4
- package/src/shards/_template/generators/weather.ts +128 -0
- package/src/shards/_template/generators/world.ts +274 -98
- package/src/shards/_template/hero.json +6 -6
- package/src/shards/_template/manifest.json +21 -14
- package/src/shards/authoring-slice/generators/shard.ts +6 -0
- package/src/shards/authoring-slice/generators/textures.ts +173 -0
- package/src/shards/authoring-slice/generators/world.ts +415 -0
- package/src/shards/authoring-slice/shard.config.ts +7 -0
- package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AUTHORING-PARITY AP1: the scene description. An author writes an ordinary three.js scene inside `defineShard`; the
|
|
3
|
+
* walker (`lower.ts`) reads it once into this plain, serialisable shape, and both back ends read only this: the shardfile
|
|
4
|
+
* back end (`shardfile.ts`, `wildshard build`) and the dev transport (`../watch`, `wildshard watch`).
|
|
5
|
+
*
|
|
6
|
+
* Every number is in world metres and linear colour. Geometry is kept in its own frame and deduplicated (a shared
|
|
7
|
+
* `BoxGeometry` is one entry), so a part of 1,000 placed boxes is one geometry and 1,000 matrices, as three draws it.
|
|
8
|
+
* Each part carries a content hash, so a re-run that changes one part changes only that part's hash.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Linear RGB, each 0..n (an HDR emissive may exceed 1). */
|
|
12
|
+
export type Rgb = readonly [number, number, number];
|
|
13
|
+
export type Vec3 = readonly [number, number, number];
|
|
14
|
+
|
|
15
|
+
/** An RGBA8 raster the author painted (`paint`) or handed in as a `DataTexture`. Row 0 is v = 0 (three's DataTexture). */
|
|
16
|
+
export interface SceneTexture {
|
|
17
|
+
readonly key: string;
|
|
18
|
+
readonly width: number;
|
|
19
|
+
readonly height: number;
|
|
20
|
+
readonly rgba: Uint8Array;
|
|
21
|
+
readonly colourSpace: 'srgb' | 'linear';
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A lowered material: the fields of `MeshStandardMaterial` / `MeshBasicMaterial` / `SpriteMaterial` an M1 scene uses. */
|
|
25
|
+
export interface SceneMaterial {
|
|
26
|
+
readonly key: string;
|
|
27
|
+
/** the author's `material.name`, or the key */
|
|
28
|
+
readonly name: string;
|
|
29
|
+
readonly kind: 'standard' | 'basic' | 'sprite';
|
|
30
|
+
readonly colour: Rgb;
|
|
31
|
+
readonly roughness: number;
|
|
32
|
+
readonly metalness: number;
|
|
33
|
+
readonly emissive: Rgb;
|
|
34
|
+
readonly emissiveIntensity: number;
|
|
35
|
+
/** a `SceneTexture` key */
|
|
36
|
+
readonly map: string | null;
|
|
37
|
+
/** the map's `repeat` and `offset` (uv' = uv * repeat + offset) */
|
|
38
|
+
readonly repeat: readonly [number, number];
|
|
39
|
+
readonly offset: readonly [number, number];
|
|
40
|
+
readonly alphaTest: number;
|
|
41
|
+
readonly side: 'front' | 'back' | 'double';
|
|
42
|
+
readonly vertexColours: boolean;
|
|
43
|
+
readonly transparent: boolean;
|
|
44
|
+
readonly opacity: number;
|
|
45
|
+
readonly blending: 'normal' | 'additive';
|
|
46
|
+
readonly depthWrite: boolean;
|
|
47
|
+
readonly fog: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** One geometry in its own frame. `colour` is 3 floats per vertex when present. */
|
|
51
|
+
export interface SceneGeometry {
|
|
52
|
+
readonly key: string;
|
|
53
|
+
readonly position: Float32Array;
|
|
54
|
+
readonly normal: Float32Array;
|
|
55
|
+
readonly uv: Float32Array | null;
|
|
56
|
+
readonly colour: Float32Array | null;
|
|
57
|
+
readonly index: Uint32Array | null;
|
|
58
|
+
/** triangles in one copy */
|
|
59
|
+
readonly triangles: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** One mesh draw: a geometry in one material at a world matrix, optionally instanced. */
|
|
63
|
+
export interface SceneDraw {
|
|
64
|
+
/** the object's path under its part (`hut/Mesh 3`), for messages and reports */
|
|
65
|
+
readonly path: string;
|
|
66
|
+
readonly geometry: string;
|
|
67
|
+
readonly material: string;
|
|
68
|
+
/** column-major world matrix */
|
|
69
|
+
readonly matrix: readonly number[];
|
|
70
|
+
/** an `InstancedMesh`'s live instances: their local matrices (16 floats each, column-major) and colours (3 each) */
|
|
71
|
+
readonly instances: { readonly count: number; readonly matrices: Float32Array; readonly colours: Float32Array | null } | null;
|
|
72
|
+
readonly castShadow: boolean;
|
|
73
|
+
readonly receiveShadow: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A `Sprite`: a camera-facing card at a world point. */
|
|
77
|
+
export interface SceneSprite {
|
|
78
|
+
readonly path: string;
|
|
79
|
+
readonly material: string;
|
|
80
|
+
readonly position: Vec3;
|
|
81
|
+
readonly scale: readonly [number, number];
|
|
82
|
+
readonly center: readonly [number, number];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface SceneLight {
|
|
86
|
+
readonly path: string;
|
|
87
|
+
readonly kind: 'point' | 'directional' | 'hemisphere' | 'ambient';
|
|
88
|
+
readonly colour: Rgb;
|
|
89
|
+
/** hemisphere only */
|
|
90
|
+
readonly groundColour: Rgb | null;
|
|
91
|
+
readonly intensity: number;
|
|
92
|
+
/** point only: three's range (0 = infinite) and decay */
|
|
93
|
+
readonly distance: number;
|
|
94
|
+
readonly decay: number;
|
|
95
|
+
readonly position: Vec3;
|
|
96
|
+
/** directional only: where it points */
|
|
97
|
+
readonly target: Vec3 | null;
|
|
98
|
+
readonly castShadow: boolean;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A solid box, said once by `solid(mesh)`: the mesh's own bounds in its world frame. */
|
|
102
|
+
export interface SceneCollider {
|
|
103
|
+
readonly path: string;
|
|
104
|
+
readonly kind: 'cuboid';
|
|
105
|
+
readonly centre: Vec3;
|
|
106
|
+
readonly half: Vec3;
|
|
107
|
+
/** world rotation quaternion (x, y, z, w) */
|
|
108
|
+
readonly rotation: readonly [number, number, number, number];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A `Water` surface: its outline (world x, z) and level, taken from its own geometry. */
|
|
112
|
+
export interface SceneWater {
|
|
113
|
+
readonly path: string;
|
|
114
|
+
readonly outline: readonly (readonly [number, number])[];
|
|
115
|
+
readonly level: number;
|
|
116
|
+
readonly tint: Rgb;
|
|
117
|
+
readonly reflect: 'planar' | 'sky';
|
|
118
|
+
/** the surface triangles in world space (x, y, z per vertex, non-indexed), for the dev page */
|
|
119
|
+
readonly triangles: Float32Array;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface ScenePart {
|
|
123
|
+
readonly name: string;
|
|
124
|
+
/** content hash of everything below and of the materials, textures and geometries it uses */
|
|
125
|
+
readonly hash: string;
|
|
126
|
+
readonly draws: readonly SceneDraw[];
|
|
127
|
+
readonly sprites: readonly SceneSprite[];
|
|
128
|
+
readonly lights: readonly SceneLight[];
|
|
129
|
+
readonly colliders: readonly SceneCollider[];
|
|
130
|
+
readonly water: readonly SceneWater[];
|
|
131
|
+
readonly materials: readonly string[];
|
|
132
|
+
readonly textures: readonly string[];
|
|
133
|
+
readonly geometries: readonly string[];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** `world.post(...)`: the cleanroom's composer, as numbers. */
|
|
137
|
+
export interface ScenePost {
|
|
138
|
+
readonly tone: 'aces' | 'neutral' | 'none';
|
|
139
|
+
readonly exposure: number;
|
|
140
|
+
readonly bloom: { readonly strength: number; readonly radius: number; readonly threshold: number } | null;
|
|
141
|
+
readonly vignette: number;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface SceneLook {
|
|
145
|
+
readonly fog: { readonly kind: 'exp2'; readonly colour: Rgb; readonly density: number } | { readonly kind: 'linear'; readonly colour: Rgb; readonly near: number; readonly far: number } | null;
|
|
146
|
+
readonly background: Rgb | null;
|
|
147
|
+
readonly post: ScenePost | null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The ground the author declared with `world.ground(heightAt)`: closures stay at compile time, never on the wire. */
|
|
151
|
+
export interface SceneGround {
|
|
152
|
+
readonly heightAt: (x: number, z: number) => number;
|
|
153
|
+
readonly colourAt: ((x: number, z: number) => Rgb) | null;
|
|
154
|
+
/** a hash of the height field sampled on a 2 m grid, so a re-run knows whether the ground changed */
|
|
155
|
+
readonly hash: string;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface ShardIdentityInput { readonly slug: string; readonly name: string; readonly author?: string; readonly revision?: number; readonly seed?: number }
|
|
159
|
+
|
|
160
|
+
/** Everything the walker read from one run of the author's scene. */
|
|
161
|
+
export interface ShardScene {
|
|
162
|
+
readonly identity: ShardIdentityInput;
|
|
163
|
+
readonly parts: readonly ScenePart[];
|
|
164
|
+
readonly materials: Readonly<Record<string, SceneMaterial>>;
|
|
165
|
+
readonly textures: Readonly<Record<string, SceneTexture>>;
|
|
166
|
+
readonly geometries: Readonly<Record<string, SceneGeometry>>;
|
|
167
|
+
readonly look: SceneLook;
|
|
168
|
+
readonly ground: SceneGround | null;
|
|
169
|
+
readonly spawn: { readonly position: Vec3; readonly yaw: number };
|
|
170
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** AP1: a small, stable content hash for scene parts (two FNV-1a lanes, 64 bits as hex). Not a security hash: it only
|
|
2
|
+
* tells a re-run which parts changed. Pure JavaScript, so it runs in an author bundle and in the dev page alike. */
|
|
3
|
+
export class ContentHash {
|
|
4
|
+
private a = 0x811c9dc5;
|
|
5
|
+
private b = 0x01000193 ^ 0x5bd1e995;
|
|
6
|
+
bytes(view: ArrayBufferView): this {
|
|
7
|
+
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
|
|
8
|
+
let a = this.a, b = this.b;
|
|
9
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
10
|
+
const byte = bytes[i] ?? 0;
|
|
11
|
+
a = Math.imul(a ^ byte, 0x01000193);
|
|
12
|
+
b = Math.imul(b ^ byte, 0x5bd1e995) ^ (b >>> 15);
|
|
13
|
+
}
|
|
14
|
+
this.a = a; this.b = b;
|
|
15
|
+
return this;
|
|
16
|
+
}
|
|
17
|
+
text(value: string): this { return this.bytes(new TextEncoder().encode(`${value}\u0000`)); }
|
|
18
|
+
numbers(values: readonly number[]): this { return this.bytes(Float64Array.from(values)); }
|
|
19
|
+
json(value: unknown): this { return this.text(JSON.stringify(value)); }
|
|
20
|
+
hex(): string { return (this.a >>> 0).toString(16).padStart(8, '0') + (this.b >>> 0).toString(16).padStart(8, '0'); }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const hashOf = (fill: (hash: ContentHash) => void): string => { const hash = new ContentHash(); fill(hash); return hash.hex(); };
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AdditiveBlending, AmbientLight, BackSide, Box3, DataTexture, DirectionalLight, DoubleSide, Fog, FogExp2, Group, HemisphereLight, InstancedMesh, Line, Matrix4,
|
|
3
|
+
Mesh, MeshBasicMaterial, MeshStandardMaterial, type Object3D, PointLight, Points, Quaternion, Scene, SpotLight, Sprite, SpriteMaterial, Vector3,
|
|
4
|
+
type BufferAttribute, type BufferGeometry, type Color, type InterleavedBufferAttribute, type Material, type Texture,
|
|
5
|
+
} from 'three';
|
|
6
|
+
import { isSolid, paintedPixels, Water, type ShardWorld } from './author';
|
|
7
|
+
import type {
|
|
8
|
+
Rgb, SceneCollider, SceneDraw, SceneGeometry, SceneGround, SceneLight, SceneLook, SceneMaterial, ScenePart, ScenePost, SceneSprite, SceneTexture,
|
|
9
|
+
SceneWater, ShardIdentityInput, ShardScene, Vec3,
|
|
10
|
+
} from './description';
|
|
11
|
+
import { ContentHash, hashOf } from './hash';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* AUTHORING-PARITY AP1: the walker. It runs the author's build function on a fresh `Scene`, then reads every object once
|
|
15
|
+
* into a `ShardScene`. It refuses only what has no lowering yet, naming the object's path, its type and the row that
|
|
16
|
+
* adds it, so an author is never left with a silently missing thing.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** A refusal: the object's path and the fix. */
|
|
20
|
+
export class SceneRefusalError extends Error {
|
|
21
|
+
constructor(path: string, problem: string, fix: string) { super(`scene: ${path}: ${problem}. ${fix}`); this.name = 'SceneRefusalError'; }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const rgb = (colour: Color, scale = 1): Rgb => [colour.r * scale, colour.g * scale, colour.b * scale];
|
|
25
|
+
const v3 = (v: Vector3): Vec3 => [v.x, v.y, v.z];
|
|
26
|
+
|
|
27
|
+
interface Tables {
|
|
28
|
+
materials: Map<string, SceneMaterial>; textures: Map<string, SceneTexture>; geometries: Map<string, SceneGeometry>;
|
|
29
|
+
geometryKeys: WeakMap<BufferGeometry, string>; materialKeys: WeakMap<Material, string>; textureKeys: WeakMap<Texture, string>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function floats(attribute: BufferAttribute | InterleavedBufferAttribute, width: number): Float32Array {
|
|
33
|
+
const out = new Float32Array(attribute.count * width);
|
|
34
|
+
for (let i = 0; i < attribute.count; i++) for (let c = 0; c < width; c++) out[i * width + c] = c < attribute.itemSize ? attribute.getComponent(i, c) : 0;
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function lowerGeometry(geometry: BufferGeometry, path: string, tables: Tables): string {
|
|
39
|
+
const known = tables.geometryKeys.get(geometry); if (known !== undefined) return known;
|
|
40
|
+
const positionAttribute = geometry.getAttribute('position');
|
|
41
|
+
if (positionAttribute === undefined) throw new SceneRefusalError(path, 'its geometry has no position', 'Give the geometry a position attribute');
|
|
42
|
+
if (!geometry.hasAttribute('normal')) geometry.computeVertexNormals();
|
|
43
|
+
const index = geometry.getIndex(), count = index?.count ?? positionAttribute.count;
|
|
44
|
+
if (count % 3 !== 0) throw new SceneRefusalError(path, 'its geometry is not triangles', 'Draw lines and points with Line / Points once AP11 lands; a Mesh must be triangles');
|
|
45
|
+
const position = floats(positionAttribute, 3), normal = floats(geometry.getAttribute('normal'), 3);
|
|
46
|
+
const uv = geometry.hasAttribute('uv') ? floats(geometry.getAttribute('uv'), 2) : null;
|
|
47
|
+
const colour = geometry.hasAttribute('color') ? floats(geometry.getAttribute('color'), 3) : null;
|
|
48
|
+
const indices = index === null ? null : Uint32Array.from(index.array);
|
|
49
|
+
const key = `g${hashOf((h) => { h.bytes(position).bytes(normal); if (uv !== null) h.text('uv').bytes(uv); if (colour !== null) h.text('colour').bytes(colour); if (indices !== null) h.text('index').bytes(indices); })}`;
|
|
50
|
+
if (!tables.geometries.has(key)) tables.geometries.set(key, { key, position, normal, uv, colour, index: indices, triangles: count / 3 });
|
|
51
|
+
tables.geometryKeys.set(geometry, key);
|
|
52
|
+
return key;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function lowerTexture(texture: Texture, path: string, tables: Tables): string {
|
|
56
|
+
const known = tables.textureKeys.get(texture); if (known !== undefined) return known;
|
|
57
|
+
let pixels = paintedPixels(texture.source);
|
|
58
|
+
if (pixels === undefined && texture instanceof DataTexture) {
|
|
59
|
+
const { data, width, height } = texture.image as { data: unknown; width: number; height: number };
|
|
60
|
+
if ((data instanceof Uint8Array || data instanceof Uint8ClampedArray) && data.length === width * height * 4) pixels = { width, height, rgba: new Uint8Array(data.buffer, data.byteOffset, data.byteLength) };
|
|
61
|
+
}
|
|
62
|
+
if (pixels === undefined) throw new SceneRefusalError(path, `texture ${texture.name || texture.constructor.name} has no pixels at compile time`, 'Paint it with paint(width, height, fn) from @wildshard/sdk/scene/shard (a CanvasTexture needs a browser), or hand in an RGBA8 DataTexture');
|
|
63
|
+
const colourSpace = texture.colorSpace === 'srgb' ? 'srgb' : 'linear';
|
|
64
|
+
const key = `t${hashOf((h) => { h.numbers([pixels.width, pixels.height]).text(colourSpace).bytes(pixels.rgba); })}`;
|
|
65
|
+
if (!tables.textures.has(key)) tables.textures.set(key, { key, width: pixels.width, height: pixels.height, rgba: pixels.rgba, colourSpace });
|
|
66
|
+
tables.textureKeys.set(texture, key);
|
|
67
|
+
return key;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function lowerMaterial(material: Material, path: string, tables: Tables): string {
|
|
71
|
+
const known = tables.materialKeys.get(material); if (known !== undefined) return known;
|
|
72
|
+
let kind: SceneMaterial['kind'];
|
|
73
|
+
if (material instanceof MeshStandardMaterial) kind = 'standard';
|
|
74
|
+
else if (material instanceof MeshBasicMaterial) kind = 'basic';
|
|
75
|
+
else if (material instanceof SpriteMaterial) kind = 'sprite';
|
|
76
|
+
else throw new SceneRefusalError(path, `${material.type} has no lowering yet`, 'Use MeshStandardMaterial or MeshBasicMaterial; node (TSL) materials arrive with AP13');
|
|
77
|
+
const m = material as MeshStandardMaterial & MeshBasicMaterial & SpriteMaterial;
|
|
78
|
+
const map = m.map === null || m.map === undefined ? null : lowerTexture(m.map, path, tables);
|
|
79
|
+
const standard = material instanceof MeshStandardMaterial;
|
|
80
|
+
const fields: Omit<SceneMaterial, 'key' | 'name'> = {
|
|
81
|
+
kind, colour: rgb(m.color), roughness: standard ? m.roughness : 1, metalness: standard ? m.metalness : 0,
|
|
82
|
+
emissive: standard ? rgb(m.emissive) : [0, 0, 0], emissiveIntensity: standard ? m.emissiveIntensity : 0, map,
|
|
83
|
+
repeat: m.map ? [m.map.repeat.x, m.map.repeat.y] : [1, 1], offset: m.map ? [m.map.offset.x, m.map.offset.y] : [0, 0],
|
|
84
|
+
alphaTest: material.alphaTest, side: material.side === DoubleSide ? 'double' : material.side === BackSide ? 'back' : 'front',
|
|
85
|
+
vertexColours: material.vertexColors, transparent: material.transparent, opacity: material.opacity,
|
|
86
|
+
blending: material.blending === AdditiveBlending ? 'additive' : 'normal', depthWrite: material.depthWrite, fog: m.fog !== false,
|
|
87
|
+
};
|
|
88
|
+
const key = `m${hashOf((h) => h.json(fields))}`;
|
|
89
|
+
if (!tables.materials.has(key)) tables.materials.set(key, { key, name: material.name === '' ? key : material.name, ...fields });
|
|
90
|
+
tables.materialKeys.set(material, key);
|
|
91
|
+
return key;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The object's path under its part: names where given, else `Type index`. */
|
|
95
|
+
function pathOf(object: Object3D, root: Object3D): string {
|
|
96
|
+
const parts: string[] = [];
|
|
97
|
+
for (let node: Object3D | null = object; node !== null && node !== root; node = node.parent) {
|
|
98
|
+
const index = node.parent === null ? 0 : node.parent.children.indexOf(node);
|
|
99
|
+
parts.unshift(node.name === '' ? `${node.type} ${index}` : node.name);
|
|
100
|
+
}
|
|
101
|
+
return [root.name, ...parts].join('/');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function colliderOf(path: string, matrix: Matrix4, box: Box3): SceneCollider {
|
|
105
|
+
const centre = box.getCenter(new Vector3()), size = box.getSize(new Vector3());
|
|
106
|
+
const position = new Vector3(), rotation = new Quaternion(), scale = new Vector3();
|
|
107
|
+
matrix.decompose(position, rotation, scale);
|
|
108
|
+
const world = centre.clone().applyMatrix4(matrix);
|
|
109
|
+
return { path, kind: 'cuboid', centre: v3(world), half: [Math.abs(size.x * scale.x) / 2, Math.abs(size.y * scale.y) / 2, Math.abs(size.z * scale.z) / 2], rotation: [rotation.x, rotation.y, rotation.z, rotation.w] };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function lowerPart(root: Object3D, tables: Tables): ScenePart {
|
|
113
|
+
const draws: SceneDraw[] = [], sprites: SceneSprite[] = [], lights: SceneLight[] = [], colliders: SceneCollider[] = [], water: SceneWater[] = [];
|
|
114
|
+
const visit = (object: Object3D): void => {
|
|
115
|
+
const path = pathOf(object, root);
|
|
116
|
+
if (!object.visible) {
|
|
117
|
+
// an invisible solid is a collider only: said once, drawn never
|
|
118
|
+
if (object instanceof Mesh && isSolid(object)) { object.geometry.computeBoundingBox(); colliders.push(colliderOf(path, object.matrixWorld, object.geometry.boundingBox ?? new Box3())); }
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (object instanceof Water) {
|
|
122
|
+
// the format holds at most 64 outline points: 48 evenly spaced along the shape
|
|
123
|
+
const points = object.shape.getSpacedPoints(48).slice(0, 48).map((p) => new Vector3(p.x, p.y, 0).applyMatrix4(object.matrixWorld));
|
|
124
|
+
const geometry = object.geometry, position = geometry.getAttribute('position'), index = geometry.getIndex(), n = index?.count ?? position.count;
|
|
125
|
+
const triangles = new Float32Array(n * 3);
|
|
126
|
+
for (let i = 0; i < n; i++) { const p = new Vector3().fromBufferAttribute(position, index?.getX(i) ?? i).applyMatrix4(object.matrixWorld); triangles.set([p.x, p.y, p.z], i * 3); }
|
|
127
|
+
const level = new Vector3().setFromMatrixPosition(object.matrixWorld).y;
|
|
128
|
+
water.push({ path, outline: points.map((p) => [p.x, p.z] as const), level, tint: rgb(object.material.color), reflect: object.reflect, triangles });
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (object instanceof Mesh) {
|
|
132
|
+
if (Array.isArray(object.material)) throw new SceneRefusalError(path, 'it has several materials', 'Split it into one mesh per material');
|
|
133
|
+
const geometry = lowerGeometry(object.geometry, path, tables), material = lowerMaterial(object.material, path, tables);
|
|
134
|
+
let instances: SceneDraw['instances'] = null;
|
|
135
|
+
if (object instanceof InstancedMesh) {
|
|
136
|
+
const count = object.count, matrices = new Float32Array(object.instanceMatrix.array.buffer, object.instanceMatrix.array.byteOffset, count * 16).slice();
|
|
137
|
+
const colours = object.instanceColor === null ? null : new Float32Array(object.instanceColor.array.buffer, object.instanceColor.array.byteOffset, count * 3).slice();
|
|
138
|
+
instances = { count, matrices, colours };
|
|
139
|
+
if (isSolid(object)) {
|
|
140
|
+
object.geometry.computeBoundingBox(); const box = object.geometry.boundingBox ?? new Box3();
|
|
141
|
+
for (let i = 0; i < count; i++) colliders.push(colliderOf(`${path}#${i}`, object.matrixWorld.clone().multiply(new Matrix4().fromArray(matrices, i * 16)), box));
|
|
142
|
+
}
|
|
143
|
+
} else if (isSolid(object)) {
|
|
144
|
+
object.geometry.computeBoundingBox(); colliders.push(colliderOf(path, object.matrixWorld, object.geometry.boundingBox ?? new Box3()));
|
|
145
|
+
}
|
|
146
|
+
draws.push({ path, geometry, material, matrix: [...object.matrixWorld.elements], instances, castShadow: object.castShadow, receiveShadow: object.receiveShadow });
|
|
147
|
+
} else if (object instanceof Sprite) {
|
|
148
|
+
const material = lowerMaterial(object.material, path, tables), scale = new Vector3().setFromMatrixScale(object.matrixWorld);
|
|
149
|
+
sprites.push({ path, material, position: v3(new Vector3().setFromMatrixPosition(object.matrixWorld)), scale: [scale.x, scale.y], center: [object.center.x, object.center.y] });
|
|
150
|
+
} else if (object instanceof PointLight || object instanceof DirectionalLight || object instanceof HemisphereLight || object instanceof AmbientLight) {
|
|
151
|
+
const position = v3(new Vector3().setFromMatrixPosition(object.matrixWorld));
|
|
152
|
+
const kind: SceneLight['kind'] = object instanceof PointLight ? 'point' : object instanceof DirectionalLight ? 'directional' : object instanceof HemisphereLight ? 'hemisphere' : 'ambient';
|
|
153
|
+
lights.push({ path, kind, colour: rgb(object.color), groundColour: object instanceof HemisphereLight ? rgb(object.groundColor) : null, intensity: object.intensity,
|
|
154
|
+
distance: object instanceof PointLight ? object.distance : 0, decay: object instanceof PointLight ? object.decay : 0, position,
|
|
155
|
+
target: object instanceof DirectionalLight ? v3(object.target.getWorldPosition(new Vector3())) : null, castShadow: object.castShadow });
|
|
156
|
+
} else if (object instanceof SpotLight) {
|
|
157
|
+
throw new SceneRefusalError(path, 'SpotLight has no lowering yet', 'Use a PointLight; spot lamps are an engine row after M1');
|
|
158
|
+
} else if (object instanceof Points || object instanceof Line) {
|
|
159
|
+
throw new SceneRefusalError(path, `${object.type} has no lowering yet`, 'Motes and lines arrive with AP11; leave them out of the part until then');
|
|
160
|
+
} else if (isSolid(object)) {
|
|
161
|
+
colliders.push(colliderOf(path, new Matrix4(), new Box3().setFromObject(object))); // a solid group is one world box; its meshes still draw
|
|
162
|
+
}
|
|
163
|
+
for (const child of object.children) visit(child);
|
|
164
|
+
};
|
|
165
|
+
visit(root);
|
|
166
|
+
const materials = [...new Set([...draws.map((d) => d.material), ...sprites.map((s) => s.material)])];
|
|
167
|
+
const textures = [...new Set(materials.map((key) => tables.materials.get(key)?.map).filter((key): key is string => typeof key === 'string'))];
|
|
168
|
+
const geometries = [...new Set(draws.map((d) => d.geometry))];
|
|
169
|
+
const hash = new ContentHash().text(root.name);
|
|
170
|
+
for (const draw of draws) {
|
|
171
|
+
hash.text(draw.geometry).text(draw.material).numbers(draw.matrix).numbers([draw.castShadow ? 1 : 0, draw.receiveShadow ? 1 : 0]);
|
|
172
|
+
if (draw.instances !== null) { hash.bytes(draw.instances.matrices); if (draw.instances.colours !== null) hash.bytes(draw.instances.colours); }
|
|
173
|
+
}
|
|
174
|
+
hash.json(sprites).json(lights).json(colliders).json(water.map((w) => ({ ...w, triangles: [...w.triangles] })));
|
|
175
|
+
return { name: root.name, hash: hash.hex(), draws, sprites, lights, colliders, water, materials, textures, geometries };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function groundHash(heightAt: (x: number, z: number) => number, colourAt: SceneGround['colourAt']): string {
|
|
179
|
+
const samples: number[] = [];
|
|
180
|
+
for (let z = -250; z <= 250; z += 2) for (let x = -250; x <= 250; x += 2) { samples.push(heightAt(x, z)); if (colourAt !== null) samples.push(...colourAt(x, z)); }
|
|
181
|
+
return hashOf((h) => h.numbers(samples));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const DEFAULT_POST: ScenePost = { tone: 'aces', exposure: 1, bloom: null, vignette: 0 };
|
|
185
|
+
|
|
186
|
+
/** Run the author's build on a fresh scene and read it. Parts come in authored order; `scene` holds anything outside one. */
|
|
187
|
+
export function lowerShard(identity: ShardIdentityInput, build: (world: ShardWorld) => void): ShardScene {
|
|
188
|
+
const scene = new Scene(), parts: Group[] = [];
|
|
189
|
+
let ground: SceneGround | null = null, post: ScenePost | null = null, spawn: ShardScene['spawn'] = { position: [0, 0, 0], yaw: 0 };
|
|
190
|
+
const world: ShardWorld = {
|
|
191
|
+
scene,
|
|
192
|
+
part: (name, fill) => {
|
|
193
|
+
if (!/^[a-z][a-z0-9-]{0,63}$/u.test(name)) throw new SceneRefusalError(name, 'a part name must be kebab-case', 'Name it like `hut` or `pond-lamps`');
|
|
194
|
+
if (name === 'scene' || parts.some((p) => p.name === name)) throw new SceneRefusalError(name, 'two parts share this name', 'Give every world.part its own name');
|
|
195
|
+
const group = new Group(); group.name = name; parts.push(group); scene.add(group); fill(group); return group;
|
|
196
|
+
},
|
|
197
|
+
ground: (heightAt, options = {}) => { ground = { heightAt, colourAt: options.colourAt ?? null, hash: groundHash(heightAt, options.colourAt ?? null) }; },
|
|
198
|
+
post: (settings) => { post = { ...DEFAULT_POST, ...post, ...settings }; },
|
|
199
|
+
spawn: (x, y, z, yaw = 0) => { spawn = { position: [x, y, z], yaw }; },
|
|
200
|
+
};
|
|
201
|
+
build(world);
|
|
202
|
+
scene.updateMatrixWorld(true);
|
|
203
|
+
// anything added to the scene outside a part is the part `scene`
|
|
204
|
+
const loose = new Group(); loose.name = 'scene';
|
|
205
|
+
for (const child of scene.children.slice()) if (!parts.includes(child as Group)) loose.add(child);
|
|
206
|
+
const roots = loose.children.length > 0 ? [...parts, loose] : parts;
|
|
207
|
+
scene.add(loose); scene.updateMatrixWorld(true);
|
|
208
|
+
const tables: Tables = { materials: new Map(), textures: new Map(), geometries: new Map(), geometryKeys: new WeakMap(), materialKeys: new WeakMap(), textureKeys: new WeakMap() };
|
|
209
|
+
const lowered = roots.map((root) => lowerPart(root, tables));
|
|
210
|
+
const fog: SceneLook['fog'] = scene.fog instanceof FogExp2 ? { kind: 'exp2', colour: rgb(scene.fog.color), density: scene.fog.density }
|
|
211
|
+
: scene.fog instanceof Fog ? { kind: 'linear', colour: rgb(scene.fog.color), near: scene.fog.near, far: scene.fog.far } : null;
|
|
212
|
+
const background = scene.background !== null && typeof scene.background === 'object' && 'isColor' in scene.background ? rgb(scene.background as Color) : null;
|
|
213
|
+
return {
|
|
214
|
+
identity, parts: lowered, materials: Object.fromEntries(tables.materials), textures: Object.fromEntries(tables.textures),
|
|
215
|
+
geometries: Object.fromEntries(tables.geometries), look: { fog, background, post }, ground, spawn,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** One line per part and kind: what the walker read, for logs and tests. */
|
|
220
|
+
export function sceneSummary(shard: ShardScene): { part: string; draws: number; instances: number; triangles: number; sprites: number; lights: number; colliders: number; water: number; materials: number; textures: number }[] {
|
|
221
|
+
return shard.parts.map((part) => ({
|
|
222
|
+
part: part.name, draws: part.draws.length, instances: part.draws.reduce((n, d) => n + (d.instances?.count ?? 0), 0),
|
|
223
|
+
triangles: part.draws.reduce((n, d) => n + (shard.geometries[d.geometry]?.triangles ?? 0) * (d.instances?.count ?? 1), 0),
|
|
224
|
+
sprites: part.sprites.length, lights: part.lights.length, colliders: part.colliders.length, water: part.water.length, materials: part.materials.length, textures: part.textures.length,
|
|
225
|
+
}));
|
|
226
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AUTHORING-PARITY: `@wildshard/sdk/scene/shard`, the author's entry for a shard written as three.js source.
|
|
3
|
+
*
|
|
4
|
+
* ```ts
|
|
5
|
+
* import * as THREE from 'three';
|
|
6
|
+
* import { defineShard } from '@wildshard/sdk/scene/shard';
|
|
7
|
+
* import { paint, solid, Water } from '@wildshard/sdk/scene/author';
|
|
8
|
+
* export default defineShard({ slug: 'mossgate', name: 'Mossgate Hollow' }, (world) => {
|
|
9
|
+
* world.part('hut', (hut) => hut.add(solid(new THREE.Mesh(new THREE.BoxGeometry(6, 3, 0.3), stone))));
|
|
10
|
+
* });
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* `wildshard build` runs the default export as the shard's generator (the shardfile back end, `shardfile.ts`);
|
|
14
|
+
* `wildshard watch` calls its `describe()` and streams the parts to a running page (`../watch`).
|
|
15
|
+
*/
|
|
16
|
+
import type { ProjectGenerationContext, GeneratedProject } from '../projectGeneration';
|
|
17
|
+
import type { ShardWorld } from './author';
|
|
18
|
+
import type { ShardIdentityInput, ShardScene } from './description';
|
|
19
|
+
import { lowerShard } from './lower';
|
|
20
|
+
import { compileShardfile, type ShardfileOptions } from './shardfile';
|
|
21
|
+
import { liveShell } from '../watch/protocol';
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
/** A shard written as a scene: the generator `wildshard build` runs, plus the scene `wildshard watch` reads. */
|
|
25
|
+
export interface SceneShard {
|
|
26
|
+
(ctx: ProjectGenerationContext): Promise<GeneratedProject>;
|
|
27
|
+
/** Run the author's build once on a fresh scene and read it (compile time only). */
|
|
28
|
+
readonly describe: () => ShardScene;
|
|
29
|
+
readonly identity: ShardIdentityInput;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Declare a shard as a three.js scene. The build function runs at compile time only, never in a page or on a server. */
|
|
33
|
+
export function defineShard(identity: ShardIdentityInput, build: (world: ShardWorld) => void, options: ShardfileOptions = {}): SceneShard {
|
|
34
|
+
const describe = (): ShardScene => lowerShard(identity, build);
|
|
35
|
+
// `wildshard watch` builds the page's shell only: the dev scene host draws the parts (SHARD-SOURCE AP6)
|
|
36
|
+
const generate = (ctx: ProjectGenerationContext): Promise<GeneratedProject> => compileShardfile(process.env['WILDSHARD_SCENE_LIVE'] === '1' ? liveShell(describe()) : describe(), ctx, options);
|
|
37
|
+
return Object.assign(generate, { describe, identity });
|
|
38
|
+
}
|