@bendyline/molen-tooling 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/capture/harness.js +216 -216
  2. package/dist/capture/worldgen-preview.js +288 -288
  3. package/dist/cli.mjs +110 -10
  4. package/dist/docs-src/guide/3d-model-assets.md +35 -3
  5. package/dist/docs-src/guide/adaptive-performance.md +4 -0
  6. package/dist/docs-src/guide/agent-loop.md +6 -6
  7. package/dist/docs-src/guide/aircraft.md +16 -7
  8. package/dist/docs-src/guide/audio.md +247 -0
  9. package/dist/docs-src/guide/browser-mount.md +3 -1
  10. package/dist/docs-src/guide/building-interiors.md +5 -4
  11. package/dist/docs-src/guide/determinism.md +12 -12
  12. package/dist/docs-src/guide/earth-view.md +444 -0
  13. package/dist/docs-src/guide/entities.md +1 -1
  14. package/dist/docs-src/guide/examples.md +2 -1
  15. package/dist/docs-src/guide/game-samples.md +21 -4
  16. package/dist/docs-src/guide/graphics-performance.md +40 -8
  17. package/dist/docs-src/guide/input.md +9 -0
  18. package/dist/docs-src/guide/markers.md +52 -0
  19. package/dist/docs-src/guide/materials.md +10 -3
  20. package/dist/docs-src/guide/navigation.md +144 -0
  21. package/dist/docs-src/guide/project.md +1 -1
  22. package/dist/docs-src/guide/quickstart.md +2 -2
  23. package/dist/docs-src/guide/recognizable-places.md +3 -2
  24. package/dist/docs-src/guide/scripting.md +4 -2
  25. package/dist/docs-src/guide/sky.md +16 -0
  26. package/dist/docs-src/guide/source-bundles.md +0 -1
  27. package/dist/docs-src/guide/structure-library.md +2 -2
  28. package/dist/docs-src/guide/terrain.md +45 -2
  29. package/dist/docs-src/guide/vehicles.md +18 -9
  30. package/dist/docs-src/guide/worldgen.md +3 -3
  31. package/dist/docs-src/llms.txt +10 -4
  32. package/dist/docs-src/schemas/README.md +3 -0
  33. package/dist/docs-src/schemas/archive-set.md +175 -0
  34. package/dist/docs-src/schemas/components.md +1104 -1
  35. package/dist/docs-src/schemas/matgraph.md +6 -0
  36. package/dist/docs-src/schemas/soundbank.md +251 -0
  37. package/dist/docs-src/schemas/structure-placements.md +496 -0
  38. package/dist/docs-src/schemas/terrain-package.md +120 -0
  39. package/dist/index.d.mts +5 -1
  40. package/dist/index.mjs +1 -1
  41. package/dist/{mcp-AOfIp89b.mjs → mcp-BTVwVKFb.mjs} +67 -3
  42. package/dist/{ops-C4BvDgP-.mjs → ops-BPdHodFR.mjs} +915 -29
  43. package/dist/templates/city-courier/README.md +13 -0
  44. package/dist/templates/city-courier/delivery-run.replay.json +151 -151
  45. package/dist/templates/city-courier/gen/molen-types.ts +142 -4
  46. package/dist/templates/city-courier/package.json +1 -0
  47. package/dist/templates/city-courier/scene.json +79 -0
  48. package/dist/templates/city-courier/scripts/game.ts +5 -1
  49. package/dist/templates/city-courier/scripts/molen-scripts.d.ts +167 -4
  50. package/dist/templates/city-courier/src/audio.ts +96 -0
  51. package/dist/templates/city-courier/src/game-shell.css +8 -0
  52. package/dist/templates/city-courier/src/main.ts +3 -0
  53. package/dist/templates/city-courier/test/headless.test.ts +1 -1
  54. package/dist/templates/index.json +3 -0
  55. package/dist/templates/skybound/README.md +13 -0
  56. package/dist/templates/skybound/first-leap.replay.json +152 -152
  57. package/dist/templates/skybound/gen/molen-types.ts +142 -4
  58. package/dist/templates/skybound/package.json +1 -0
  59. package/dist/templates/skybound/scene.json +40 -0
  60. package/dist/templates/skybound/scripts/game.ts +8 -5
  61. package/dist/templates/skybound/scripts/molen-scripts.d.ts +167 -4
  62. package/dist/templates/skybound/src/audio.ts +96 -0
  63. package/dist/templates/skybound/src/game-shell.css +8 -0
  64. package/dist/templates/skybound/src/main.ts +3 -0
  65. package/dist/templates/skybound/test/headless.test.ts +1 -1
  66. package/dist/templates/top-down-arena/README.md +14 -1
  67. package/dist/templates/top-down-arena/arena-skirmish.replay.json +152 -152
  68. package/dist/templates/top-down-arena/package.json +1 -0
  69. package/dist/templates/top-down-arena/scene.json +20 -0
  70. package/dist/templates/top-down-arena/scripts/combat.ts +1 -0
  71. package/dist/templates/top-down-arena/scripts/molen-scripts.d.ts +167 -4
  72. package/dist/templates/top-down-arena/src/audio.ts +96 -0
  73. package/dist/templates/top-down-arena/src/gen/molen-types.ts +142 -4
  74. package/dist/templates/top-down-arena/src/main.ts +3 -0
  75. package/dist/templates/top-down-arena/test/headless.test.ts +1 -1
  76. package/package.json +11 -11
@@ -10,20 +10,21 @@ import { createPlacesContent, createRegionResolver, semanticTileToBatch, tileGro
10
10
  import { evaluateCameraTrack, registerCameraTrackSchema } from "@bendyline/molen-client/camera-track";
11
11
  import { createReadStream, watch } from "node:fs";
12
12
  import { createServer } from "node:http";
13
- import { buildTypeIndex, checkTypes, componentMapIssues, componentNames, createComponentRegistry, decodeCollisionTrimesh, detectKind, encodeCollisionTrimesh, formatIssues, getComponent, getSchema, listComponents, listSchemas, namespaceCovers, registerSchema, resolveAllTypes, sceneTypeRefIssues, schemaKinds, validate, validateByKind } from "@bendyline/molen-schema";
13
+ import { audioSignalIssues, audioSignalRefs, audioSoundRefs, buildTypeIndex, checkTypes, componentMapIssues, componentNames, createComponentRegistry, decodeCollisionTrimesh, detectKind, encodeCollisionTrimesh, formatIssues, getComponent, getSchema, listComponents, listSchemas, namespaceCovers, nearestWithDistance, registerSchema, resolveAllTypes, sceneTypeRefIssues, schemaKinds, validate, validateByKind, weatherProfile } from "@bendyline/molen-schema";
14
14
  import { z } from "zod";
15
15
  import { createHash, randomUUID } from "node:crypto";
16
16
  import { Node, NodeIO, getBounds } from "@gltf-transform/core";
17
17
  import { ALL_EXTENSIONS, KHRTextureBasisu } from "@gltf-transform/extensions";
18
- import { dedup, getTextureColorSpace, listTextureSlots, prune, quantize, weld } from "@gltf-transform/functions";
18
+ import { dedup, getTextureColorSpace, listTextureInfoByMaterial, listTextureSlots, prune, quantize, weld } from "@gltf-transform/functions";
19
19
  import { fileURLToPath, pathToFileURL } from "node:url";
20
20
  import { stripScriptTypes } from "@bendyline/molen-client/vite";
21
- import { ENGINE_VERSION, STATE_FORMAT, World, applyKeyframeTo, buildWorld, contentDrift, dmath, installGameplay, isExperience, keyframeStateFormat, stateHash, takeKeyframe, worldFromKeyframe } from "@bendyline/molen-kernel";
21
+ import { ENGINE_VERSION, STATE_FORMAT, World, applyKeyframeTo, buildWorld, contentDrift, dmath, installGameplay, isExperience, keyframeStateFormat, quatRotateVec3, stateHash, takeKeyframe, worldFromKeyframe } from "@bendyline/molen-kernel";
22
22
  import { homedir, tmpdir } from "node:os";
23
23
  import { createTypeLibrary } from "@bendyline/molen-kernel/content";
24
24
  import { createPackSet, openPack, sha256 } from "@bendyline/molen-pack";
25
- import { PACK_SOURCE_FILE, buildPack, extractPack, openPackAt } from "@bendyline/molen-pack/node";
25
+ import { PACK_SOURCE_FILE, buildPack, extractPack, openPackAt, recordInPackIndex } from "@bendyline/molen-pack/node";
26
26
  import { installTerrain, terrainScriptApi } from "@bendyline/molen-kernel/terrain";
27
+ import { AudioDirector, entitySourceFromWorld, mergeSoundbanks } from "@bendyline/molen-client/audio";
27
28
  import { diffKeyframes, firstDivergentTick, formatAssertionResults, perTickHashes, runAssertions, runHeadless } from "@bendyline/molen-kernel/testing";
28
29
  import { hashJson } from "@bendyline/molen-kernel/determinism";
29
30
  import { PMTiles } from "pmtiles";
@@ -1061,6 +1062,67 @@ function buildStats(doc, sizeBytes) {
1061
1062
  };
1062
1063
  }
1063
1064
  const NODE_CAP = 128;
1065
+ /** Only the explicit, supported extras contract makes unused UV0 meaningful at runtime. */
1066
+ function sharedSurfaceRef(material) {
1067
+ const value = material?.getExtras().molenSurface;
1068
+ if (value === null || typeof value !== "object") return void 0;
1069
+ const surface = value;
1070
+ return surface.uv === "repeats" && typeof surface.ref === "string" && surface.ref.trim().length > 0 && typeof surface.slot === "string" && [
1071
+ "wall",
1072
+ "roof",
1073
+ "trim",
1074
+ "foundation",
1075
+ "window",
1076
+ "door"
1077
+ ].includes(surface.slot) ? surface.ref : void 0;
1078
+ }
1079
+ /** Keep opted-in UV0 across pruning without retaining unused attributes on other primitives. */
1080
+ async function prunePreservingSharedSurfaceUvs(doc) {
1081
+ const saved = /* @__PURE__ */ new Map();
1082
+ for (const mesh of doc.getRoot().listMeshes()) for (const primitive of mesh.listPrimitives()) {
1083
+ const uv = primitive.getAttribute("TEXCOORD_0");
1084
+ if (sharedSurfaceRef(primitive.getMaterial()) === void 0 || uv === null) continue;
1085
+ let semantic = "_MOLEN_SHARED_UV0";
1086
+ while (primitive.getAttribute(semantic) !== null) semantic += "_";
1087
+ primitive.setAttribute(semantic, uv);
1088
+ saved.set(primitive, semantic);
1089
+ }
1090
+ await doc.transform(prune());
1091
+ const groups = /* @__PURE__ */ new Map();
1092
+ for (const mesh of doc.getRoot().listMeshes()) for (const primitive of mesh.listPrimitives()) {
1093
+ const material = primitive.getMaterial();
1094
+ if (material === null || sharedSurfaceRef(material) === void 0) continue;
1095
+ const group = groups.get(material) ?? [];
1096
+ group.push(primitive);
1097
+ groups.set(material, group);
1098
+ }
1099
+ for (const [material, primitives] of groups) {
1100
+ if (primitives.some((primitive) => {
1101
+ const semantic = saved.get(primitive);
1102
+ const uv = primitive.getAttribute("TEXCOORD_0");
1103
+ return uv !== null && (semantic === void 0 || uv !== primitive.getAttribute(semantic));
1104
+ })) {
1105
+ const shiftUvs = (primitive) => {
1106
+ const coordinates = primitive.listSemantics().filter((semantic) => /^TEXCOORD_\d+$/.test(semantic)).map((semantic) => Number(semantic.slice(9))).sort((a, b) => b - a);
1107
+ for (const index of coordinates) {
1108
+ primitive.setAttribute(`TEXCOORD_${index + 1}`, primitive.getAttribute(`TEXCOORD_${index}`));
1109
+ primitive.setAttribute(`TEXCOORD_${index}`, null);
1110
+ }
1111
+ };
1112
+ for (const primitive of primitives) {
1113
+ shiftUvs(primitive);
1114
+ for (const target of primitive.listTargets()) shiftUvs(target);
1115
+ }
1116
+ for (const info of listTextureInfoByMaterial(material)) info.setTexCoord(info.getTexCoord() + 1);
1117
+ }
1118
+ for (const primitive of primitives) {
1119
+ const semantic = saved.get(primitive);
1120
+ if (semantic === void 0) continue;
1121
+ primitive.setAttribute("TEXCOORD_0", primitive.getAttribute(semantic));
1122
+ primitive.setAttribute(semantic, null);
1123
+ }
1124
+ }
1125
+ }
1064
1126
  /**
1065
1127
  * Pick the project.json an import registers into. The source file's surrounding project is NOT a
1066
1128
  * safe default: `molen asset import ../otherproj/models/key.glb` used to write the asset into
@@ -1091,6 +1153,23 @@ async function resolveImportProject(input, sourcePath) {
1091
1153
  async function importAsset(input) {
1092
1154
  const warnings = [];
1093
1155
  try {
1156
+ if (input.assetDir !== void 0 && input.outDir !== void 0) return {
1157
+ ok: false,
1158
+ error: "assetDir and outDir are mutually exclusive; choose an exact bundle directory or an assets root"
1159
+ };
1160
+ if (input.assetDir !== void 0 && input.assetDir.trim().length === 0) return {
1161
+ ok: false,
1162
+ error: "assetDir must not be empty"
1163
+ };
1164
+ if (input.assetDir?.includes("\0")) return {
1165
+ ok: false,
1166
+ error: "assetDir must not contain a null byte"
1167
+ };
1168
+ const id = slug$2(input.id ?? basename(input.path, extname(input.path)));
1169
+ if (id.length === 0) return {
1170
+ ok: false,
1171
+ error: "asset id is empty after slugging"
1172
+ };
1094
1173
  const sourcePath = resolve(input.path);
1095
1174
  const resolved = await resolveImportProject(input, sourcePath);
1096
1175
  if (resolved.error !== void 0) return {
@@ -1099,6 +1178,47 @@ async function importAsset(input) {
1099
1178
  };
1100
1179
  const projectPath = resolved.projectPath;
1101
1180
  if (resolved.warning !== void 0) warnings.push(resolved.warning);
1181
+ let registeredAssets = {};
1182
+ if (projectPath !== void 0) {
1183
+ const project = validate("project", parseJson(await readFile(projectPath, "utf8")));
1184
+ if (!project.ok) return {
1185
+ ok: false,
1186
+ error: project.formatted
1187
+ };
1188
+ registeredAssets = project.value.assets;
1189
+ }
1190
+ const registeredSidecar = input.assetDir === void 0 && input.outDir === void 0 ? registeredAssets[id] : void 0;
1191
+ const assetsRoot = input.outDir ?? (projectPath !== void 0 ? join(dirname(projectPath), "assets") : resolve(input.cwd ?? process.cwd(), "assets"));
1192
+ const dir = input.assetDir !== void 0 ? resolve(input.cwd ?? process.cwd(), input.assetDir) : registeredSidecar !== void 0 && projectPath !== void 0 ? dirname(resolve(dirname(projectPath), registeredSidecar)) : join(assetsRoot, id.replaceAll(".", "/"));
1193
+ const sidecarPath = registeredSidecar !== void 0 && projectPath !== void 0 ? resolve(dirname(projectPath), registeredSidecar) : join(dir, "asset.json");
1194
+ if (projectPath !== void 0) {
1195
+ for (const [registeredId, path] of Object.entries(registeredAssets)) if (registeredId !== id && relative(resolve(dir), dirname(resolve(dirname(projectPath), path))) === "") return {
1196
+ ok: false,
1197
+ error: `${dir} belongs to asset "${registeredId}"; refusing to overwrite it with "${id}"`
1198
+ };
1199
+ }
1200
+ try {
1201
+ if (!(await stat(dir)).isDirectory()) return {
1202
+ ok: false,
1203
+ error: `${dir} is not a directory`
1204
+ };
1205
+ if (input.force !== true) return {
1206
+ ok: false,
1207
+ error: `${dir} already exists; choose another id or pass force: true to replace it`
1208
+ };
1209
+ let existing;
1210
+ try {
1211
+ existing = parseJson(await readFile(sidecarPath, "utf8"));
1212
+ } catch (error) {
1213
+ if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
1214
+ }
1215
+ if (existing !== null && typeof existing === "object" && "id" in existing && typeof existing.id === "string" && existing.id !== id) return {
1216
+ ok: false,
1217
+ error: `${dir} belongs to asset "${existing.id}"; refusing to overwrite it with "${id}"`
1218
+ };
1219
+ } catch (error) {
1220
+ if (error.code !== "ENOENT") throw error;
1221
+ }
1102
1222
  const sourceBytes = new Uint8Array(await readFile(sourcePath));
1103
1223
  const io = await createAssetIO();
1104
1224
  let doc;
@@ -1112,7 +1232,13 @@ async function importAsset(input) {
1112
1232
  };
1113
1233
  }
1114
1234
  doc.setLogger(gltfLogger);
1115
- if (input.optimize !== false) await doc.transform(dedup(), prune(), weld(), quantize());
1235
+ const sharedSurfaces = [...new Set(doc.getRoot().listMaterials().map(sharedSurfaceRef).filter((ref) => ref !== void 0))].sort();
1236
+ if (sharedSurfaces.length > 0) warnings.push(`shared surfaces are external runtime dependencies: ${sharedSurfaces.join(", ")}; hosts without these surfaces render the embedded PBR fallback`);
1237
+ if (input.optimize !== false) {
1238
+ await doc.transform(dedup());
1239
+ await prunePreservingSharedSurfaceUvs(doc);
1240
+ await doc.transform(weld(), quantize());
1241
+ }
1116
1242
  const root = doc.getRoot();
1117
1243
  const extensionsUsed = root.listExtensionsUsed().map((e) => e.extensionName);
1118
1244
  const nodeName = (node, i) => {
@@ -1202,21 +1328,6 @@ async function importAsset(input) {
1202
1328
  alphaMode: m.getAlphaMode()
1203
1329
  };
1204
1330
  });
1205
- const id = slug$2(input.id ?? basename(sourcePath, extname(sourcePath)));
1206
- if (id.length === 0) return {
1207
- ok: false,
1208
- error: "asset id is empty after slugging"
1209
- };
1210
- const dir = join(input.outDir ?? (projectPath !== void 0 ? join(dirname(projectPath), "assets") : resolve(input.cwd ?? process.cwd(), "assets")), id.replaceAll(".", "/"));
1211
- try {
1212
- await stat(dir);
1213
- if (input.force !== true) return {
1214
- ok: false,
1215
- error: `${dir} already exists; choose another id or pass force: true to replace it`
1216
- };
1217
- } catch (error) {
1218
- if (error.code !== "ENOENT") throw error;
1219
- }
1220
1331
  await mkdir(dir, { recursive: true });
1221
1332
  const glb = await io.writeBinary(doc);
1222
1333
  await writeFile(join(dir, "model.glb"), glb);
@@ -1279,7 +1390,6 @@ async function importAsset(input) {
1279
1390
  ok: false,
1280
1391
  error: `sidecar failed self-validation:\n${checked.formatted}`
1281
1392
  };
1282
- const sidecarPath = join(dir, "asset.json");
1283
1393
  await writeFile(sidecarPath, `${JSON.stringify(checked.value, null, 2)}\n`);
1284
1394
  try {
1285
1395
  await stat(sidecarPath);
@@ -2090,6 +2200,684 @@ async function stageAssetsImpl(input) {
2090
2200
  };
2091
2201
  }
2092
2202
  //#endregion
2203
+ //#region src/audio-probe.ts
2204
+ function ascii(b, at, len) {
2205
+ return String.fromCharCode(...b.subarray(at, at + len));
2206
+ }
2207
+ function probeWav(b, v) {
2208
+ let at = 12;
2209
+ let byteRate = 0;
2210
+ let sampleRate;
2211
+ let channels;
2212
+ while (at + 8 <= b.length) {
2213
+ const id = ascii(b, at, 4);
2214
+ const size = v.getUint32(at + 4, true);
2215
+ if (id === "fmt ") {
2216
+ channels = v.getUint16(at + 10, true);
2217
+ sampleRate = v.getUint32(at + 12, true);
2218
+ byteRate = v.getUint32(at + 16, true);
2219
+ } else if (id === "data" && byteRate > 0) return {
2220
+ format: "wav",
2221
+ durationS: Math.min(size, b.length - at - 8) / byteRate,
2222
+ ...sampleRate !== void 0 ? { sampleRate } : {},
2223
+ ...channels !== void 0 ? { channels } : {}
2224
+ };
2225
+ at += 8 + size + (size & 1);
2226
+ }
2227
+ return { format: "wav" };
2228
+ }
2229
+ function probeOgg(b, v) {
2230
+ let rate;
2231
+ let channels;
2232
+ let preSkip = 0;
2233
+ let opus = false;
2234
+ const head = ascii(b, 0, Math.min(b.length, 256));
2235
+ const vorbis = head.indexOf("vorbis");
2236
+ const opusHead = head.indexOf("OpusHead");
2237
+ if (vorbis >= 0) {
2238
+ channels = b[vorbis + 11];
2239
+ rate = v.getUint32(vorbis + 12, true);
2240
+ } else if (opusHead >= 0) {
2241
+ opus = true;
2242
+ channels = b[opusHead + 9];
2243
+ preSkip = v.getUint16(opusHead + 10, true);
2244
+ rate = 48e3;
2245
+ }
2246
+ for (let at = b.length - 27; at >= 0; at--) if (b[at] === 79 && ascii(b, at, 4) === "OggS") {
2247
+ const granule = Number(v.getBigUint64(at + 6, true));
2248
+ if (rate && granule > 0) return {
2249
+ format: "ogg",
2250
+ durationS: (granule - (opus ? preSkip : 0)) / rate,
2251
+ sampleRate: opus ? v.getUint32(opusHead + 12, true) || 48e3 : rate,
2252
+ ...channels !== void 0 ? { channels } : {}
2253
+ };
2254
+ break;
2255
+ }
2256
+ return { format: "ogg" };
2257
+ }
2258
+ const MP3_BITRATES_V1 = [
2259
+ 0,
2260
+ 32,
2261
+ 40,
2262
+ 48,
2263
+ 56,
2264
+ 64,
2265
+ 80,
2266
+ 96,
2267
+ 112,
2268
+ 128,
2269
+ 160,
2270
+ 192,
2271
+ 224,
2272
+ 256,
2273
+ 320
2274
+ ];
2275
+ const MP3_BITRATES_V2 = [
2276
+ 0,
2277
+ 8,
2278
+ 16,
2279
+ 24,
2280
+ 32,
2281
+ 40,
2282
+ 48,
2283
+ 56,
2284
+ 64,
2285
+ 80,
2286
+ 96,
2287
+ 112,
2288
+ 128,
2289
+ 144,
2290
+ 160
2291
+ ];
2292
+ const MP3_RATES = {
2293
+ 3: [
2294
+ 44100,
2295
+ 48e3,
2296
+ 32e3
2297
+ ],
2298
+ 2: [
2299
+ 22050,
2300
+ 24e3,
2301
+ 16e3
2302
+ ],
2303
+ 0: [
2304
+ 11025,
2305
+ 12e3,
2306
+ 8e3
2307
+ ]
2308
+ };
2309
+ function probeMp3(b, v) {
2310
+ let at = 0;
2311
+ if (ascii(b, 0, 3) === "ID3") at = 10 + ((b[6] ?? 0) << 21 | (b[7] ?? 0) << 14 | (b[8] ?? 0) << 7 | (b[9] ?? 0));
2312
+ for (; at + 4 < b.length; at++) {
2313
+ if (b[at] !== 255 || ((b[at + 1] ?? 0) & 224) !== 224) continue;
2314
+ const h = v.getUint32(at, false);
2315
+ const version = h >>> 19 & 3;
2316
+ const layer = h >>> 17 & 3;
2317
+ const bitrateIndex = h >>> 12 & 15;
2318
+ const rateIndex = h >>> 10 & 3;
2319
+ if (version === 1 || layer !== 1 || bitrateIndex === 0 || bitrateIndex === 15 || rateIndex === 3) continue;
2320
+ const sampleRate = MP3_RATES[version][rateIndex];
2321
+ const mono = (h >>> 6 & 3) === 3;
2322
+ const v1 = version === 3;
2323
+ const samplesPerFrame = v1 ? 1152 : 576;
2324
+ const sideInfo = v1 ? mono ? 17 : 32 : mono ? 9 : 17;
2325
+ const tag = ascii(b, at + 4 + sideInfo, 4);
2326
+ const channels = mono ? 1 : 2;
2327
+ if (tag === "Xing" || tag === "Info") {
2328
+ if (v.getUint32(at + 8 + sideInfo, false) & 1) return {
2329
+ format: "mp3",
2330
+ durationS: v.getUint32(at + 12 + sideInfo, false) * samplesPerFrame / sampleRate,
2331
+ sampleRate,
2332
+ channels
2333
+ };
2334
+ }
2335
+ const kbps = (v1 ? MP3_BITRATES_V1 : MP3_BITRATES_V2)[bitrateIndex] * 1e3;
2336
+ return {
2337
+ format: "mp3",
2338
+ durationS: (b.length - at) * 8 / kbps,
2339
+ sampleRate,
2340
+ channels
2341
+ };
2342
+ }
2343
+ return { format: "mp3" };
2344
+ }
2345
+ /** Probe a clip's header for duration, sample rate and channel count. */
2346
+ function probeAudio(bytes) {
2347
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2348
+ if (bytes.length >= 12 && ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WAVE") return probeWav(bytes, v);
2349
+ if (bytes.length >= 27 && ascii(bytes, 0, 4) === "OggS") return probeOgg(bytes, v);
2350
+ if (bytes.length >= 4 && (ascii(bytes, 0, 3) === "ID3" || bytes[0] === 255 && ((bytes[1] ?? 0) & 224) === 224)) return probeMp3(bytes, v);
2351
+ return { format: "unknown" };
2352
+ }
2353
+ //#endregion
2354
+ //#region src/ops/audio-check.ts
2355
+ const fail$3 = (error) => ({
2356
+ ok: false,
2357
+ sounds: 0,
2358
+ clips: 0,
2359
+ bytes: 0,
2360
+ licenses: {},
2361
+ issues: [],
2362
+ error
2363
+ });
2364
+ /** Validate a sound bank and every clip it names: present, hash, duration, loop points. */
2365
+ function checkSoundbank(input) {
2366
+ return guardOp(fail$3, () => checkSoundbankImpl(input));
2367
+ }
2368
+ async function checkSoundbankImpl(input) {
2369
+ const bankPath = resolve(input.bankPath);
2370
+ const v = validate("soundbank", parseJson(await readFile(bankPath, "utf8")));
2371
+ if (!v.ok) return fail$3(v.formatted);
2372
+ const bank = v.value;
2373
+ const dir = dirname(bankPath);
2374
+ const issues = [];
2375
+ const licenses = {};
2376
+ let clips = 0;
2377
+ let bytes = 0;
2378
+ for (const [id, entry] of Object.entries(bank.sounds)) {
2379
+ const at = `/sounds/${id}`;
2380
+ licenses[entry.source.license] = (licenses[entry.source.license] ?? 0) + 1;
2381
+ if (!entry.description) issues.push({
2382
+ path: at,
2383
+ message: "no description (agents choose sounds by it)",
2384
+ severity: "notice"
2385
+ });
2386
+ if (!entry.source.url && !entry.source.prompt && !entry.source.site) issues.push({
2387
+ path: `${at}/source`,
2388
+ message: "no origin: add url, site or prompt",
2389
+ severity: "notice"
2390
+ });
2391
+ for (const [i, clip] of entry.clips.entries()) {
2392
+ let data;
2393
+ try {
2394
+ data = new Uint8Array(await readFile(join(dir, clip)));
2395
+ } catch {
2396
+ issues.push({
2397
+ path: `${at}/clips/${i}`,
2398
+ message: `missing file ${clip}`,
2399
+ severity: "error"
2400
+ });
2401
+ continue;
2402
+ }
2403
+ clips++;
2404
+ bytes += data.length;
2405
+ if (i === 0 && entry.hash) {
2406
+ if (`sha256:${createHash("sha256").update(data).digest("hex")}` !== entry.hash) issues.push({
2407
+ path: `${at}/hash`,
2408
+ message: `${clip} changed since import`,
2409
+ severity: "error"
2410
+ });
2411
+ }
2412
+ const probe = probeAudio(data);
2413
+ if (i === 0 && entry.durationS !== void 0 && probe.durationS !== void 0) {
2414
+ if (Math.abs(probe.durationS - entry.durationS) > .1) issues.push({
2415
+ path: `${at}/durationS`,
2416
+ message: `durationS ${entry.durationS} but ${clip} is ${probe.durationS.toFixed(3)}s`,
2417
+ severity: "error"
2418
+ });
2419
+ }
2420
+ if (entry.loopEnd !== void 0 && probe.durationS !== void 0 && entry.loopEnd > probe.durationS + .01) issues.push({
2421
+ path: `${at}/loopEnd`,
2422
+ message: `loopEnd ${entry.loopEnd} is past the end of ${clip} (${probe.durationS.toFixed(3)}s)`,
2423
+ severity: "error"
2424
+ });
2425
+ }
2426
+ }
2427
+ return {
2428
+ ok: !issues.some((i) => i.severity === "error"),
2429
+ id: bank.id,
2430
+ sounds: Object.keys(bank.sounds).length,
2431
+ clips,
2432
+ bytes,
2433
+ licenses,
2434
+ issues
2435
+ };
2436
+ }
2437
+ //#endregion
2438
+ //#region src/ops/audio-import.ts
2439
+ const fail$2 = (error) => ({
2440
+ ok: false,
2441
+ bankPath: "",
2442
+ warnings: [],
2443
+ error
2444
+ });
2445
+ /** Add a clip to a sound bank: copy it beside the bank, hash and probe it, record provenance. */
2446
+ function importSound(input) {
2447
+ return guardOp(fail$2, () => importSoundImpl(input));
2448
+ }
2449
+ async function importSoundImpl(input) {
2450
+ const warnings = [];
2451
+ const bankPath = resolve(input.bankPath);
2452
+ const bankDir = dirname(bankPath);
2453
+ let bank;
2454
+ try {
2455
+ bank = parseJson(await readFile(bankPath, "utf8"));
2456
+ } catch (e) {
2457
+ if (e.code !== "ENOENT") throw e;
2458
+ bank = {
2459
+ format: "molen/soundbank@1",
2460
+ id: basename(bankDir),
2461
+ sounds: {}
2462
+ };
2463
+ warnings.push(`created ${bankPath}`);
2464
+ }
2465
+ const src = resolve(input.file);
2466
+ const bytes = new Uint8Array(await readFile(src));
2467
+ const inside = !relative(bankDir, src).startsWith("..") && !isAbsolute(relative(bankDir, src));
2468
+ let clip;
2469
+ if (inside) clip = relative(bankDir, src).split(sep).join("/");
2470
+ else {
2471
+ const dir = input.copyTo ?? "audio";
2472
+ clip = `${dir}/${basename(src)}`;
2473
+ await mkdir(join(bankDir, dir), { recursive: true });
2474
+ await copyFile(src, join(bankDir, clip));
2475
+ }
2476
+ const probe = probeAudio(bytes);
2477
+ if (probe.format === "unknown") warnings.push(`${basename(src)}: unrecognized audio format`);
2478
+ if (probe.format !== "mp3" && probe.format !== "unknown") warnings.push(`${basename(src)} is ${probe.format}; MP3 is the one format every browser decodes`);
2479
+ const durationS = input.durationS ?? probe.durationS;
2480
+ const hash = `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
2481
+ const previous = bank.sounds[input.id];
2482
+ const source = {
2483
+ license: input.license,
2484
+ ...input.site !== void 0 ? { site: input.site } : {},
2485
+ ...input.source !== void 0 ? { url: input.source } : {},
2486
+ ...input.author !== void 0 ? { author: input.author } : {},
2487
+ ...input.prompt !== void 0 ? { prompt: input.prompt } : {},
2488
+ ...input.generator !== void 0 ? { generator: input.generator } : {}
2489
+ };
2490
+ let entry;
2491
+ if (input.append && previous) {
2492
+ if (previous.clips.includes(clip)) return {
2493
+ ...fail$2(`${clip} is already a clip of ${input.id}`),
2494
+ bankPath
2495
+ };
2496
+ entry = {
2497
+ ...previous,
2498
+ clips: [...previous.clips, clip]
2499
+ };
2500
+ } else {
2501
+ entry = {
2502
+ clips: [clip],
2503
+ ...input.description !== void 0 ? { description: input.description } : {},
2504
+ ...input.loop !== void 0 ? { loop: input.loop } : {},
2505
+ ...input.loopStart !== void 0 ? { loopStart: input.loopStart } : {},
2506
+ ...input.loopEnd !== void 0 ? { loopEnd: input.loopEnd } : {},
2507
+ ...input.gain !== void 0 ? { gain: input.gain } : {},
2508
+ ...input.bus !== void 0 ? { bus: input.bus } : {},
2509
+ ...durationS !== void 0 ? { durationS: Math.round(durationS * 1e3) / 1e3 } : {},
2510
+ hash,
2511
+ source
2512
+ };
2513
+ if (previous) warnings.push(`replaced existing sound ${input.id}`);
2514
+ }
2515
+ if (durationS === void 0) warnings.push("duration unknown; pass --duration for music tracks");
2516
+ const next = {
2517
+ ...bank,
2518
+ sounds: {
2519
+ ...bank.sounds,
2520
+ [input.id]: entry
2521
+ }
2522
+ };
2523
+ const checked = validate("soundbank", next);
2524
+ if (!checked.ok) return {
2525
+ ...fail$2(checked.formatted),
2526
+ bankPath
2527
+ };
2528
+ await writeFile(bankPath, `${JSON.stringify(next, null, 2)}\n`);
2529
+ return {
2530
+ ok: true,
2531
+ bankPath,
2532
+ id: input.id,
2533
+ clip,
2534
+ entry,
2535
+ warnings
2536
+ };
2537
+ }
2538
+ //#endregion
2539
+ //#region src/ops/audio-plan.ts
2540
+ const fail$1 = (error) => ({
2541
+ ok: false,
2542
+ ticks: 0,
2543
+ tickRate: 0,
2544
+ banks: [],
2545
+ voices: [],
2546
+ oneShots: [],
2547
+ events: [],
2548
+ issues: [],
2549
+ warnings: [],
2550
+ timeline: "",
2551
+ error
2552
+ });
2553
+ /** Run a scene headlessly and report the sounds it would play, tick by tick. */
2554
+ function planAudio(input) {
2555
+ return guardOp(fail$1, () => planAudioImpl(input));
2556
+ }
2557
+ function vec(v) {
2558
+ return Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === "number") ? v : void 0;
2559
+ }
2560
+ function towards(from, to) {
2561
+ if (!to) return [
2562
+ 0,
2563
+ 0,
2564
+ -1
2565
+ ];
2566
+ const d = [
2567
+ to[0] - from[0],
2568
+ to[1] - from[1],
2569
+ to[2] - from[2]
2570
+ ];
2571
+ const len = Math.hypot(...d);
2572
+ return len > 1e-9 ? [
2573
+ d[0] / len,
2574
+ d[1] / len,
2575
+ d[2] / len
2576
+ ] : [
2577
+ 0,
2578
+ 0,
2579
+ -1
2580
+ ];
2581
+ }
2582
+ function transformOf(world, id) {
2583
+ const t = world.get(id, { name: "transform" });
2584
+ return {
2585
+ ...vec(t?.pos) ? { pos: vec(t?.pos) } : {},
2586
+ ...Array.isArray(t?.rot) ? { rot: t?.rot } : {}
2587
+ };
2588
+ }
2589
+ /** Where the ears are for a headless run: a named entity, else the scene camera. */
2590
+ function listenerFor(world, manifest, entity) {
2591
+ if (entity !== void 0) {
2592
+ const { pos, rot } = transformOf(world, entity);
2593
+ if (!pos) return {};
2594
+ return {
2595
+ position: pos,
2596
+ forward: rot ? quatRotateVec3(rot, [
2597
+ 0,
2598
+ 0,
2599
+ -1
2600
+ ]) : [
2601
+ 0,
2602
+ 0,
2603
+ -1
2604
+ ],
2605
+ up: [
2606
+ 0,
2607
+ 1,
2608
+ 0
2609
+ ]
2610
+ };
2611
+ }
2612
+ const c = manifest.camera;
2613
+ if (!c) return { position: [
2614
+ 0,
2615
+ 0,
2616
+ 0
2617
+ ] };
2618
+ if (c.mode === "top-down-ortho") return {
2619
+ position: [
2620
+ c.center[0],
2621
+ c.cameraHeight ?? 50,
2622
+ c.center[1]
2623
+ ],
2624
+ forward: [
2625
+ 0,
2626
+ -1,
2627
+ 0
2628
+ ],
2629
+ up: [
2630
+ 0,
2631
+ 0,
2632
+ -1
2633
+ ]
2634
+ };
2635
+ if (c.mode === "follow") {
2636
+ const { pos } = transformOf(world, c.entity);
2637
+ if (!pos) return {};
2638
+ const eye = [
2639
+ pos[0] + c.offset[0],
2640
+ pos[1] + c.offset[1],
2641
+ pos[2] + c.offset[2]
2642
+ ];
2643
+ return {
2644
+ position: eye,
2645
+ forward: towards(eye, [
2646
+ pos[0] + c.lookOffset[0],
2647
+ pos[1] + c.lookOffset[1],
2648
+ pos[2] + c.lookOffset[2]
2649
+ ]),
2650
+ up: [
2651
+ 0,
2652
+ 1,
2653
+ 0
2654
+ ]
2655
+ };
2656
+ }
2657
+ return {
2658
+ position: c.position,
2659
+ forward: towards(c.position, c.lookAt),
2660
+ up: [
2661
+ 0,
2662
+ 1,
2663
+ 0
2664
+ ]
2665
+ };
2666
+ }
2667
+ async function loadBanks(paths, project) {
2668
+ const inputs = [];
2669
+ const labels = [];
2670
+ if (paths && paths.length > 0) {
2671
+ for (const path of paths) {
2672
+ const v = validate("soundbank", parseJson(await readFile(path, "utf8")));
2673
+ if (!v.ok) return `${path}:\n${v.formatted}`;
2674
+ inputs.push({
2675
+ doc: v.value,
2676
+ base: relative(process.cwd(), dirname(resolve(path)))
2677
+ });
2678
+ labels.push(path);
2679
+ }
2680
+ return {
2681
+ inputs,
2682
+ labels
2683
+ };
2684
+ }
2685
+ const set = project?.packs ?? await openProjectPacks(void 0);
2686
+ for (const { pack, path } of set.provided("soundbank")) {
2687
+ const v = validate("soundbank", await pack.readJson(path));
2688
+ if (!v.ok) return `${pack.manifest.id}/${path}:\n${v.formatted}`;
2689
+ const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";
2690
+ inputs.push({
2691
+ doc: v.value,
2692
+ base: `pack:${pack.manifest.id}/${dir}`
2693
+ });
2694
+ labels.push(`${pack.manifest.id}@${pack.manifest.version}:${path}`);
2695
+ }
2696
+ if (inputs.length === 0) return "no sound bank: pass --bank <file>, add a pack providing \"soundbank\" to project.json, or set MOLEN_PACKS";
2697
+ return {
2698
+ inputs,
2699
+ labels
2700
+ };
2701
+ }
2702
+ async function planAudioImpl(input) {
2703
+ let manifest;
2704
+ let types;
2705
+ let project;
2706
+ let buildOpts = {};
2707
+ if (input.scene !== void 0) {
2708
+ const v = validate("scene", input.scene);
2709
+ if (!v.ok) return fail$1(v.formatted);
2710
+ manifest = v.value;
2711
+ } else {
2712
+ if (input.scenePath === void 0) return fail$1("planAudio: provide scenePath or scene");
2713
+ const loaded = await loadSceneDocument(input.scenePath, { ...input.projectPath !== void 0 ? { projectPath: input.projectPath } : {} });
2714
+ manifest = loaded.manifest;
2715
+ types = loaded.project?.resolvedTypes;
2716
+ project = loaded.project;
2717
+ buildOpts = await sceneBuildOptionsFor(loaded);
2718
+ }
2719
+ let commands = input.commands ?? [];
2720
+ if (input.commandsPath !== void 0) {
2721
+ const raw = parseJson(await readFile(input.commandsPath, "utf8"));
2722
+ const list = Array.isArray(raw) ? raw : raw.commands;
2723
+ if (!Array.isArray(list)) return fail$1(`${input.commandsPath}: expected an array of commands`);
2724
+ commands = [];
2725
+ for (const [i, c] of list.entries()) {
2726
+ const v = validate("command", c);
2727
+ if (!v.ok) return fail$1(`command[${i}] invalid:\n${v.formatted}`);
2728
+ commands.push(v.value);
2729
+ }
2730
+ }
2731
+ let setup;
2732
+ const setupModule = resolveSetupModule(input.setupModule, project);
2733
+ if (setupModule !== void 0) setup = await loadSetupLike(setupModule);
2734
+ const banks = await loadBanks(input.bankPaths, project);
2735
+ if (typeof banks === "string") return fail$1(banks);
2736
+ const bank = mergeSoundbanks(banks.inputs);
2737
+ const warnings = [];
2738
+ const director = new AudioDirector({
2739
+ bank,
2740
+ onWarning: (m) => warnings.push(m)
2741
+ });
2742
+ const build = await prepareSceneBuilder(manifest, setup, {
2743
+ ...buildOpts,
2744
+ ...types !== void 0 ? { types } : {}
2745
+ });
2746
+ let weather = void 0;
2747
+ if (input.weather !== void 0) try {
2748
+ weather = weatherProfile(input.weather);
2749
+ } catch {
2750
+ return fail$1(`unknown weather profile "${input.weather}" (sunny, partly-cloudy, overcast, rain, snow, fog)`);
2751
+ }
2752
+ const issues = [];
2753
+ const voices = /* @__PURE__ */ new Map();
2754
+ const done = [];
2755
+ const oneShots = [];
2756
+ const events = [];
2757
+ let tickRate = 30;
2758
+ let detach;
2759
+ let lastTick = 0;
2760
+ const record = (cmds, tick) => {
2761
+ for (const cmd of cmds) if (cmd.op === "start") if (cmd.loop || cmd.voice.startsWith("music:")) {
2762
+ const entity = cmd.voice.startsWith("src:") ? cmd.voice.slice(4, cmd.voice.lastIndexOf("~")) : void 0;
2763
+ voices.set(cmd.voice, {
2764
+ voice: cmd.voice,
2765
+ sound: cmd.sound,
2766
+ bus: cmd.bus,
2767
+ startTick: tick,
2768
+ peakGain: cmd.gain,
2769
+ pitch: [cmd.pitch, cmd.pitch],
2770
+ ...entity !== void 0 ? { entity } : {}
2771
+ });
2772
+ } else oneShots.push({
2773
+ tick,
2774
+ sound: cmd.sound,
2775
+ bus: cmd.bus,
2776
+ ...cmd.spatial ? { position: cmd.spatial.position } : {}
2777
+ });
2778
+ else if (cmd.op === "set") {
2779
+ const v = voices.get(cmd.voice);
2780
+ if (v && cmd.gain !== void 0) v.peakGain = Math.max(v.peakGain, cmd.gain);
2781
+ if (v && cmd.pitch !== void 0) v.pitch = [Math.min(v.pitch[0], cmd.pitch), Math.max(v.pitch[1], cmd.pitch)];
2782
+ } else if (cmd.op === "stop") {
2783
+ const v = voices.get(cmd.voice);
2784
+ if (v) {
2785
+ voices.delete(cmd.voice);
2786
+ done.push({
2787
+ ...v,
2788
+ stopTick: tick
2789
+ });
2790
+ }
2791
+ }
2792
+ };
2793
+ const staticCheck = (world) => {
2794
+ const source = entitySourceFromWorld(world);
2795
+ for (const component of [
2796
+ "audioSource",
2797
+ "audioZone",
2798
+ "audioEnvironment"
2799
+ ]) for (const [id, data] of source.each(component)) {
2800
+ for (const ref of audioSoundRefs(component, data)) {
2801
+ if (bank.resolve(ref.sound)) continue;
2802
+ const near = nearestWithDistance(ref.sound, [...bank.ids()]);
2803
+ issues.push({
2804
+ path: `/entities/${id}/components/${component}${ref.path}`,
2805
+ message: `unknown sound "${ref.sound}"${near ? `; did you mean "${near.candidate}"?` : ""}`
2806
+ });
2807
+ }
2808
+ for (const ref of audioSignalRefs(component, data)) for (const issue of audioSignalIssues(ref.signal)) issues.push({
2809
+ path: `/entities/${id}/components/${component}${ref.path}`,
2810
+ message: `${issue.message}${issue.hint ? `; ${issue.hint}` : ""}`
2811
+ });
2812
+ }
2813
+ };
2814
+ runHeadless(build, {
2815
+ commands,
2816
+ ticks: input.ticks,
2817
+ onTick(world) {
2818
+ if (!detach) {
2819
+ tickRate = world.tickRate;
2820
+ const source = entitySourceFromWorld(world);
2821
+ director.setBank(bank);
2822
+ detach = source.onEvent?.((event, tick) => {
2823
+ director.handleEvent(event, tick);
2824
+ if (event.type.startsWith("audio.")) events.push({
2825
+ tick,
2826
+ type: event.type,
2827
+ payload: event.payload
2828
+ });
2829
+ });
2830
+ staticCheck(world);
2831
+ }
2832
+ lastTick = world.tick;
2833
+ const listener = listenerFor(world, manifest, input.listener);
2834
+ record(director.update({
2835
+ nowMs: world.tick * 1e3 / world.tickRate,
2836
+ listener: {
2837
+ ...listener,
2838
+ ...input.mode !== void 0 ? { mode: input.mode } : {}
2839
+ },
2840
+ source: entitySourceFromWorld(world),
2841
+ signals: {
2842
+ ...weather ? { weather } : {},
2843
+ ...input.daylight !== void 0 ? { sky: { daylight: input.daylight } } : {}
2844
+ }
2845
+ }), world.tick);
2846
+ }
2847
+ });
2848
+ detach?.();
2849
+ const all = [...done, ...voices.values()].sort((a, b) => a.startTick - b.startTick);
2850
+ const lines = [];
2851
+ lines.push(`${input.ticks} ticks at ${tickRate} Hz, banks: ${banks.labels.join(", ")}`);
2852
+ lines.push(all.length > 0 ? "loops:" : "loops: none");
2853
+ for (const v of all) {
2854
+ const span = `[${v.startTick} → ${v.stopTick ?? "end"}]`.padEnd(14);
2855
+ const at = v.entity !== void 0 ? ` @${v.entity}` : "";
2856
+ const pitch = v.pitch[0] === v.pitch[1] ? v.pitch[0].toFixed(2) : `${v.pitch[0].toFixed(2)}–${v.pitch[1].toFixed(2)}`;
2857
+ lines.push(` ${span} ${v.sound}${at} bus ${v.bus} peak ${v.peakGain.toFixed(2)} pitch ${pitch}`);
2858
+ }
2859
+ lines.push(oneShots.length > 0 ? `one-shots (${oneShots.length}):` : "one-shots: none");
2860
+ for (const s of oneShots.slice(0, 200)) {
2861
+ const at = s.position ? ` at [${s.position.map((x) => Math.round(x * 10) / 10).join(", ")}]` : "";
2862
+ lines.push(` t=${String(s.tick).padEnd(6)} ${s.sound}${at} (${s.bus})`);
2863
+ }
2864
+ if (oneShots.length > 200) lines.push(` … ${oneShots.length - 200} more`);
2865
+ for (const i of issues) lines.push(`✗ ${i.path}: ${i.message}`);
2866
+ for (const w of warnings) lines.push(`! ${w}`);
2867
+ return {
2868
+ ok: issues.length === 0 && !warnings.some((w) => w.startsWith("unknown sound")),
2869
+ ticks: lastTick,
2870
+ tickRate,
2871
+ banks: banks.labels,
2872
+ voices: all,
2873
+ oneShots,
2874
+ events,
2875
+ issues,
2876
+ warnings,
2877
+ timeline: lines.join("\n")
2878
+ };
2879
+ }
2880
+ //#endregion
2093
2881
  //#region src/ops/camera.ts
2094
2882
  /**
2095
2883
  * The camera a capture uses: an explicit override wins; otherwise the scene's own `camera`
@@ -2132,6 +2920,14 @@ function literal(value) {
2132
2920
  if (typeof value !== "string") return String(value);
2133
2921
  return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
2134
2922
  }
2923
+ /** True when a node prints as a top-level `a | b` union. */
2924
+ function isUnion(node) {
2925
+ if (node === void 0 || node.const !== void 0) return false;
2926
+ if (node.enum !== void 0) return node.enum.length > 1;
2927
+ const union = node.anyOf ?? node.oneOf;
2928
+ if (union !== void 0) return union.length > 1;
2929
+ return Array.isArray(node.type) && node.type.length > 1;
2930
+ }
2135
2931
  /** Print a JSON Schema node as a TS type expression. Unknown constructs degrade to `unknown`. */
2136
2932
  function schemaToTsType(schema, indent = "") {
2137
2933
  const node = schema;
@@ -2155,7 +2951,7 @@ function schemaToTsType(schema, indent = "") {
2155
2951
  if (node.prefixItems !== void 0) return `[${node.prefixItems.map((p) => schemaToTsType(p, indent)).join(", ")}]`;
2156
2952
  const item = node.items !== void 0 ? schemaToTsType(node.items, indent) : "unknown";
2157
2953
  if (node.minItems !== void 0 && node.minItems === node.maxItems && node.minItems > 0 && node.minItems <= 8) return `[${Array.from({ length: node.minItems }, () => item).join(", ")}]`;
2158
- return `${item}[]`;
2954
+ return isUnion(node.items) ? `(${item})[]` : `${item}[]`;
2159
2955
  }
2160
2956
  case "object": {
2161
2957
  const props = node.properties ?? {};
@@ -2421,6 +3217,29 @@ function renderScriptTypes(input) {
2421
3217
  "",
2422
3218
  ...renderMath(),
2423
3219
  "",
3220
+ "/** Options for `molen.audio.play`. Omit entity and position for a non-positional sound. */",
3221
+ "interface MolenAudioPlayOptions {",
3222
+ " /** Play at (and follow) this entity's transform. */",
3223
+ " entity?: MolenEntityId;",
3224
+ " /** Play at a fixed world position. */",
3225
+ " position?: MolenVec3;",
3226
+ " gain?: number;",
3227
+ " pitch?: number;",
3228
+ " bus?: string;",
3229
+ " /** Loop until stopped; default the sound's own loop flag. */",
3230
+ " loop?: boolean;",
3231
+ "}",
3232
+ "",
3233
+ "/** `molen.audio`: each call emits an `audio.*` event the client plays (guide/audio.md). */",
3234
+ "interface MolenAudioApi {",
3235
+ " /** Play a sound-bank id; returns a handle for `stop`. */",
3236
+ " play(sound: string, opts?: MolenAudioPlayOptions): string;",
3237
+ " /** Stop by handle, or every voice matching an entity and/or sound. */",
3238
+ " stop(target: string | { entity?: MolenEntityId; sound?: string }, fadeS?: number): void;",
3239
+ " /** Switch background music to a track or playlist; null stops it. */",
3240
+ " music(playlist: string | string[] | null, opts?: { crossfadeS?: number }): void;",
3241
+ "}",
3242
+ "",
2424
3243
  "/** The verb set injected into every scene-data script as `molen`. */",
2425
3244
  "interface MolenApi {",
2426
3245
  " /** Spawn from a component map. */",
@@ -2477,6 +3296,8 @@ function renderScriptTypes(input) {
2477
3296
  " handler: (payload: MolenCommands[T], ctx: MolenTickContext, command: MolenCommand) => void,",
2478
3297
  " ): MolenUnsubscribe;",
2479
3298
  " emit(type: string, payload?: MolenJsonValue): void;",
3299
+ " /** Sound: play/stop one-shots and loops, switch music. Never affects the simulation. */",
3300
+ " readonly audio: MolenAudioApi;",
2480
3301
  " raycast(origin: MolenVec3, dir: MolenVec3, maxDist: number, mask?: number): MolenRayHit | null;",
2481
3302
  " overlapCircle(center: MolenVec3, radius: number, mask?: number): string[];",
2482
3303
  " /** Emit `event` after `ticks` ticks (snapshot-safe world timer). Returns the timer id. */",
@@ -2684,7 +3505,7 @@ async function loadTypeScript(projectDir) {
2684
3505
  */
2685
3506
  function typescriptNotFoundError(projectDir) {
2686
3507
  return [
2687
- "typescript not found — molen scripts check compiles with the project's own TypeScript",
3508
+ "typescript not found — molen scripts check compiles with the project's own TypeScript",
2688
3509
  ` install it in ${projectDir}:`,
2689
3510
  " npm install # the scaffold lists typescript as a devDependency",
2690
3511
  " or add it directly:",
@@ -2723,7 +3544,7 @@ function diagnosticsFor(ts, target, projectDir) {
2723
3544
  }
2724
3545
  const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
2725
3546
  out.push({
2726
- file: relative(projectDir, d.file.fileName),
3547
+ file: relative(projectDir, d.file.fileName).replaceAll("\\", "/"),
2727
3548
  line: line + 1,
2728
3549
  column: character + 1,
2729
3550
  code: `TS${d.code}`,
@@ -2758,7 +3579,7 @@ async function checkScripts(input) {
2758
3579
  ok: false,
2759
3580
  stale,
2760
3581
  ungenerated,
2761
- error: `script declarations are ${stale.length > 0 ? "stale" : "missing"} — run: molen types gen`
3582
+ error: `script declarations are ${stale.length > 0 ? "stale" : "missing"} — run: molen types gen`
2762
3583
  };
2763
3584
  const ts = await loadTypeScript(project.dir);
2764
3585
  if (ts === void 0) return {
@@ -3090,7 +3911,7 @@ const OPS_CATALOG = [
3090
3911
  },
3091
3912
  {
3092
3913
  name: "fetch_pack",
3093
- summary: "Download content packs (a pack URL, or a molen/pack-index@1 URL) into the project and pin them in project.json `packs` with their contentHash, so the project runs offline.",
3914
+ summary: "Download content packs (a pack URL, or a molen/pack-index@1 URL) into the project, list them in index.json in the download directory (so a page can open them), and pin them in project.json `packs` with their contentHash, so the project runs offline.",
3094
3915
  cli: "molen pack fetch <url> [ids…] [--out-dir <d>] [--project <path>]",
3095
3916
  mcpTool: "fetch_pack",
3096
3917
  params: [
@@ -3101,6 +3922,57 @@ const OPS_CATALOG = [
3101
3922
  cwdParam()
3102
3923
  ]
3103
3924
  },
3925
+ {
3926
+ name: "plan_audio",
3927
+ summary: "Run a scene headlessly and list the sounds it would play: looping voices with start/stop ticks, peak gain and pitch range, one-shots by tick, audio.* script events, and unknown sound ids or signals. Hear a scene's audio annotations without a browser.",
3928
+ cli: "molen audio plan <scene|name> --ticks <N> [--bank <bank.json,…>] [--commands <f>] [--setup <m>] [--listener <entity>] [--mode <walk|drive|fly>] [--weather <profile>] [--daylight <0..1>] [--project <project.json>] [--json]",
3929
+ mcpTool: "plan_audio",
3930
+ params: [
3931
+ p("scenePath", "string", true, "Scene file path or project scene name."),
3932
+ p("ticks", "int>0", true, "Ticks to simulate."),
3933
+ p("bankPaths", "string[]", false, "molen/soundbank@1 files (default: every provides.soundbank in the project's packs)."),
3934
+ p("commandsPath", "string", false, "JSON array (or {commands:[...]}) of command envelopes."),
3935
+ p("setupModule", "string", false, "ESM module exporting setup(world, manifest)."),
3936
+ p("listener", "string", false, "Entity whose transform is the listener (default: the scene camera)."),
3937
+ p("mode", "string", false, "listener.mode for rules: walk, drive, fly…"),
3938
+ p("weather", "string", false, "Weather profile: sunny, partly-cloudy, overcast, rain, snow, fog."),
3939
+ p("daylight", "number", false, "sky.daylight 0 (night) – 1 (day); default 1."),
3940
+ projectPathParam()
3941
+ ]
3942
+ },
3943
+ {
3944
+ name: "import_sound",
3945
+ summary: "Add an audio clip to a molen/soundbank@1 file: copy it beside the bank, hash it, probe its duration, and record license and provenance. --append adds a variation to an existing sound.",
3946
+ cli: "molen audio import <file> --id <sound.id> --bank <bank.json> --license <spdx> [--source <url>] [--site s] [--author a] [--prompt p] [--generator g] [--description d] [--loop] [--loop-start s] [--loop-end s] [--bus b] [--gain g] [--duration s] [--append] [--copy-to <dir>]",
3947
+ mcpTool: "import_sound",
3948
+ params: [
3949
+ p("file", "string", true, "Audio file (MP3 recommended; WAV and Ogg accepted)."),
3950
+ p("id", "string", true, "Sound id, e.g. \"ambience.rain.medium\"."),
3951
+ p("bankPath", "string", true, "Sound bank JSON to update (created when missing)."),
3952
+ p("license", "string", true, "SPDX license of the recording, e.g. \"CC0-1.0\"."),
3953
+ p("source", "string", false, "Page of the original recording."),
3954
+ p("site", "string", false, "Origin site: freesound, kenney, opengameart, …"),
3955
+ p("author", "string", false, "Recordist or creator."),
3956
+ p("prompt", "string", false, "Generation prompt, for generated clips."),
3957
+ p("generator", "string", false, "Generator/model name, for generated clips."),
3958
+ p("description", "string", false, "What it sounds like (agents choose sounds by it)."),
3959
+ p("loop", "boolean", false, "Loop the clip (ambience, engines)."),
3960
+ p("loopStart", "number", false, "Loop start in seconds."),
3961
+ p("loopEnd", "number", false, "Loop end in seconds."),
3962
+ p("bus", "string", false, "Default bus: music, ambience, sfx, ui, voice."),
3963
+ p("gain", "number", false, "Base gain (default 1)."),
3964
+ p("durationS", "number", false, "Duration in seconds; overrides the probed value."),
3965
+ p("append", "boolean", false, "Add as another variation of an existing sound."),
3966
+ p("copyTo", "string", false, "Directory under the bank for copied files (default audio).")
3967
+ ]
3968
+ },
3969
+ {
3970
+ name: "check_soundbank",
3971
+ summary: "Check a molen/soundbank@1 file and every clip it names: files present, hashes unchanged, durations and loop points consistent, provenance recorded; prints a license summary.",
3972
+ cli: "molen audio check <bank.json>",
3973
+ mcpTool: "check_soundbank",
3974
+ params: [p("bankPath", "string", true, "Sound bank JSON.")]
3975
+ },
3104
3976
  {
3105
3977
  name: "test_types",
3106
3978
  summary: "Smoke-test every registry type standalone: resolved shape validates, spawns, and survives N simulated ticks.",
@@ -3129,14 +4001,15 @@ const OPS_CATALOG = [
3129
4001
  {
3130
4002
  name: "import_asset",
3131
4003
  summary: "Import a glTF/GLB: normalize, extract bounds + collision (hulls/trimesh), write the asset sidecar, register in project.json.",
3132
- cli: "molen asset import <file.glb> [--id <asset-id>] [--trimesh] [--no-optimize] [--out-dir <d>] [--project <project.json>] [--force]",
4004
+ cli: "molen asset import <file.glb> [--id <asset-id>] [--trimesh] [--no-optimize] [--out-dir <d>] [--asset-dir <d>] [--project <project.json>] [--force]",
3133
4005
  mcpTool: "import_asset",
3134
4006
  params: [
3135
4007
  p("path", "string", true, "Source .glb/.gltf file."),
3136
4008
  p("id", "string", false, "Asset id (default: slugged filename; dotted ids join a namespace)."),
3137
4009
  p("trimesh", "boolean", false, "Also extract a whole-asset collision trimesh (collision.bin)."),
3138
4010
  p("optimize", "boolean", false, "Normalize pass dedup/prune/weld/quantize (default true)."),
3139
- p("outDir", "string", false, "Assets root override (default: <project dir>/assets)."),
4011
+ p("outDir", "string", false, "Assets root override; retains root/id layout. Mutually exclusive with assetDir."),
4012
+ p("assetDir", "string", false, "Exact bundle directory, relative to cwd. Mutually exclusive with outDir. Omit both to preserve an existing project asset directory."),
3140
4013
  p("projectPath", "string", false, "project.json to register into. Required when the source file sits in a different project than the cwd."),
3141
4014
  cwdParam(),
3142
4015
  p("force", "boolean", false, "Replace an existing asset directory (default false).")
@@ -4433,6 +5306,15 @@ async function fetchContentPack(input) {
4433
5306
  size: bytes.length
4434
5307
  });
4435
5308
  }
5309
+ for (const pack of fetched) {
5310
+ const { file, version, contentHash, size } = pack;
5311
+ await recordInPackIndex(outDir, pack.id, {
5312
+ file,
5313
+ version,
5314
+ contentHash,
5315
+ size
5316
+ });
5317
+ }
4436
5318
  if (projectPath !== void 0) await updateProjectFile(projectPath, (manifest) => {
4437
5319
  for (const pack of fetched) {
4438
5320
  const file = relative(dirname(projectPath), join(outDir, pack.file));
@@ -7213,6 +8095,10 @@ join("capture", "worldgen-preview.html");
7213
8095
  */
7214
8096
  /** Local archive path of a package source; remote archives are not read by this Node op. */
7215
8097
  function archivePath(source) {
8098
+ if (source.kind === "pmtiles-set") {
8099
+ const location = "path" in source ? source.path : source.url;
8100
+ throw new Error(`archive set ${location} is not supported; worldgen stats reads single local PMTiles archives`);
8101
+ }
7216
8102
  if ("path" in source) return source.path;
7217
8103
  throw new Error(`archive ${source.url} is remote; worldgen stats reads local packages only`);
7218
8104
  }
@@ -7477,4 +8363,4 @@ function formatWorldgenStats(result) {
7477
8363
  registerCameraTrackSchema();
7478
8364
  registerExperiencePlaySchema();
7479
8365
  //#endregion
7480
- export { assetFileIndex as $, inspectContentPack as A, OPS_CATALOG as B, checkTypesOp as C, buildContentPack as D, reserveNamespace as E, listFigurePresets as F, ASSET_INDEX_FILE as G, formatOp as H, exportFrames as I, formatBytes as J, stageAssets as K, driveScene as L, generateTypes as M, renderTypesModule as N, extractContentPack as O, previewFigure as P, listAssets as Q, locateDocsRoot as R, rasterizeMaterial as S, projectInfo as T, checkScripts as U, describeOps as V, schemaToTsType as W, packAsset as X, formatPacked as Y, inspectAsset as Z, loadComponentRegistry as _, lineupBatchDoc as a, updateProjectFile as at, diffSnapshots as b, validateAsset as c, registerExperiencePlaySchema as ct, runSimulation as d, importAsset as et, screenshotScene as f, listSchemasOp as g, listComponentsOp as h, bakeWorldgen as i, loadSetupLike as it, verifyContentPack as j, fetchContentPack as k, applyUvPaintOp as l, getSchemaOp as m, worldgenStats as n, loadProject as nt, loadStylePackFromDisk as o, parseExperiencePlayScenario as ot, getComponentOp as p, screenshotAsset as q, previewWorldgen as r, loadSceneDocument as rt, simWatch as s, playExperience as st, formatWorldgenStats as t, findProjectFile as tt, testTypes as u, scaffoldExperience as v, listTypes as w, runReplayFile as x, listTemplates as y, searchDocs as z };
8366
+ export { packAsset as $, inspectContentPack as A, OPS_CATALOG as B, checkTypesOp as C, buildContentPack as D, reserveNamespace as E, listFigurePresets as F, planAudio as G, formatOp as H, exportFrames as I, ASSET_INDEX_FILE as J, importSound as K, driveScene as L, generateTypes as M, renderTypesModule as N, extractContentPack as O, previewFigure as P, formatPacked as Q, locateDocsRoot as R, rasterizeMaterial as S, projectInfo as T, checkScripts as U, describeOps as V, schemaToTsType as W, screenshotAsset as X, stageAssets as Y, formatBytes as Z, loadComponentRegistry as _, lineupBatchDoc as a, loadProject as at, diffSnapshots as b, validateAsset as c, updateProjectFile as ct, runSimulation as d, registerExperiencePlaySchema as dt, inspectAsset as et, screenshotScene as f, listSchemasOp as g, listComponentsOp as h, bakeWorldgen as i, findProjectFile as it, verifyContentPack as j, fetchContentPack as k, applyUvPaintOp as l, parseExperiencePlayScenario as lt, getSchemaOp as m, worldgenStats as n, assetFileIndex as nt, loadStylePackFromDisk as o, loadSceneDocument as ot, getComponentOp as p, checkSoundbank as q, previewWorldgen as r, importAsset as rt, simWatch as s, loadSetupLike as st, formatWorldgenStats as t, listAssets as tt, testTypes as u, playExperience as ut, scaffoldExperience as v, listTypes as w, runReplayFile as x, listTemplates as y, searchDocs as z };