@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,341 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AdditiveBlending, AmbientLight, BackSide, Box3, DataTexture, DirectionalLight, DoubleSide, Fog, FrontSide, FogExp2, Group, HemisphereLight, InstancedMesh, Line, Matrix4,
|
|
3
|
+
Mesh, MeshBasicMaterial, MeshStandardMaterial, type Object3D, PointLight, Points, PointsMaterial, Quaternion, Scene, SpotLight, Sprite, SpriteMaterial, Vector3,
|
|
4
|
+
type BufferAttribute, type BufferGeometry, Color, type InterleavedBufferAttribute, Material, ShaderMaterial, type Texture,
|
|
5
|
+
} from 'three';
|
|
6
|
+
import { vec3 } from 'three/tsl';
|
|
7
|
+
import { GraphMaterial, graph, isCatalogueMaterial, meshMap, type GraphValue } from '../materials';
|
|
8
|
+
import { LOOK_SKY_BUDGET } from '@wildshard/format/look-sky';
|
|
9
|
+
import { isSolid, motionOf, paintedPixels, Water, type ShardWorld } from './author';
|
|
10
|
+
import type {
|
|
11
|
+
Rgb, SceneCollider, SceneDraw, SceneSky, SceneGeometry, SceneGround, SceneLight, SceneLook, SceneMaterial, SceneMotion, ScenePart, ScenePoints, ScenePost, SceneSprite, SceneTexture,
|
|
12
|
+
SceneWater, ShardIdentityInput, ShardScene, Vec3,
|
|
13
|
+
} from './description';
|
|
14
|
+
import { ContentHash, hashOf } from './hash';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* AUTHORING-PARITY AP1: the walker. It runs the author's build function on a fresh `Scene`, then reads every object once
|
|
18
|
+
* into a `ShardScene`. It refuses only what has no lowering yet, naming the object's path, its type and the row that
|
|
19
|
+
* adds it, so an author is never left with a silently missing thing.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** A refusal: the object's path and the fix. */
|
|
23
|
+
/** ss4d: whether a graph material entry samples the mesh's own map (a `meshMap` node in its graph). */
|
|
24
|
+
const readsMeshMap = (entry: object): boolean =>
|
|
25
|
+
Object.values((entry as { graph?: { nodes?: Record<string, { op?: string }> } }).graph?.nodes ?? {}).some((node) => node.op === 'meshMap');
|
|
26
|
+
|
|
27
|
+
export class SceneRefusalError extends Error {
|
|
28
|
+
constructor(path: string, problem: string, fix: string) { super(`scene: ${path}: ${problem}. ${fix}`); this.name = 'SceneRefusalError'; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const rgb = (colour: Color, scale = 1): Rgb => [colour.r * scale, colour.g * scale, colour.b * scale];
|
|
32
|
+
const v3 = (v: Vector3): Vec3 => [v.x, v.y, v.z];
|
|
33
|
+
|
|
34
|
+
interface Tables {
|
|
35
|
+
materials: Map<string, SceneMaterial>; textures: Map<string, SceneTexture>; geometries: Map<string, SceneGeometry>;
|
|
36
|
+
geometryKeys: WeakMap<BufferGeometry, string>; materialKeys: WeakMap<Material, string>; textureKeys: WeakMap<Texture, string>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function floats(attribute: BufferAttribute | InterleavedBufferAttribute, width: number): Float32Array {
|
|
40
|
+
const out = new Float32Array(attribute.count * width);
|
|
41
|
+
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;
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function lowerGeometry(geometry: BufferGeometry, path: string, tables: Tables): string {
|
|
46
|
+
const known = tables.geometryKeys.get(geometry); if (known !== undefined) return known;
|
|
47
|
+
const positionAttribute = geometry.getAttribute('position');
|
|
48
|
+
if (positionAttribute === undefined) throw new SceneRefusalError(path, 'its geometry has no position', 'Give the geometry a position attribute');
|
|
49
|
+
if (!geometry.hasAttribute('normal')) geometry.computeVertexNormals();
|
|
50
|
+
const index = geometry.getIndex(), count = index?.count ?? positionAttribute.count;
|
|
51
|
+
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');
|
|
52
|
+
const position = floats(positionAttribute, 3), normal = floats(geometry.getAttribute('normal'), 3);
|
|
53
|
+
const uv = geometry.hasAttribute('uv') ? floats(geometry.getAttribute('uv'), 2) : null;
|
|
54
|
+
const colour = geometry.hasAttribute('color') ? floats(geometry.getAttribute('color'), 3) : null;
|
|
55
|
+
const indices = index === null ? null : Uint32Array.from(index.array);
|
|
56
|
+
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); })}`;
|
|
57
|
+
if (!tables.geometries.has(key)) tables.geometries.set(key, { key, position, normal, uv, colour, index: indices, triangles: count / 3 });
|
|
58
|
+
tables.geometryKeys.set(geometry, key);
|
|
59
|
+
return key;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A painted array's texture key per colour space (an array is never written after it is painted). */
|
|
63
|
+
const PIXEL_KEYS = new WeakMap<Uint8Array, Partial<Record<'srgb' | 'linear', string>>>();
|
|
64
|
+
function lowerTexture(texture: Texture, path: string, tables: Tables): string {
|
|
65
|
+
const known = tables.textureKeys.get(texture); if (known !== undefined) return known;
|
|
66
|
+
let pixels = paintedPixels(texture.source);
|
|
67
|
+
if (pixels === undefined && texture instanceof DataTexture) {
|
|
68
|
+
const { data, width, height } = texture.image as { data: unknown; width: number; height: number };
|
|
69
|
+
if ((data instanceof Uint8Array || data instanceof Uint8ClampedArray) && data.length === width * height * 4) pixels = { width, height, rgba: new Uint8Array(data.buffer, data.byteOffset, data.byteLength) };
|
|
70
|
+
}
|
|
71
|
+
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');
|
|
72
|
+
const colourSpace = texture.colorSpace === 'srgb' ? 'srgb' : 'linear';
|
|
73
|
+
// AP17: a watched revision's memoised paint hands back the same pixel array, so its hash is kept by that array
|
|
74
|
+
const cached = PIXEL_KEYS.get(pixels.rgba)?.[colourSpace], { rgba, width, height } = pixels;
|
|
75
|
+
const key = cached ?? `t${hashOf((h) => { h.numbers([width, height]).text(colourSpace).bytes(rgba); })}`;
|
|
76
|
+
if (cached === undefined) PIXEL_KEYS.set(rgba, { ...PIXEL_KEYS.get(rgba), [colourSpace]: key });
|
|
77
|
+
if (!tables.textures.has(key)) tables.textures.set(key, { key, width: pixels.width, height: pixels.height, rgba: pixels.rgba, colourSpace });
|
|
78
|
+
tables.textureKeys.set(texture, key);
|
|
79
|
+
return key;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
interface NodeSlots { readonly isNodeMaterial?: boolean; readonly isMeshBasicNodeMaterial?: boolean; readonly map?: Texture | null; readonly [slot: string]: unknown }
|
|
83
|
+
const isNodeMaterial = (material: Material): boolean => Reflect.get(material, 'isNodeMaterial') === true;
|
|
84
|
+
/** AP13: a three.js node material (`MeshStandardNodeMaterial`, `MeshBasicNodeMaterial`) as one material graph: its TSL slots
|
|
85
|
+
* go through `graph()`, its plain numbers stand where a slot is empty. A slot the graph has no stage for is refused. */
|
|
86
|
+
function nodeMaterialGraph(material: Material, path: string): GraphMaterial {
|
|
87
|
+
const m = material as Material & NodeSlots & { color?: Color; emissive?: Color; roughness?: number; metalness?: number };
|
|
88
|
+
for (const slot of ['positionNode', 'normalNode', 'outputNode', 'fragmentNode', 'vertexNode', 'castShadowNode', 'receivedShadowNode', 'aoNode', 'lightsNode', 'envNode']) {
|
|
89
|
+
if (m[slot] !== null && m[slot] !== undefined) throw new SceneRefusalError(path, `its ${slot} has no graph stage`, 'Use colorNode, emissiveNode, roughnessNode, metalnessNode and opacityNode, or write the whole surface with graph() in a GraphMaterial');
|
|
90
|
+
}
|
|
91
|
+
const value = (node: unknown, fallback: GraphValue): GraphValue => (node === null || node === undefined ? fallback : node as GraphValue);
|
|
92
|
+
const c = m.color ?? new Color(1, 1, 1), e = m.emissive ?? new Color(0, 0, 0);
|
|
93
|
+
const unlit = m.isMeshBasicNodeMaterial === true;
|
|
94
|
+
// ss4d: a node material's own `map` (three draws map x color when colorNode is empty) is the mesh's colour map: the
|
|
95
|
+
// graph reads it as `meshMap`, the shard binds the lowered texture to it (props.materials `colour`)
|
|
96
|
+
const mapped = m.map !== null && m.map !== undefined, empty = (slot: string): boolean => m[slot] === null || m[slot] === undefined;
|
|
97
|
+
const cutsOrBlends = material.transparent || material.alphaTest > 0;
|
|
98
|
+
const surface = {
|
|
99
|
+
colour: value(m['colorNode'], mapped ? meshMap.rgb.mul(vec3(c.r, c.g, c.b)) : [c.r, c.g, c.b]),
|
|
100
|
+
...(unlit ? {} : { emissive: value(m['emissiveNode'], [e.r, e.g, e.b]), roughness: value(m['roughnessNode'], m.roughness ?? 1), metalness: value(m['metalnessNode'], m.metalness ?? 0) }),
|
|
101
|
+
...(!empty('opacityNode') ? { alpha: value(m['opacityNode'], 1) } : mapped && empty('colorNode') && cutsOrBlends ? { alpha: meshMap.a.mul(material.opacity) } : {}),
|
|
102
|
+
...(material.alphaTest > 0 ? { alphaCutoff: material.alphaTest } : {}),
|
|
103
|
+
};
|
|
104
|
+
return new GraphMaterial(graph({ model: unlit ? 'unlit' : 'standard', doubleSided: material.side === DoubleSide, surface }));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function lowerMaterial(material: Material, path: string, tables: Tables): string {
|
|
108
|
+
const known = tables.materialKeys.get(material); if (known !== undefined) return known;
|
|
109
|
+
// AP13: shaders are TSL; raw GLSL never reaches a shard file
|
|
110
|
+
if (material instanceof ShaderMaterial) throw new SceneRefusalError(path, `a ${material.type} is raw GLSL`, 'Write the shader in TSL and draw it with new GraphMaterial(graph({ surface: { colour } })) from @wildshard/sdk/materials');
|
|
111
|
+
const catalogue = isCatalogueMaterial(material) ? material.toMaterialEntry() : isNodeMaterial(material) ? nodeMaterialGraph(material, path).toMaterialEntry() : null;
|
|
112
|
+
if (catalogue === null && material.onBeforeCompile !== Material.prototype.onBeforeCompile) throw new SceneRefusalError(path, 'its onBeforeCompile patches GLSL', 'Write the change in TSL as a GraphMaterial (graph() from @wildshard/sdk/materials), or declare it with animate() if it is motion');
|
|
113
|
+
let kind: SceneMaterial['kind'];
|
|
114
|
+
if (material instanceof MeshStandardMaterial) kind = 'standard';
|
|
115
|
+
else if (material instanceof MeshBasicMaterial) kind = 'basic';
|
|
116
|
+
else if (material instanceof SpriteMaterial) kind = 'sprite';
|
|
117
|
+
else if (material instanceof PointsMaterial) kind = 'points';
|
|
118
|
+
else if (catalogue !== null) kind = 'standard';
|
|
119
|
+
else throw new SceneRefusalError(path, `${material.type} has no lowering yet`, 'Use MeshStandardMaterial, MeshBasicMaterial, a node material or a GraphMaterial (TSL through graph())');
|
|
120
|
+
if (material instanceof PointsMaterial && !material.sizeAttenuation) throw new SceneRefusalError(path, 'a Points cloud sized in pixels has no lowering', 'Leave sizeAttenuation on: a point is a card `size` metres across');
|
|
121
|
+
const m = material as MeshStandardMaterial & MeshBasicMaterial & SpriteMaterial & PointsMaterial;
|
|
122
|
+
// ss4d: a graph draws only what it samples: a map reaches the shard (its props.materials `colour`) only when the graph
|
|
123
|
+
// reads the mesh map (a node material's colorNode replaces its map, as in three)
|
|
124
|
+
const sampled = catalogue === null || (catalogue as { family?: string }).family !== 'graph' || readsMeshMap(catalogue);
|
|
125
|
+
const map = m.map === null || m.map === undefined || !sampled ? null : lowerTexture(m.map, path, tables);
|
|
126
|
+
const standard = material instanceof MeshStandardMaterial;
|
|
127
|
+
const fields: Omit<SceneMaterial, 'key' | 'name'> = {
|
|
128
|
+
kind, colour: rgb(m.color), roughness: standard ? m.roughness : 1, metalness: standard ? m.metalness : 0,
|
|
129
|
+
emissive: standard ? rgb(m.emissive) : [0, 0, 0], emissiveIntensity: standard ? m.emissiveIntensity : 0, map,
|
|
130
|
+
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],
|
|
131
|
+
alphaTest: material.alphaTest, side: material.side === DoubleSide ? 'double' : material.side === BackSide ? 'back' : 'front',
|
|
132
|
+
vertexColours: material.vertexColors, transparent: material.transparent, opacity: material.opacity,
|
|
133
|
+
blending: material.blending === AdditiveBlending ? 'additive' : 'normal', depthWrite: material.depthWrite, fog: m.fog !== false,
|
|
134
|
+
polygonOffset: material.polygonOffset ? material.polygonOffsetFactor : 0,
|
|
135
|
+
pointSize: material instanceof PointsMaterial ? material.size : 0,
|
|
136
|
+
entry: catalogue,
|
|
137
|
+
};
|
|
138
|
+
const key = `m${hashOf((h) => h.json(fields))}`;
|
|
139
|
+
if (!tables.materials.has(key)) tables.materials.set(key, { key, name: material.name === '' ? key : material.name, ...fields });
|
|
140
|
+
tables.materialKeys.set(material, key);
|
|
141
|
+
return key;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The object's path under its part: names where given, else `Type index`. */
|
|
145
|
+
function pathOf(object: Object3D, root: Object3D): string {
|
|
146
|
+
const parts: string[] = [];
|
|
147
|
+
for (let node: Object3D | null = object; node !== null && node !== root; node = node.parent) {
|
|
148
|
+
const index = node.parent === null ? 0 : node.parent.children.indexOf(node);
|
|
149
|
+
parts.unshift(node.name === '' ? `${node.type} ${index}` : node.name);
|
|
150
|
+
}
|
|
151
|
+
return [root.name, ...parts].join('/');
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function colliderOf(path: string, matrix: Matrix4, box: Box3): SceneCollider {
|
|
155
|
+
const centre = box.getCenter(new Vector3()), size = box.getSize(new Vector3());
|
|
156
|
+
const position = new Vector3(), rotation = new Quaternion(), scale = new Vector3();
|
|
157
|
+
matrix.decompose(position, rotation, scale);
|
|
158
|
+
const world = centre.clone().applyMatrix4(matrix);
|
|
159
|
+
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] };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const CARD_MOTIONS: ReadonlySet<string> = new Set(['pulse', 'drift', 'rise']), MESH_MOTIONS: ReadonlySet<string> = new Set(['sway', 'uvScroll']), LIGHT_MOTIONS: ReadonlySet<string> = new Set(['flicker']);
|
|
163
|
+
/** The motion `object` takes (AP12): one declared on it must fit what it is (else a refusal by path); one declared on a
|
|
164
|
+
* group reaches only the objects it fits (a fire's group pulses its cards and flickers its light). */
|
|
165
|
+
function fitMotion(object: Object3D, root: Object3D, path: string, kinds: ReadonlySet<string>, what: string): SceneMotion | null {
|
|
166
|
+
const own = motionOf(object, object);
|
|
167
|
+
if (own !== null && !kinds.has(own.kind)) throw new SceneRefusalError(path, `${own.kind} does not move a ${what}`, 'flicker moves a PointLight; pulse, drift and rise move a Sprite or Points; sway and uvScroll move a mesh. spin and bob need moving parts: an engine row after M2');
|
|
168
|
+
if (own !== null) return own;
|
|
169
|
+
const inherited = object.parent === null || object === root ? null : motionOf(object.parent, root);
|
|
170
|
+
return inherited !== null && kinds.has(inherited.kind) ? inherited : null;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* ss4d: a graph material (TSL, a node material, a catalogue entry) is its own whole surface: the engine draws its graph
|
|
175
|
+
* and nothing of the scene's card or motion rows, so a card or a declared motion on one would be dropped. Refused by
|
|
176
|
+
* path, never dropped: a card is a SpriteMaterial or a PointsMaterial; a graph moves in its own `vertex.offset` stage.
|
|
177
|
+
*/
|
|
178
|
+
function refuseGraphMotion(path: string, key: string, tables: Tables, what: string): void {
|
|
179
|
+
if (tables.materials.get(key)?.entry === null) return;
|
|
180
|
+
throw new SceneRefusalError(path, what === 'card' ? 'a graph material has no card (a camera-facing quad)' : `a graph material does not take a declared ${what}`,
|
|
181
|
+
what === 'card' ? 'Draw a Sprite or Points with a SpriteMaterial or PointsMaterial (its map, colour and blending), or a plain Mesh with the graph'
|
|
182
|
+
: 'Move it in the graph: vertex: { offset } over graphInputs.windTime (sway) or a uv over time (uvScroll), or draw it with a MeshStandardMaterial');
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function lowerPart(root: Object3D, tables: Tables, panel?: string): ScenePart {
|
|
186
|
+
const draws: SceneDraw[] = [], sprites: SceneSprite[] = [], lights: SceneLight[] = [], colliders: SceneCollider[] = [], water: SceneWater[] = [], points: ScenePoints[] = [];
|
|
187
|
+
const visit = (object: Object3D): void => {
|
|
188
|
+
const path = pathOf(object, root);
|
|
189
|
+
if (!object.visible) {
|
|
190
|
+
// an invisible solid is a collider only: said once, drawn never
|
|
191
|
+
if (object instanceof Mesh && isSolid(object)) { object.geometry.computeBoundingBox(); colliders.push(colliderOf(path, object.matrixWorld, object.geometry.boundingBox ?? new Box3())); }
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (object instanceof Water) {
|
|
195
|
+
// the format holds at most 64 outline points: 48 evenly spaced along the shape
|
|
196
|
+
const outline = object.shape.getSpacedPoints(48).slice(0, 48).map((p) => new Vector3(p.x, p.y, 0).applyMatrix4(object.matrixWorld));
|
|
197
|
+
const geometry = object.geometry, position = geometry.getAttribute('position'), index = geometry.getIndex(), n = index?.count ?? position.count;
|
|
198
|
+
const triangles = new Float32Array(n * 3);
|
|
199
|
+
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); }
|
|
200
|
+
const level = new Vector3().setFromMatrixPosition(object.matrixWorld).y;
|
|
201
|
+
water.push({ path, outline: outline.map((p) => [p.x, p.z] as const), level, tint: rgb(object.material.color), reflect: object.reflect, triangles });
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (object instanceof Mesh) {
|
|
205
|
+
if (Array.isArray(object.material)) throw new SceneRefusalError(path, 'it has several materials', 'Split it into one mesh per material');
|
|
206
|
+
const geometry = lowerGeometry(object.geometry, path, tables), material = lowerMaterial(object.material, path, tables);
|
|
207
|
+
let instances: SceneDraw['instances'] = null;
|
|
208
|
+
if (object instanceof InstancedMesh) {
|
|
209
|
+
const count = object.count, matrices = new Float32Array(object.instanceMatrix.array.buffer, object.instanceMatrix.array.byteOffset, count * 16).slice();
|
|
210
|
+
const colours = object.instanceColor === null ? null : new Float32Array(object.instanceColor.array.buffer, object.instanceColor.array.byteOffset, count * 3).slice();
|
|
211
|
+
instances = { count, matrices, colours };
|
|
212
|
+
if (isSolid(object)) {
|
|
213
|
+
object.geometry.computeBoundingBox(); const box = object.geometry.boundingBox ?? new Box3();
|
|
214
|
+
for (let i = 0; i < count; i++) colliders.push(colliderOf(`${path}#${i}`, object.matrixWorld.clone().multiply(new Matrix4().fromArray(matrices, i * 16)), box));
|
|
215
|
+
}
|
|
216
|
+
} else if (isSolid(object)) {
|
|
217
|
+
object.geometry.computeBoundingBox(); colliders.push(colliderOf(path, object.matrixWorld, object.geometry.boundingBox ?? new Box3()));
|
|
218
|
+
}
|
|
219
|
+
const motion = fitMotion(object, root, path, MESH_MOTIONS, 'mesh');
|
|
220
|
+
if (motion !== null) refuseGraphMotion(path, material, tables, motion.kind);
|
|
221
|
+
draws.push({ path, geometry, material, matrix: [...object.matrixWorld.elements], instances, castShadow: object.castShadow, receiveShadow: object.receiveShadow, motion });
|
|
222
|
+
} else if (object instanceof Sprite) {
|
|
223
|
+
const material = lowerMaterial(object.material, path, tables), scale = new Vector3().setFromMatrixScale(object.matrixWorld);
|
|
224
|
+
refuseGraphMotion(path, material, tables, 'card');
|
|
225
|
+
sprites.push({ path, material, position: v3(new Vector3().setFromMatrixPosition(object.matrixWorld)), scale: [scale.x, scale.y], center: [object.center.x, object.center.y], motion: fitMotion(object, root, path, CARD_MOTIONS, 'Sprite') });
|
|
226
|
+
} else if (object instanceof PointLight || object instanceof DirectionalLight || object instanceof HemisphereLight || object instanceof AmbientLight) {
|
|
227
|
+
const position = v3(new Vector3().setFromMatrixPosition(object.matrixWorld));
|
|
228
|
+
const kind: SceneLight['kind'] = object instanceof PointLight ? 'point' : object instanceof DirectionalLight ? 'directional' : object instanceof HemisphereLight ? 'hemisphere' : 'ambient';
|
|
229
|
+
lights.push({ path, kind, colour: rgb(object.color), groundColour: object instanceof HemisphereLight ? rgb(object.groundColor) : null, intensity: object.intensity,
|
|
230
|
+
distance: object instanceof PointLight ? object.distance : 0, decay: object instanceof PointLight ? object.decay : 0, position,
|
|
231
|
+
target: object instanceof DirectionalLight ? v3(object.target.getWorldPosition(new Vector3())) : null, castShadow: object.castShadow,
|
|
232
|
+
motion: object instanceof PointLight ? fitMotion(object, root, path, LIGHT_MOTIONS, 'light') : null });
|
|
233
|
+
} else if (object instanceof SpotLight) {
|
|
234
|
+
throw new SceneRefusalError(path, 'SpotLight has no lowering yet', 'Use a PointLight; spot lamps are an engine row after M1');
|
|
235
|
+
} else if (object instanceof Points) {
|
|
236
|
+
// AP11: each point a camera-facing card; the cloud keeps its own motion (drift, rise)
|
|
237
|
+
if (Array.isArray(object.material)) throw new SceneRefusalError(path, 'it has several materials', 'Give a Points cloud one PointsMaterial');
|
|
238
|
+
const material = lowerMaterial(object.material, path, tables), position = object.geometry.getAttribute('position');
|
|
239
|
+
refuseGraphMotion(path, material, tables, 'card');
|
|
240
|
+
if (position === undefined) throw new SceneRefusalError(path, 'its geometry has no position', 'Give the cloud a position attribute');
|
|
241
|
+
const seats = new Float32Array(position.count * 3), p = new Vector3();
|
|
242
|
+
for (let i = 0; i < position.count; i++) { p.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld); seats.set([p.x, p.y, p.z], i * 3); }
|
|
243
|
+
points.push({ path, material, positions: seats, motion: fitMotion(object, root, path, CARD_MOTIONS, 'Points cloud') });
|
|
244
|
+
} else if (object instanceof Line) {
|
|
245
|
+
throw new SceneRefusalError(path, `${object.type} has no lowering yet`, 'Draw a line as a thin mesh (a TubeGeometry)');
|
|
246
|
+
} else if (isSolid(object)) {
|
|
247
|
+
colliders.push(colliderOf(path, new Matrix4(), new Box3().setFromObject(object))); // a solid group is one world box; its meshes still draw
|
|
248
|
+
}
|
|
249
|
+
for (const child of object.children) visit(child);
|
|
250
|
+
};
|
|
251
|
+
visit(root);
|
|
252
|
+
const materials = [...new Set([...draws.map((d) => d.material), ...sprites.map((s) => s.material), ...points.map((c) => c.material)])];
|
|
253
|
+
const textures = [...new Set(materials.map((key) => tables.materials.get(key)?.map).filter((key): key is string => typeof key === 'string'))];
|
|
254
|
+
const geometries = [...new Set(draws.map((d) => d.geometry))];
|
|
255
|
+
const hash = new ContentHash().text(root.name).text(panel ?? '');
|
|
256
|
+
// AP16: a panel is meshes and solids, the things a state row can hide; anything else would stay when it hides
|
|
257
|
+
if (panel !== undefined && sprites.length + points.length + lights.length + water.length > 0) throw new SceneRefusalError(root.name, 'a panel part holds meshes and solids only (its sprites, points, lights and water would not hide with it)', 'Put them in a part of their own');
|
|
258
|
+
// a panel is a library model, which carries no tile motion: a moving mesh would stand still
|
|
259
|
+
if (panel !== undefined && draws.some((d) => d.motion !== null)) throw new SceneRefusalError(root.name, 'a panel part cannot move (sway, flicker, pulse or uvScroll)', 'Put the moving meshes in a part of their own');
|
|
260
|
+
for (const draw of draws) {
|
|
261
|
+
hash.text(draw.geometry).text(draw.material).numbers(draw.matrix).numbers([draw.castShadow ? 1 : 0, draw.receiveShadow ? 1 : 0]).json(draw.motion);
|
|
262
|
+
if (draw.instances !== null) { hash.bytes(draw.instances.matrices); if (draw.instances.colours !== null) hash.bytes(draw.instances.colours); }
|
|
263
|
+
}
|
|
264
|
+
hash.json(sprites).json(lights).json(colliders).json(water.map((w) => ({ ...w, triangles: [...w.triangles] })));
|
|
265
|
+
for (const cloud of points) hash.text(cloud.material).bytes(cloud.positions).json(cloud.motion);
|
|
266
|
+
return { name: root.name, hash: hash.hex(), ...(panel === undefined ? {} : { panel }), draws, sprites, points, lights, colliders, water, materials, textures, geometries };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function groundHash(heightAt: (x: number, z: number) => number, colourAt: SceneGround['colourAt']): string {
|
|
270
|
+
const samples: number[] = [];
|
|
271
|
+
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)); }
|
|
272
|
+
return hashOf((h) => h.numbers(samples));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const DEFAULT_POST: ScenePost = { tone: 'aces', exposure: 1, bloom: null, vignette: 0 };
|
|
276
|
+
|
|
277
|
+
/** Run the author's build on a fresh scene and read it. Parts come in authored order; `scene` holds anything outside one. */
|
|
278
|
+
export function lowerShard(identity: ShardIdentityInput, build: (world: ShardWorld) => void): ShardScene {
|
|
279
|
+
const scene = new Scene(), parts: Group[] = [], panels = new Map<Object3D, string>();
|
|
280
|
+
let sky: SceneSky | null = null;
|
|
281
|
+
let ground: SceneGround | null = null, post: ScenePost | null = null, spawn: ShardScene['spawn'] = { position: [0, 0, 0], yaw: 0 };
|
|
282
|
+
const world: ShardWorld = {
|
|
283
|
+
scene,
|
|
284
|
+
part: (name, fill, options = {}) => {
|
|
285
|
+
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`');
|
|
286
|
+
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');
|
|
287
|
+
const { panel } = options;
|
|
288
|
+
// AP16: the format's panel id (props `id`), one part each, at most 64 (props.panels)
|
|
289
|
+
// a panel's collider takes its id, so it may not look like a part's collider (`scene.<part>`)
|
|
290
|
+
if (panel !== undefined && (!/^[a-z][a-z0-9.-]{0,127}$/u.test(panel) || panel.startsWith('scene.'))) throw new SceneRefusalError(name, `panel id ${panel} is not a shardfile id`, 'Name it like `brasscap.gate`: lower case, digits, dots and dashes');
|
|
291
|
+
if (panel !== undefined && [...panels.values()].includes(panel)) throw new SceneRefusalError(name, `two parts are panel ${panel}`, 'Give every panel part its own id');
|
|
292
|
+
if (panel !== undefined && panels.size >= 64) throw new SceneRefusalError(name, 'a shard has at most 64 panels', 'Merge panels that hide together');
|
|
293
|
+
const group = new Group(); group.name = name; parts.push(group); scene.add(group);
|
|
294
|
+
if (panel !== undefined) panels.set(group, panel);
|
|
295
|
+
fill(group); return group;
|
|
296
|
+
},
|
|
297
|
+
ground: (heightAt, options = {}) => {
|
|
298
|
+
// ss4d: the ground is a lit PBR surface (the cleanroom's ground mesh material), never the format's default toon
|
|
299
|
+
const m = options.material;
|
|
300
|
+
if (m !== undefined && !(m instanceof MeshStandardMaterial)) throw new SceneRefusalError('ground', `a ${(m as { type?: string }).type ?? 'material'} ground has no lowering`, 'Give world.ground a MeshStandardMaterial');
|
|
301
|
+
// the shard's ground takes colour, roughness, metalness and detail only: anything else is refused, never dropped
|
|
302
|
+
if (m?.map !== null && m?.map !== undefined) throw new SceneRefusalError('ground', 'a ground map has no lowering (the terrain has no uvs)', 'Say its grain with world.ground(h, { detail }), the PBR detail layer');
|
|
303
|
+
if (m !== undefined && (m.emissive.getHex() !== 0 || m.transparent || m.side !== FrontSide)) throw new SceneRefusalError('ground', 'a ground material is opaque, one-sided and unlit by itself', 'Leave emissive black, transparent off and side FrontSide on the ground material');
|
|
304
|
+
const surface = { colour: m === undefined ? [1, 1, 1] as Rgb : rgb(m.color), roughness: m?.roughness ?? 1, metalness: m?.metalness ?? 0, detail: options.detail ?? null };
|
|
305
|
+
ground = { heightAt, colourAt: options.colourAt ?? null, surface, hash: groundHash(heightAt, options.colourAt ?? null) };
|
|
306
|
+
},
|
|
307
|
+
post: (settings) => { post = { ...DEFAULT_POST, ...post, ...settings }; },
|
|
308
|
+
// AP14: the sky compiles at once, so a graph outside the vocabulary or the sky's budget is refused at its line
|
|
309
|
+
sky: (colour, options = {}) => {
|
|
310
|
+
const env = options.environment;
|
|
311
|
+
sky = { graph: graph({ kind: 'material', model: 'unlit', surface: { colour } }, { budget: LOOK_SKY_BUDGET }),
|
|
312
|
+
environment: env === undefined ? null : { intensity: env.intensity, ground: [env.ground[0], env.ground[1], env.ground[2]] } };
|
|
313
|
+
},
|
|
314
|
+
spawn: (x, y, z, yaw = 0) => { spawn = { position: [x, y, z], yaw }; },
|
|
315
|
+
};
|
|
316
|
+
build(world);
|
|
317
|
+
scene.updateMatrixWorld(true);
|
|
318
|
+
// anything added to the scene outside a part is the part `scene`
|
|
319
|
+
const loose = new Group(); loose.name = 'scene';
|
|
320
|
+
for (const child of scene.children.slice()) if (!parts.includes(child as Group)) loose.add(child);
|
|
321
|
+
const roots = loose.children.length > 0 ? [...parts, loose] : parts;
|
|
322
|
+
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() };
|
|
324
|
+
const lowered = roots.map((root) => lowerPart(root, tables, panels.get(root)));
|
|
325
|
+
const fog: SceneLook['fog'] = scene.fog instanceof FogExp2 ? { kind: 'exp2', colour: rgb(scene.fog.color), density: scene.fog.density }
|
|
326
|
+
: scene.fog instanceof Fog ? { kind: 'linear', colour: rgb(scene.fog.color), near: scene.fog.near, far: scene.fog.far } : null;
|
|
327
|
+
const background = scene.background !== null && typeof scene.background === 'object' && 'isColor' in scene.background ? rgb(scene.background as Color) : null;
|
|
328
|
+
return {
|
|
329
|
+
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,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** One line per part and kind: what the walker read, for logs and tests. */
|
|
335
|
+
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 }[] {
|
|
336
|
+
return shard.parts.map((part) => ({
|
|
337
|
+
part: part.name, draws: part.draws.length, instances: part.draws.reduce((n, d) => n + (d.instances?.count ?? 0), 0),
|
|
338
|
+
triangles: part.draws.reduce((n, d) => n + (shard.geometries[d.geometry]?.triangles ?? 0) * (d.instances?.count ?? 1), 0),
|
|
339
|
+
sprites: part.sprites.length + part.points.reduce((n, c) => n + c.positions.length / 3, 0), lights: part.lights.length, colliders: part.colliders.length, water: part.water.length, materials: part.materials.length, textures: part.textures.length,
|
|
340
|
+
}));
|
|
341
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
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, sceneGameplay, 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
|
+
/** AP19: the gameplay sections `options.extend` declares (`wildshard watch` restarts the page's simulation on a change) and
|
|
31
|
+
* the rest of what it adds (a change there is a new shell) */
|
|
32
|
+
readonly gameplay: () => ReturnType<typeof sceneGameplay>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Declare a shard as a three.js scene. The build function runs at compile time only, never in a page or on a server. */
|
|
36
|
+
export function defineShard(identity: ShardIdentityInput, build: (world: ShardWorld) => void, options: ShardfileOptions = {}): SceneShard {
|
|
37
|
+
const describe = (): ShardScene => lowerShard(identity, build);
|
|
38
|
+
// `wildshard watch` builds the page's shell only: the dev scene host draws the parts (SHARD-SOURCE AP6)
|
|
39
|
+
const generate = (ctx: ProjectGenerationContext): Promise<GeneratedProject> => compileShardfile(process.env['WILDSHARD_SCENE_LIVE'] === '1' ? liveShell(describe()) : describe(), ctx, options);
|
|
40
|
+
return Object.assign(generate, { describe, identity, gameplay: () => sceneGameplay(identity, options) });
|
|
41
|
+
}
|