@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.
Files changed (88) hide show
  1. package/GUIDE.md +26 -13
  2. package/bin/wildshard.mjs +2 -1
  3. package/docs/api/EXPORT-TIERS.md +16 -4
  4. package/lint/export-tiers.json +12 -0
  5. package/lint/host-callbacks.mjs +1 -1
  6. package/package.json +22 -6
  7. package/scripts/bake/template-skins.mjs +6 -3
  8. package/scripts/bake/template-warden.mjs +25 -0
  9. package/scripts/build-shardfiles.mjs +7 -2
  10. package/scripts/export-ci21-guests.mjs +89 -0
  11. package/scripts/prepare-product.mjs +2 -2
  12. package/scripts/scratch-sweep.mjs +182 -0
  13. package/scripts/wildshard.mjs +1 -1
  14. package/skills/wildshard-mockup-to-model/SKILL.md +5 -3
  15. package/skills/wildshard-upgrade/SKILL.md +4 -4
  16. package/src/cli/help.ts +9 -5
  17. package/src/cli/upload/validate.ts +7 -5
  18. package/src/sharddev/as/prelude.ts +67 -0
  19. package/src/sharddev/assets.ts +1 -1
  20. package/src/sharddev/authorLint.ts +45 -0
  21. package/src/sharddev/bake/compactGlb.ts +1 -1
  22. package/src/sharddev/bake/compileScript.ts +6 -0
  23. package/src/sharddev/bake/glbCompression.ts +1 -1
  24. package/src/sharddev/bake/gltfSource.ts +1 -1
  25. package/src/sharddev/bake/placeholders.ts +1 -1
  26. package/src/sharddev/bake/terrain.ts +12 -3
  27. package/src/sharddev/blobBytes.ts +1 -1
  28. package/src/sharddev/blobs.ts +2 -2
  29. package/src/sharddev/checkProject.ts +7 -18
  30. package/src/sharddev/cli.ts +17 -4
  31. package/src/sharddev/engineMusic.ts +23 -0
  32. package/src/sharddev/formatJsonSchema.ts +1 -1
  33. package/src/sharddev/materialGraphFiles.ts +1 -1
  34. package/src/sharddev/materials.ts +7 -3
  35. package/src/sharddev/newProject.ts +18 -10
  36. package/src/sharddev/outputProduct.ts +2 -2
  37. package/src/sharddev/productOutput.ts +2 -2
  38. package/src/sharddev/project.ts +6 -1
  39. package/src/sharddev/projectMap.ts +1 -1
  40. package/src/sharddev/refusals.ts +5 -3
  41. package/src/sharddev/reportCard.ts +1 -1
  42. package/src/sharddev/scene/author.ts +184 -0
  43. package/src/sharddev/scene/canvas.ts +212 -0
  44. package/src/sharddev/scene/description.ts +223 -0
  45. package/src/sharddev/scene/hash.ts +23 -0
  46. package/src/sharddev/scene/lower.ts +341 -0
  47. package/src/sharddev/scene/shard.ts +41 -0
  48. package/src/sharddev/scene/shardfile.ts +621 -0
  49. package/src/sharddev/threeGate.mjs +14 -0
  50. package/src/sharddev/threePin.mjs +40 -0
  51. package/src/sharddev/watch/page.ts +284 -0
  52. package/src/sharddev/watch/pageEntry.ts +59 -0
  53. package/src/sharddev/watch/parity-baseline.json +22 -0
  54. package/src/sharddev/watch/parity.mjs +168 -0
  55. package/src/sharddev/watch/proof.mjs +199 -0
  56. package/src/sharddev/watch/protocol.ts +166 -0
  57. package/src/sharddev/watch/socket.ts +57 -0
  58. package/src/sharddev/watch/watch.ts +373 -0
  59. package/src/shards/_template/assets/3058c100bc477fd6fe8268f33b53756b8a2556e7e41c58b2216c703ca7b042c6 +1 -0
  60. package/src/shards/_template/assets/8a0440f392737a31cf0926a3c7dc011c320144972882945a5462c893e817d94a +0 -0
  61. package/src/shards/_template/behaviour/door.as +16 -26
  62. package/src/shards/_template/card/landscape.jpg +0 -0
  63. package/src/shards/_template/card/portrait.jpg +0 -0
  64. package/src/shards/_template/card/thumb.jpg +0 -0
  65. package/src/shards/_template/data/clientScripts.json +43 -43
  66. package/src/shards/_template/data/creatures.json +2 -2
  67. package/src/shards/_template/data/look.json +141 -13
  68. package/src/shards/_template/data/rows.json +20 -2
  69. package/src/shards/_template/data/skins.json +32 -0
  70. package/src/shards/_template/data/water.json +18 -0
  71. package/src/shards/_template/generators/product.ts +5 -1
  72. package/src/shards/_template/generators/warden.ts +273 -0
  73. package/src/shards/_template/generators/world.ts +52 -21
  74. package/src/shards/_template/hero.json +6 -6
  75. package/src/shards/authoring-slice/generators/shard.ts +14 -0
  76. package/src/shards/authoring-slice/generators/sky.ts +64 -0
  77. package/src/shards/authoring-slice/generators/template-sky.ts +27 -0
  78. package/src/shards/authoring-slice/generators/textures.ts +232 -0
  79. package/src/shards/authoring-slice/generators/world.ts +518 -0
  80. package/src/shards/authoring-slice/shard.config.ts +7 -0
  81. package/src/shards/mossgate/generators/shard.ts +6 -0
  82. package/src/shards/mossgate/generators/sky.ts +64 -0
  83. package/src/shards/mossgate/generators/textures.ts +249 -0
  84. package/src/shards/mossgate/generators/world.ts +998 -0
  85. package/src/shards/mossgate/shard.config.ts +7 -0
  86. package/scripts/shard-output-report.d.mts +0 -9
  87. package/scripts/shard-output-report.mjs +0 -85
  88. package/scripts/shard-platform-cli.mjs +0 -93
@@ -5,6 +5,7 @@ import { existsSync } from 'node:fs';
5
5
  import { buildProject, readProjectAssets, validateProject } from './project';
6
6
  import { ShardfileSchema, type Shardfile } from '@wildshard/format/shardSchema';
7
7
  import { devProject } from './dev';
8
+ import { watchProject } from './watch/watch';
8
9
  import { devClient } from './devClient';
9
10
  import { proveAuthorSimulation, measureSimulation, validateSimulation } from '@wildshard/engine/host/headless';
10
11
  import { performanceReport, performanceReportLines, type PerformanceObservations } from './reportCard';
@@ -51,7 +52,7 @@ async function writeShardfileOf(options: CliOptions, folder: string, source: str
51
52
  catch (error) { throw new ShardfileRefusalError(error instanceof Error ? error.message : String(error), { cause: error }); }
52
53
  }
53
54
  /** The verbs whose first operand is a shard source (or, for validate and prove, a built folder). */
54
- const SOURCE_VERBS: ReadonlySet<string> = new Set(['check', 'synth', 'build', 'dev', 'validate', 'prove']);
55
+ const SOURCE_VERBS: ReadonlySet<string> = new Set(['check', 'synth', 'build', 'dev', 'watch', 'validate', 'prove']);
55
56
  interface CliOptions { readonly decisionLegacyLines?: number; readonly manifest?: ProjectManifestSource; readonly writeShardfile?: ShardfileWriter }
56
57
  async function runCommand(given: readonly string[], options: CliOptions): Promise<void> {
57
58
  // SA16 (J317): a verb given a repo finds its shard source at `src/` or its one `src/shards/<slug>/`.
@@ -97,9 +98,9 @@ async function runCommand(given: readonly string[], options: CliOptions): Promis
97
98
  for (const line of updateShardRepo(resolve(positional[0] ?? '.'))) console.info(line);
98
99
  return;
99
100
  }
100
- if (input === undefined) throw new Error('usage: wildshard new <dir> | check <source> [folder] [--json] | synth <source> | build <source> [folder] [--shardfile-only|--folder-only] [--no-placeholders] [--output=<slug>] | build <source> --behaviour-only | validate <source|shard.json> | dev <source> [port] (wildshard --help lists them all)');
101
+ if (input === undefined) throw new Error('usage: wildshard new <dir> | check <source> [folder] [--json] | synth <source> | build <source> [folder] [--shardfile-only|--folder-only] [--no-placeholders] [--output=<slug>] | build <source> --behaviour-only | validate <source|shard.json> | dev <source> [port] | watch <source> [port] (wildshard --help lists them all)');
101
102
  // SA16 (J314): a hand-written src/ (--template blender) has no shard.config.ts to build, synth or serve; check settles it.
102
- if ((command === 'build' || command === 'synth' || command === 'dev') && isRepoSource(resolve(input)) && isHandwrittenSource(resolve(input))) throw new Error(`${command}: ${input} is a hand-written shard file (--template blender): run wildshard check on the repo, which settles and builds it`);
103
+ if ((command === 'build' || command === 'synth' || command === 'dev') && isRepoSource(resolve(input)) && isHandwrittenSource(resolve(input))) throw new Error(`${command}: ${input} is a hand-written shard file (the retired --template blender): run wildshard check on the repo, which settles and builds it`);
103
104
  if (command === 'synth') {
104
105
  if (output !== undefined) throw new Error('usage: wildshard synth <source>');
105
106
  const result = await synthProject(resolve(input));
@@ -117,13 +118,25 @@ async function runCommand(given: readonly string[], options: CliOptions): Promis
117
118
  else if (value.startsWith('--')) unknown = true;
118
119
  else names.push(value);
119
120
  }
120
- if (input.startsWith('--') || names.length > 1 || unknown || empty > 1 || templates.length > 1) throw new Error('usage: wildshard new <dir> [slug] [--template sdk|blender] [--empty]');
121
+ if (input.startsWith('--') || names.length > 1 || unknown || empty > 1 || templates.length > 1) throw new Error('usage: wildshard new <dir> [slug] [--template sdk] [--empty]');
121
122
  // An unknown template refuses here, before anything is written.
122
123
  const template = templateNamed(templates[0] ?? 'sdk');
123
124
  const slug = names[0] ?? input.split('/').reverse().find((part) => part !== '') ?? '';
124
125
  writeShardRepo(resolve(input), slug, { template, empty: empty === 1 });
125
126
  return;
126
127
  }
128
+ if (command === 'watch') {
129
+ // SHARD-SOURCE AP6: a scene shard's edits swap into the running page, no reload (`dev` is unchanged)
130
+ const port = output === undefined ? 0 : Number(output);
131
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('watch port must be 0..65535');
132
+ const server = await watchProject(resolve(input), { port, client: await devClient() });
133
+ const onSignal = (): void => {
134
+ // oxlint-disable-next-line unicorn/no-process-exit -- the signal handler replaced Node's default exit; ending is its job.
135
+ void server.close().finally(() => { process.exit(0); });
136
+ };
137
+ process.on('SIGINT', onSignal); process.on('SIGTERM', onSignal);
138
+ console.info(`wildshard watch: ${server.url}?skipintro`); return;
139
+ }
127
140
  if (command === 'dev') {
128
141
  const port = output === undefined ? 0 : Number(output);
129
142
  if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('dev port must be 0..65535');
@@ -0,0 +1,23 @@
1
+ import { ENGINE_MUSIC_STYLE, engineMusicFiles, musicDir } from '@wildshard/engine/audio/bootAudio';
2
+ import { withAssetTables, type AssetTables } from '@wildshard/engine/boot/tables';
3
+ import { MUSIC_MANIFESTS, SFX_MANIFESTS } from '@wildshard/engine/game/boot/audio.generated';
4
+ import { PUBLIC_BYTES } from '@wildshard/engine/game/boot/bytes.generated';
5
+ import { ASSET_VERSIONS } from '@wildshard/engine/game/boot/versions.generated';
6
+ import { PACKS } from '@wildshard/engine/game/boot/packs.generated';
7
+ import type { AudioData } from '@wildshard/format/audio';
8
+
9
+ /** The engine's own boot tables, as the page installs them: which engine music ships, and each file's bytes. */
10
+ export const ENGINE_TABLES: AssetTables = { bytes: PUBLIC_BYTES, versions: ASSET_VERSIONS, music: MUSIC_MANIFESTS, sfx: SFX_MANIFESTS, packs: PACKS };
11
+
12
+ /** AUDIO AU18: the build log's line for the engine music a shard plays, derived from its `audio/audio` rows by name,
13
+ * in the engine cook's `engineMusicLine` format. Undefined when the shard has no audio section. Throws, naming each,
14
+ * when the rows name engine music this engine's style lacks. */
15
+ export function engineMusicLine(shard: string, section: unknown, tables: AssetTables = ENGINE_TABLES): string | undefined {
16
+ if (typeof section !== 'object' || section === null || !('audio' in section)) return undefined;
17
+ const data = section.audio as AudioData, dir = musicDir(ENGINE_MUSIC_STYLE);
18
+ let files: string[];
19
+ try { files = withAssetTables(tables, () => engineMusicFiles(data)); }
20
+ catch (error) { throw new Error(`${shard}: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); }
21
+ const bytes = files.reduce((sum, url) => sum + (tables.bytes[url] ?? 0), 0);
22
+ return `${shard}: engine music: ${files.length} files, ${(bytes / 1e6).toFixed(2)} MB${files.length === 0 ? '' : ` (${files.map(url => url.slice(dir.length)).join(', ')})`}`;
23
+ }
@@ -119,7 +119,7 @@ import { AudioRoutingSchema } from '@wildshard/format/audioRouting';
119
119
  import { AudioDataSchema } from '@wildshard/format/audio';
120
120
  import { LedgerFactSchema, LedgerRulesSchema } from '@wildshard/format/ledger';
121
121
  import { DirectorSchema } from '@wildshard/format/director';
122
- import { DirectorProductSchema } from '@wildshard/format/directorProduct';
122
+ import { DirectorDocumentSchema as DirectorProductSchema } from '@wildshard/format/directorDocument';
123
123
  import { DirectorStagesSchema } from '@wildshard/format/directorStages';
124
124
  import { LogicalStateSchema, MigrationsSchema } from '@wildshard/format/migrations';
125
125
  import { TraversalSchema } from '@wildshard/format/traversal';
@@ -1,4 +1,4 @@
1
- import { assetCost } from '@wildshard/format/product';
1
+ import { assetCost } from '@wildshard/format/shardfileAssets';
2
2
  import { encodeCanonicalJson } from './immutable';
3
3
  import { hashAssetBytes } from './assetHandle';
4
4
 
@@ -150,7 +150,9 @@ readonly skyLightDirection: Node<"vec3">;
150
150
  /** Its linear colour multiplied by intensity; excludes shadowing and atmosphere fog colour. */
151
151
  readonly skyLightColour: Node<"vec3">;
152
152
  /** the scene colour at the pixel (a post input) */
153
- readonly sceneColour: Node<"vec4">; } = {
153
+ readonly sceneColour: Node<"vec4">;
154
+ /** the world direction through the pixel (a post input: sky detail; SHARD-SOURCE AP13) */
155
+ readonly viewRay: Node<"vec3">; } = {
154
156
  /** toward the light (the `sun` sub-graph only) */
155
157
  /** true for a front-facing fragment; vertex stages refuse this input */
156
158
  frontFacing: op('frontFacing', 'bool'),
@@ -198,6 +200,7 @@ readonly sceneColour: Node<"vec4">; } = {
198
200
  skyLightColour: op('skyLightColour', 'vec3'),
199
201
  /** the scene colour at the pixel (a post input) */
200
202
  sceneColour: op('sceneColour', 'vec4'),
203
+ viewRay: op('viewRay', 'vec3'),
201
204
  } as const;
202
205
 
203
206
  /** TSL built-ins that are graph inputs as they are (matched by identity; `uv()` by its attribute). */
@@ -264,7 +267,7 @@ function constLiteral(value: unknown): GraphLiteral | undefined {
264
267
  * const ir = graph({ flatShading: true, lighting: { sun: graphInputs.albedo.mul(graphInputs.sunColour).mul(cel).mul(1 / Math.PI) } });
265
268
  * ```
266
269
  */
267
- export function graph(spec: GraphSpec): GraphIr {
270
+ export function graph(spec: GraphSpec, host: { readonly budget?: GraphBudget } = {}): GraphIr {
268
271
  const nodes: Record<string, GraphNode> = {}, ids = new Map<Node, string>(), used = new Set<string>(), paramDefs: Record<string, GraphParam> = {};
269
272
  let counter = 0;
270
273
  const fresh = (): string => { let id = `n${counter++}`; while (used.has(id)) id = `n${counter++}`; return id; };
@@ -381,7 +384,8 @@ export function graph(spec: GraphSpec): GraphIr {
381
384
  ...(spec.doubleSided === undefined ? {} : { doubleSided: spec.doubleSided }), ...(spec.flipBackfaceNormals === undefined ? {} : { flipBackfaceNormals: spec.flipBackfaceNormals }), ...(spec.toonCaustics === undefined ? {} : { toonCaustics: spec.toonCaustics }), ...(spec.flatShading === undefined ? {} : { flatShading: spec.flatShading }),
382
385
  ...(Object.keys(paramDefs).length === 0 ? {} : { params: paramDefs }), nodes, stages,
383
386
  };
384
- const checked = validateGraph(structuredClone(ir), { trustedBudget: true });
387
+ // `host.budget`: the ceilings a host grants this kind of graph (a look's sky, AP14), checked here and never written in it
388
+ const checked = validateGraph(structuredClone(ir), { trustedBudget: true, ...(host.budget === undefined ? {} : { budget: host.budget }) });
385
389
  if (!checked.ok) throw new Error(`graph: ${checked.errors.join('; ')}`);
386
390
  return checked.graph;
387
391
  }
@@ -31,19 +31,24 @@ function writeInstallScriptPolicy(project: string): void {
31
31
  writeFileSync(resolve(project, 'pnpm-workspace.yaml'), INSTALL_SCRIPT_POLICY);
32
32
  }
33
33
 
34
- /** SA16 (J314, J317): `new --template <name>`. `sdk` is Mossgate (sharddev's `_template`); `blender` is shard-format's
35
- * hand-written `blender-template` (`corpus/handwritten`): a shard file folder held by hand, no sdk at runtime, no three. */
36
- export const TEMPLATES = ['sdk', 'blender'] as const;
34
+ /** SA16 (J314, J317): `new --template <name>`. `sdk` is Mossgate (sharddev's `_template`), the only template since
35
+ * SS5 (J341): a shard is TypeScript three.js scene source, and Blender makes the models it loads. */
36
+ export const TEMPLATES = ['sdk'] as const;
37
37
  export type TemplateName = (typeof TEMPLATES)[number];
38
+ /** What `writeShardRepo` can still lay out. `blender` is the retired hand-written shape (shard-format's
39
+ * `blender-template`, a shard file folder held by hand): `new` refuses it, but repos made that way still check and upload,
40
+ * so tests keep making one to prove that. */
41
+ export type RepoShape = TemplateName | 'blender';
38
42
  /** The template `new` makes with no flag. */
39
43
  export const DEFAULT_TEMPLATE: TemplateName = 'sdk';
40
44
  /** J317: a repo with one shard keeps its shard source at `src/`. */
41
45
  export const SHARD_SOURCE_FOLDER = 'src';
42
46
 
43
- /** The template named by `--template`, or a refusal that names both, thrown before anything is written. */
47
+ /** The template named by `--template`, or a refusal, thrown before anything is written. */
44
48
  export function templateNamed(name: string): TemplateName {
49
+ if (name === 'blender') throw new Error('new: --template blender is retired (J341): a shard is TypeScript three.js scene source, and Blender makes the .glb models that code loads; leave out --template. Repos made with it still check and upload');
45
50
  const found = TEMPLATES.find(template => template === name);
46
- if (found === undefined) throw new Error(`new: unknown template ${name}: use --template sdk or --template blender`);
51
+ if (found === undefined) throw new Error(`new: unknown template ${name}: leave out --template, or pass --template sdk`);
47
52
  return found;
48
53
  }
49
54
 
@@ -60,6 +65,9 @@ function sdkPackage(): SdkPackage {
60
65
  || !('dependencies' in parsed) || typeof parsed.dependencies !== 'object' || parsed.dependencies === null) throw new Error('new: the installed @wildshard/sdk has no package.json version');
61
66
  const dependencies: Record<string, string> = {};
62
67
  for (const [name, spec] of Object.entries(parsed.dependencies)) if (typeof spec === 'string') dependencies[name] = spec;
68
+ // SA8: `three` is the sdk's peer, pinned exact; a repo lists it at that pin like the others (dependencies win, as in updatePins).
69
+ const peers: unknown = 'peerDependencies' in parsed ? parsed.peerDependencies : undefined;
70
+ if (typeof peers === 'object' && peers !== null) for (const [name, spec] of Object.entries(peers)) if (typeof spec === 'string') dependencies[name] ??= spec;
63
71
  const node = 'engines' in parsed && typeof parsed.engines === 'object' && parsed.engines !== null && 'node' in parsed.engines && typeof parsed.engines.node === 'string' ? parsed.engines.node : undefined;
64
72
  if (node === undefined) throw new Error('new: the installed @wildshard/sdk names no Node engine');
65
73
  return { version: parsed.version, node, dependencies };
@@ -73,7 +81,7 @@ export const REPO_DEPENDENCIES = ['@wildshard/engine', '@wildshard/format', 'thr
73
81
  export const HANDWRITTEN_DEPENDENCIES = ['@wildshard/format'] as const;
74
82
 
75
83
  /** A new repo's package.json: the shard's slug, SA39's pnpm pin, and each Wildshard package pinned exactly. */
76
- export function repoPackageJson(slug: string, template: TemplateName = DEFAULT_TEMPLATE): string {
84
+ export function repoPackageJson(slug: string, template: RepoShape = DEFAULT_TEMPLATE): string {
77
85
  const sdk = sdkPackage(), dependencies: Record<string, string> = { '@wildshard/sdk': sdk.version };
78
86
  for (const name of template === 'blender' ? HANDWRITTEN_DEPENDENCIES : REPO_DEPENDENCIES) {
79
87
  const spec = sdk.dependencies[name];
@@ -115,7 +123,7 @@ const HANDWRITTEN_LAYOUT = `- \`src/\` is the shard source, written by hand: a s
115
123
  nothing here imports code, so no engine and no three.js. Its \`version\` is
116
124
  the version \`wildshard upload\` sends.`;
117
125
 
118
- function repoReadme(slug: string, template: TemplateName, empty: boolean): string {
126
+ function repoReadme(slug: string, template: RepoShape, empty: boolean): string {
119
127
  const handwritten = template === 'blender' && !empty;
120
128
  const world = empty ? 'a bare shard source (`--empty`)' : template === 'sdk' ? 'the reference world, Mossgate (Template 1)' : 'the hand-written Blender template (`blender-template`)';
121
129
  const files = empty ? '`data/`, `generators/`,\n `behaviour/` and `assets/`' : '`data/`,\n `generators/`, `behaviour/`, `assets/` and `manifest.json` (the card)';
@@ -148,7 +156,7 @@ ${layout}
148
156
 
149
157
  /** Write the repo files around a shard source at `src/`: package.json, tsconfig, ignores, README, and the agent files
150
158
  * (GUIDE.md, the four skills, their `.agents/skills` links, AGENTS.md and CLAUDE.md; SA28). */
151
- function writeRepoFiles(project: string, slug: string, template: TemplateName, empty: boolean): void {
159
+ function writeRepoFiles(project: string, slug: string, template: RepoShape, empty: boolean): void {
152
160
  writeFileSync(resolve(project, 'package.json'), repoPackageJson(slug, empty ? DEFAULT_TEMPLATE : template));
153
161
  // A hand-written repo holds no TypeScript to check.
154
162
  if (template !== 'blender' || empty) writeFileSync(resolve(project, 'tsconfig.json'), TSCONFIG);
@@ -199,8 +207,8 @@ export function writeEmptyShardSource(source: string, slug: string): void {
199
207
  writeEmptySource(source, slug);
200
208
  }
201
209
 
202
- /** `wildshard new <dir> [slug] [--template sdk|blender] [--empty]`: a whole single-shard repo, its shard source at `src/`. */
203
- export function writeShardRepo(project: string, slug: string, options: { readonly template?: TemplateName; readonly empty?: boolean } = {}): void {
210
+ /** `wildshard new <dir> [slug] [--template sdk] [--empty]` (and the retired `blender` shape, for tests): a whole single-shard repo, its shard source at `src/`. */
211
+ export function writeShardRepo(project: string, slug: string, options: { readonly template?: RepoShape; readonly empty?: boolean } = {}): void {
204
212
  const template = options.template ?? DEFAULT_TEMPLATE;
205
213
  assertTarget(project, slug);
206
214
  mkdirSync(project, { recursive: true });
@@ -12,7 +12,7 @@ import { outputSectionPayloads, OUTPUT_SECTIONS } from '@wildshard/format/output
12
12
  import { decisionScriptsFromSections, scriptAdmissionRows, type ScriptAdmissionRows } from '@wildshard/format/scriptContract';
13
13
  import type { DecisionScripts } from '@wildshard/format/decisionScripts';
14
14
  import { structuralGridEvidence } from '@wildshard/format/gridReadiness';
15
- import { offlineMemoryAdmission } from '@wildshard/format/product';
15
+ import { offlineMemoryAdmission } from '@wildshard/format/shardfileAssets';
16
16
  import { validationRevision, validationSourceBytes } from '@wildshard/format/validationReceipt';
17
17
  import { preflightDeclaredCosts } from '@wildshard/format/assetAdmission';
18
18
  import { admitProduct, readmitted, rememberAdmitted } from './productOutput';
@@ -26,7 +26,7 @@ import { COOK_DATA_PATH, cookMountPath } from '@wildshard/format/cookData';
26
26
  import type { CookInput } from './cookInput';
27
27
  import { validateDefinedJson, type EmittedSections } from './sections';
28
28
  import { parseDiscoveryValues, type DiscoveryValues } from '@wildshard/format/discoveryValues';
29
- import { checkWorldTargets, outputBlobExtension as blobExtension, outputBlobKind as blobKind, readCanonicalJson as readJson, validateShardfileProduct, type ProductFiles, type ValidatedProduct } from '@wildshard/format/productValidation';
29
+ import { checkWorldTargets, outputBlobExtension as blobExtension, outputBlobKind as blobKind, readCanonicalJson as readJson, validateShardfileFolder as validateShardfileProduct, type ShardfileFiles as ProductFiles, type ValidatedShardfile as ValidatedProduct } from '@wildshard/format/shardfileValidation';
30
30
 
31
31
  const encoder = new TextEncoder();
32
32
  function jsonBytes(value: unknown): Uint8Array { return encoder.encode(encodeCanonicalJson(value)); }
@@ -4,8 +4,8 @@ import { mkdirSync, writeFileSync } from 'node:fs';
4
4
  import { resolve } from 'node:path';
5
5
  import type { ScriptAdmissionRows } from '@wildshard/format/scriptContract';
6
6
  import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
7
- import { admitShardfileProduct, assertProductTargets as assertTargets } from '@wildshard/format/productValidation';
8
- import { offlineMemoryAdmission, prepareAssetDecoders } from '@wildshard/format/product';
7
+ import { admitShardfileFolder as admitShardfileProduct, assertShardfileTargets as assertTargets } from '@wildshard/format/shardfileValidation';
8
+ import { offlineMemoryAdmission, prepareAssetDecoders } from '@wildshard/format/shardfileAssets';
9
9
  import { validationRevision, validationSourceBytes } from '@wildshard/format/validationReceipt';
10
10
  import { preflightDeclaredCosts } from '@wildshard/format/assetAdmission';
11
11
  import { CLIENT_FEATURE_SIDES, unsidedKinds } from '@wildshard/format/featureSides';
@@ -16,7 +16,7 @@ import process from 'node:process';
16
16
  import { build } from 'vite';
17
17
  import ts from '@typescript/typescript6';
18
18
  import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
19
- import { preflightAssetGraph, offlineMemoryAdmission, prepareAssetDecoders } from "@wildshard/format/product";
19
+ import { preflightAssetGraph, offlineMemoryAdmission, prepareAssetDecoders } from "@wildshard/format/shardfileAssets";
20
20
  import { preflightDeclaredCosts } from '@wildshard/format/assetAdmission';
21
21
  import { preflightShardfile } from '@wildshard/format/preflight';
22
22
 
@@ -37,6 +37,7 @@ import { projectPlaceholders } from './bake/placeholders';
37
37
  import type { ScriptAdmissionRows } from '@wildshard/format/scriptContract';
38
38
  import { readCookInput, type CookInput } from './cookInput';
39
39
  import { audioEncodeLine, encodeMountAudio, readStereoMarks } from './audioEncode';
40
+ import { engineMusicLine } from './engineMusic';
40
41
  import { AUTHOR_BUDGETS, AUTHOR_BUDGETS_MODULE, authorManifest } from './authorManifest';
41
42
  import { discoveryDocument, discoveryUrl } from './discoveryDocument';
42
43
  import { outputScriptAdmissionRows, outputPlatformPayloads, clearOutputProduct, writeOutputProduct, type OutputProductOptions } from './outputProduct';
@@ -285,6 +286,10 @@ export async function buildProject(project: string, output?: string, options: {
285
286
  descriptor = writeOutputProduct(shard, assets, destination, { ...loaded.output, ...(runtime === undefined ? {} : { runtime }), ...(cook === undefined ? {} : { cook }) });
286
287
  assertNoRenamedAudioNames(destination, encoded?.renamed ?? new Map());
287
288
  phase('product-write');
289
+ // AUDIO AU18: name the engine music this shard plays, derived from its audio rows (a name the engine lacks refuses).
290
+ const audio = descriptor.sections.find(row => row.name === 'audio/audio');
291
+ const music = audio === undefined ? undefined : engineMusicLine(shard.identity.slug, JSON.parse(readFileSync(resolve(destination, audio.path), 'utf8')));
292
+ if (music !== undefined) console.info(music);
288
293
  if (runtime !== undefined) proveRuntimeData(destination, descriptor, loaded.mirrors);
289
294
  phase('runtime-proof');
290
295
  } catch (error) { clearOutputProduct(destination); throw error; }
@@ -1,5 +1,5 @@
1
1
  import { parseShardfile, type Shardfile } from '@wildshard/format/shardSchema';
2
- import { assetCost } from '@wildshard/format/product';
2
+ import { assetCost } from '@wildshard/format/shardfileAssets';
3
3
  import { hashAssetBytes } from './assetHandle';
4
4
 
5
5
  /** Build input for a baked map; paths and URLs never enter the authored product. */
@@ -37,13 +37,15 @@ export const GUIDE_FILE = 'GUIDE.md';
37
37
 
38
38
  /** The refusals that are not lint rules, most specific first; each step has one catch-all (no `match`). */
39
39
  export const REFUSAL_RULES: readonly RefusalRule[] = [
40
+ { id: 'three-version', anchor: 'three-version', steps: 'any', match: /^\[three-version\] /,
41
+ fix: 'Install the three the sdk pins: pnpm add three@<the version named> --save-exact.' },
40
42
  { id: 'usage', anchor: 'usage', steps: 'any', match: /^usage: |^unknown (?:wildshard command|build flag|command)|unknown or incomplete build map flag|^Unknown schema root|accepts no pointer|^dev port must be|^invalid --port\b|^(?:validate|prove) requires a format-2 shard\.json or (?:shard source|author project)/u,
41
43
  fix: 'Run `wildshard --help` and give the verb the arguments and flags it lists.' },
42
44
  // new
43
45
  { id: 'new-target', anchor: 'new-target', steps: ['new'], match: /new requires a fresh directory and kebab-case slug/u,
44
46
  fix: 'Name a folder that does not exist yet and a kebab-case slug: `wildshard new my-isle`.' },
45
- { id: 'new-template', anchor: 'new-template', steps: ['new'], match: /^new: unknown template /u,
46
- fix: 'Leave out --template, or pass `--template sdk` (the reference world) or `--template blender` (the hand-written Blender template).' },
47
+ { id: 'new-template', anchor: 'new-template', steps: ['new'], match: /^new: (?:unknown template |--template blender is retired)/u,
48
+ fix: 'Leave out --template (sdk is the only one). blender is retired: write three.js scene source; Blender makes models.' },
47
49
  { id: 'new-refused', anchor: 'new-refused', steps: ['new'],
48
50
  fix: 'Reinstall @wildshard/sdk (`pnpm install`); `new` copies the reference world shipped with it.' },
49
51
  // update (SA28)
@@ -198,7 +200,7 @@ export const REFUSAL_RULES: readonly RefusalRule[] = [
198
200
  fix: 'Read the reason: a format refusal means build again (`wildshard build`); a server refusal names what it wants.' },
199
201
  // lint, besides the rules below
200
202
  { id: 'lint-not-run', anchor: 'lint-not-run', steps: ['lint'], match: /^oxlint (?:did not run|exited|report has no)/u,
201
- fix: 'Reinstall @wildshard/sdk (`pnpm install`): the author lint ships with it.' },
203
+ fix: 'Reinstall (`pnpm install`): the author lint runs the repo\'s oxlint, or the one that ships with @wildshard/sdk.' },
202
204
  { id: 'lint-refused', anchor: 'lint-refused', steps: ['lint'],
203
205
  fix: 'Fix what the message names at the file and line shown.' },
204
206
  ];
@@ -1,4 +1,4 @@
1
- import { performanceReport as report, performanceReportLines as lines, performanceTargetIssues as targets, type PerformanceReport as GameReport, type PerformanceObservations as GameObservations } from '@wildshard/format/product';
1
+ import { performanceReport as report, performanceReportLines as lines, performanceTargetIssues as targets, type PerformanceReport as GameReport, type PerformanceObservations as GameObservations } from '@wildshard/format/shardfileAssets';
2
2
  import type { Shardfile } from '@wildshard/format/shardSchema';
3
3
 
4
4
  /** Author-facing report: declared bounds, measured scripts and explicit cold-network assumptions. */
@@ -0,0 +1,184 @@
1
+ import { DataTexture, LinearFilter, LinearMipmapLinearFilter, Mesh, MeshStandardMaterial, RepeatWrapping, SRGBColorSpace, ShapeGeometry, LinearSRGBColorSpace, type ColorRepresentation, type Group, type Object3D, type Scene, type Shape } from 'three';
2
+ import { positionLocal } from 'three/tsl';
3
+ import type { DetailLayer } from '@wildshard/format/detail-layer';
4
+ import type { GraphValue } from '../materials';
5
+ import type { Rgb, SceneMotion, ScenePost } from './description';
6
+
7
+ /**
8
+ * AUTHORING-PARITY AP1: what an author's scene module calls besides three.js itself. Everything here runs at compile time
9
+ * only (on the author's machine or CI), never in a player's page or on the server.
10
+ */
11
+
12
+ /** The world a `defineShard` build function receives. `scene` is a plain three.js `Scene`: add to it as in a cleanroom. */
13
+ /** AP16: what a part is besides its content. */
14
+ export interface PartOptions {
15
+ /** a panel id (`brasscap.gate`): the part's meshes are one hideable GLB and its solids one collider, both of this id */
16
+ readonly panel?: string;
17
+ }
18
+
19
+ export interface ShardWorld {
20
+ readonly scene: Scene;
21
+ /**
22
+ * A named piece of the world, the unit `watch` swaps. Objects added to `scene` outside a part belong to part `scene`.
23
+ * `options.panel` makes the part a panel (SHARD-SOURCE AP16): its meshes ship as one GLB the shard's `targets.panels`
24
+ * rows show and hide by state (a gate that opens, a rifle taken off a rack), and its solids as one collider of that id.
25
+ */
26
+ part: (name: string, build: (part: Group) => void, options?: PartOptions) => Group;
27
+ /**
28
+ * The ground: its height everywhere in the 500 m cell, and optionally its colour (linear RGB). `material` is the
29
+ * cleanroom ground mesh's `MeshStandardMaterial` (its colour, roughness and metalness; the vertex colours are
30
+ * `colourAt`); a map on it does not reach the shard (the terrain has no uvs): say its grain with `detail`, the PBR
31
+ * family's procedural layer (format `detail-layer`), drawn from world position.
32
+ */
33
+ ground: (heightAt: (x: number, z: number) => number, options?: { colourAt?: (x: number, z: number) => Rgb; material?: MeshStandardMaterial; detail?: DetailLayer }) => void;
34
+ /**
35
+ * AP14: the sky, a TSL colour (linear) along {@link skyRay}, drawn on the engine's dome in place of its gradient: the
36
+ * cleanroom's sky dome `ShaderMaterial`, written in TSL. `environment` lights PBR surfaces from that same sky (three's
37
+ * `scene.environment` from a PMREM of the dome, at `intensity`, over a `ground` colour), so ponds and metal reflect it.
38
+ */
39
+ sky: (colour: GraphValue, options?: { environment?: { intensity: number; ground: Rgb } }) => void;
40
+ /** The cleanroom's composer, as numbers. */
41
+ post: (settings: Partial<Omit<ScenePost, 'bloom'>> & { bloom?: ScenePost['bloom'] }) => void;
42
+ /** Where a player enters. */
43
+ spawn: (x: number, y: number, z: number, yaw?: number) => void;
44
+ }
45
+
46
+ /** AP14: the view ray through a sky pixel (unit, world axes, y up): the dome is centred on the camera. */
47
+ export const skyRay: ReturnType<typeof positionLocal.normalize> = positionLocal.normalize();
48
+
49
+ /** Painted pixels by texture source: `clone()` shares the source, so a clone with its own `repeat` still lowers. */
50
+ /** as a canvas `ImageData` stores a value: clamped to 0..255 and rounded */
51
+ export const byte = (value: number): number => Math.min(255, Math.max(0, Math.round(value)));
52
+ const PAINTED = new WeakMap<object, { width: number; height: number; rgba: Uint8Array }>();
53
+ export const paintedPixels = (source: object): { width: number; height: number; rgba: Uint8Array } | undefined => PAINTED.get(source);
54
+
55
+ /**
56
+ * `paint(w, h, fn)`: a texture painted per pixel, the cleanroom's `paint` without a canvas. `fn(u, v, x, y)` returns
57
+ * `[r, g, b, a?]` in 0..255 with row 0 at the top, as a canvas draws; the texture samples as a `CanvasTexture` would
58
+ * (sRGB, repeat, mipmapped). This is J338's procedural path: the shardfile ships the pixels, no image file is authored.
59
+ */
60
+ export function paint(width: number, height: number, fn: (u: number, v: number, x: number, y: number) => readonly number[], options: { colourSpace?: 'srgb' | 'linear' } = {}): DataTexture {
61
+ checkSize(width, height);
62
+ return memoPainted('paint', width, height, fn, options, () => {
63
+ const top = new Uint8Array(width * height * 4);
64
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) {
65
+ const [r = 0, g = 0, b = 0, a = 255] = fn(x / width, y / height, x, y), i = (y * width + x) * 4;
66
+ top[i] = byte(r); top[i + 1] = byte(g); top[i + 2] = byte(b); top[i + 3] = byte(a);
67
+ }
68
+ return top;
69
+ });
70
+ }
71
+
72
+ /**
73
+ * SHARD-SOURCE AP17: `wildshard watch`'s paint memo. A watched revision reruns the author's whole build, and painting is most
74
+ * of it (the authoring slice: ~200 of ~250 ms). While `withPaintMemo` runs a build in `guess` mode, a `paint` or
75
+ * `paintCanvas` call whose painter source, size and colour space match the n-th such call of the last revision takes that
76
+ * call's pixels without painting. It is a guess: a painter's closure can change while its source text does not. So watch
77
+ * pushes the guess, then runs the build again in `truth` mode (every call paints) and pushes the difference, if any.
78
+ */
79
+ export class PaintMemo {
80
+ private last = new Map<string, Uint8Array>();
81
+ private now = new Map<string, Uint8Array>();
82
+ private readonly seen = new Map<string, number>();
83
+ mode: 'guess' | 'truth' = 'guess';
84
+ hits = 0;
85
+ misses = 0;
86
+ /** Start a build: what the last one painted (or guessed) is what this one may take. */
87
+ begin(mode: 'guess' | 'truth'): void {
88
+ if (this.now.size > 0) this.last = this.now;
89
+ this.now = new Map(); this.seen.clear(); this.mode = mode; this.hits = 0; this.misses = 0;
90
+ }
91
+ /** One call's pixels (rows bottom first, as the texture holds them): the last revision's, or `paint()`'s. */
92
+ pixels(kind: string, width: number, height: number, source: string, colourSpace: string, draw: () => Uint8Array): Uint8Array {
93
+ const base = `${kind}|${width}x${height}|${colourSpace}|${source}`, nth = this.seen.get(base) ?? 0;
94
+ this.seen.set(base, nth + 1);
95
+ const key = `${base}#${nth}`, kept = this.mode === 'guess' ? this.last.get(key) : undefined;
96
+ if (kept !== undefined) this.hits++; else this.misses++;
97
+ const rgba = kept ?? draw();
98
+ this.now.set(key, rgba);
99
+ return rgba;
100
+ }
101
+ }
102
+ let memo: PaintMemo | null = null;
103
+ /** Run `build` with `next` as the paint memo (null: none, every call paints). */
104
+ export function withPaintMemo<T>(next: PaintMemo | null, build: () => T): T {
105
+ const before = memo; memo = next;
106
+ try { return build(); } finally { memo = before; }
107
+ }
108
+ /** A painter's texture through the memo, when one is set (rows top first in, as a canvas holds them). */
109
+ export function memoPainted(kind: string, width: number, height: number, painter: object, options: { colourSpace?: 'srgb' | 'linear' }, top: () => Uint8Array): DataTexture {
110
+ if (memo === null) return paintedTexture(width, height, top(), options);
111
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string -- a painter is a function: its source text is the key
112
+ const rgba = memo.pixels(kind, width, height, String(painter), options.colourSpace ?? 'srgb', () => flipRows(width, height, top()));
113
+ return textureOf(width, height, rgba, options);
114
+ }
115
+
116
+ /** A texture size from 1 to 4096 a side, or a refusal. */
117
+ export function checkSize(width: number, height: number): void {
118
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 4096 || height > 4096) throw new Error(`paint: ${width}x${height} is not a texture size from 1 to 4096`);
119
+ }
120
+
121
+ /** RGBA8 rows top first (as a canvas holds them) as the texture a `CanvasTexture` of that canvas would be. */
122
+ export function paintedTexture(width: number, height: number, top: Uint8Array, options: { colourSpace?: 'srgb' | 'linear' } = {}): DataTexture {
123
+ return textureOf(width, height, flipRows(width, height, top), options);
124
+ }
125
+
126
+ /** Canvas row y (top = 0) is texture row height-1-y: a CanvasTexture flips Y on upload, a DataTexture does not. */
127
+ function flipRows(width: number, height: number, top: Uint8Array): Uint8Array {
128
+ const rgba = new Uint8Array(width * height * 4);
129
+ for (let y = 0; y < height; y++) rgba.set(top.subarray(y * width * 4, (y + 1) * width * 4), (height - 1 - y) * width * 4);
130
+ return rgba;
131
+ }
132
+
133
+ function textureOf(width: number, height: number, rgba: Uint8Array, options: { colourSpace?: 'srgb' | 'linear' }): DataTexture {
134
+ const texture = new DataTexture(rgba, width, height);
135
+ texture.colorSpace = options.colourSpace === 'linear' ? LinearSRGBColorSpace : SRGBColorSpace;
136
+ texture.wrapS = texture.wrapT = RepeatWrapping;
137
+ texture.magFilter = LinearFilter; texture.minFilter = LinearMipmapLinearFilter; texture.generateMipmaps = true;
138
+ texture.needsUpdate = true;
139
+ PAINTED.set(texture.source, { width, height, rgba });
140
+ return texture;
141
+ }
142
+
143
+ const SOLID = new WeakSet<Object3D>();
144
+ /** `solid(mesh)`: the mesh is also a collider, its own box in its own frame. Said once, beside the mesh. */
145
+ export function solid<T extends Object3D>(object: T): T { SOLID.add(object); return object; }
146
+ export const isSolid = (object: Object3D): boolean => SOLID.has(object);
147
+
148
+ /** A water surface: an outline in the XZ plane (as `ShapeGeometry` makes it, then laid flat), a tint, a reflection. */
149
+ export class Water extends Mesh<ShapeGeometry, MeshStandardMaterial> {
150
+ readonly tint: ColorRepresentation;
151
+ readonly reflect: 'planar' | 'sky';
152
+ readonly shape: Shape;
153
+ constructor(shape: Shape, options: { tint?: ColorRepresentation; reflect?: 'planar' | 'sky'; segments?: number } = {}) {
154
+ const material = new MeshStandardMaterial({ color: options.tint ?? '#3a3458', roughness: 0.08, metalness: 0.2, transparent: true, opacity: 0.86 });
155
+ super(new ShapeGeometry(shape, options.segments ?? 24), material);
156
+ this.shape = shape; this.tint = options.tint ?? '#3a3458'; this.reflect = options.reflect ?? 'planar';
157
+ this.rotation.x = -Math.PI / 2;
158
+ this.name = 'water';
159
+ }
160
+ }
161
+
162
+ const MOTION = new WeakMap<Object3D, SceneMotion>();
163
+ /**
164
+ * `animate(node, motion)`: declared motion (SHARD-SOURCE AP12), the cleanroom's `update(t)` said as data. The engine plays
165
+ * it per frame; no author code runs in a page. A motion on a group reaches every object under it in its part.
166
+ *
167
+ * - `flicker` on a `PointLight`: its intensity wavers (a lamp, a fire);
168
+ * - `pulse` on a `Sprite`: the card breathes (a flame tongue); `drift` / `rise` on a `Sprite` or `Points`: the card wanders
169
+ * round its seat (fireflies) or climbs and fades (sparks);
170
+ * - `sway` on a mesh: it bends in the wind from its root (foliage); `uvScroll` on a mesh: its map moves (water, cloud).
171
+ */
172
+ export function animate<T extends Object3D>(object: T, motion: SceneMotion): T { MOTION.set(object, motion); return object; }
173
+ /** The motion declared on `object` or its nearest animated ancestor under `root`. */
174
+ export function motionOf(object: Object3D, root: Object3D): SceneMotion | null {
175
+ for (let node: Object3D | null = object; node !== null; node = node.parent) { const m = MOTION.get(node); if (m !== undefined) return m; if (node === root) break; }
176
+ return null;
177
+ }
178
+ export const flicker = (o: { rate: number; amount: number }): SceneMotion => ({ kind: 'flicker', rate: o.rate, amount: o.amount });
179
+ export const pulse = (o: { rate: number; amount: number }): SceneMotion => ({ kind: 'pulse', rate: o.rate, amount: o.amount });
180
+ export const drift = (o: { rate: number; radius: number }): SceneMotion => ({ kind: 'drift', rate: o.rate, radius: o.radius });
181
+ export const rise = (o: { rate: number; height: number; spread?: number }): SceneMotion => ({ kind: 'rise', rate: o.rate, height: o.height, spread: o.spread ?? 0 });
182
+ /** `amount`: metres the top of the mesh moves; it grows with the square of the height over the mesh's own bounds. */
183
+ export const sway = (o: { rate: number; amount: number; direction?: readonly [number, number] }): SceneMotion => ({ kind: 'sway', rate: o.rate, amount: o.amount, direction: o.direction ?? [0.8, 0.6] });
184
+ export const uvScroll = (u: number, v: number): SceneMotion => ({ kind: 'uvScroll', u, v });