@wildshard/sdk 0.0.1 → 0.2.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 (687) hide show
  1. package/GUIDE.md +790 -0
  2. package/README.md +13 -5
  3. package/bin/wildshard.mjs +38 -0
  4. package/lint/declaration-config.d.mts +2 -0
  5. package/lint/declaration-config.mjs +19 -0
  6. package/lint/engine-plugin.d.mts +2 -0
  7. package/lint/engine-plugin.mjs +40 -0
  8. package/lint/host-callbacks.d.mts +6 -0
  9. package/lint/host-callbacks.mjs +123 -0
  10. package/lint/host-files.d.mts +1 -0
  11. package/lint/host-files.mjs +7 -0
  12. package/lint/layer-exports.d.mts +2 -0
  13. package/lint/layer-exports.mjs +21 -0
  14. package/lint/legacy-line-basis.json +995 -0
  15. package/lint/nine-tiling-baseline.json +35 -0
  16. package/lint/ratchet.json +11 -0
  17. package/lint/runtime-files.d.mts +12 -0
  18. package/lint/runtime-files.json +16 -0
  19. package/lint/runtime-files.mjs +69 -0
  20. package/lint/runtime-performance.d.mts +6 -0
  21. package/lint/runtime-performance.mjs +184 -0
  22. package/lint/sdk-plugin.d.mts +4 -0
  23. package/lint/sdk-plugin.mjs +134 -0
  24. package/lint/shardfile-boundaries.d.mts +10 -0
  25. package/lint/shardfile-boundaries.mjs +122 -0
  26. package/lint/tile-bake-debt.json +556 -0
  27. package/package.json +365 -3
  28. package/scripts/agent-parity.mjs +1524 -0
  29. package/scripts/agent-sync.mjs +518 -0
  30. package/scripts/apfs-clone.mjs +67 -0
  31. package/scripts/assert-store-layout.mjs +23 -0
  32. package/scripts/astc6-phone-cap.d.mts +3 -0
  33. package/scripts/astc6-phone-cap.mjs +137 -0
  34. package/scripts/audit-assets.d.mts +10 -0
  35. package/scripts/audit-assets.mjs +151 -0
  36. package/scripts/bake/coatFiles.d.mts +6 -0
  37. package/scripts/bake/coatFiles.mjs +37 -0
  38. package/scripts/bake/environment.d.mts +2 -0
  39. package/scripts/bake/environment.mjs +58 -0
  40. package/scripts/bake/far-proxies.mjs +45 -0
  41. package/scripts/bake/keyed-sky.d.mts +4 -0
  42. package/scripts/bake/keyed-sky.mjs +34 -0
  43. package/scripts/bake/movers.mjs +56 -0
  44. package/scripts/bake/nativeWorld.d.mts +6 -0
  45. package/scripts/bake/nativeWorld.mjs +43 -0
  46. package/scripts/bake/navmeshGround.ts +22 -0
  47. package/scripts/bake/near-placeholder.mjs +331 -0
  48. package/scripts/bake/placeholderShards.mjs +41 -0
  49. package/scripts/bake/skins.mjs +15 -0
  50. package/scripts/bake/template-skins.mjs +33 -0
  51. package/scripts/bake/viewmodelBytes.ts +26 -0
  52. package/scripts/bake/viewmodelPage.ts +11 -0
  53. package/scripts/bake/worldHost.d.mts +35 -0
  54. package/scripts/bake/worldHost.mjs +110 -0
  55. package/scripts/bake-astc6.cache.json +80 -0
  56. package/scripts/bake-astc6.far-reach.cache.json +23 -0
  57. package/scripts/bake-astc6.list.json +111 -0
  58. package/scripts/bake-astc6.mjs +279 -0
  59. package/scripts/bake-astc6.nalati-grasslands.cache.json +42 -0
  60. package/scripts/bake-catalogue.mjs +44 -0
  61. package/scripts/bake-check.mjs +54 -0
  62. package/scripts/bake-chunk.mjs +124 -0
  63. package/scripts/bake-cloud-field.mjs +24 -0
  64. package/scripts/bake-coats.mjs +110 -0
  65. package/scripts/bake-data-maps.d.mts +24 -0
  66. package/scripts/bake-data-maps.mjs +72 -0
  67. package/scripts/bake-entry-programs.mjs +117 -0
  68. package/scripts/bake-geometry.mjs +106 -0
  69. package/scripts/bake-hybrid-tiles.mjs +28 -0
  70. package/scripts/bake-ktx2.cache.json +276 -0
  71. package/scripts/bake-ktx2.list.json +365 -0
  72. package/scripts/bake-ktx2.mjs +477 -0
  73. package/scripts/bake-map-glb.mjs +127 -0
  74. package/scripts/bake-map-rest.d.mts +7 -0
  75. package/scripts/bake-map-rest.mjs +50 -0
  76. package/scripts/bake-maps.mjs +200 -0
  77. package/scripts/bake-navmesh.mjs +259 -0
  78. package/scripts/bake-packs.mjs +129 -0
  79. package/scripts/bake-pickups.mjs +102 -0
  80. package/scripts/bake-query-terrain.mjs +64 -0
  81. package/scripts/bake-recurve-pool.mjs +16 -0
  82. package/scripts/bake-section-schemas.d.mts +3 -0
  83. package/scripts/bake-template-shardfile.mjs +32 -0
  84. package/scripts/bake-textures.mjs +80 -0
  85. package/scripts/bake-viewmodel-sets.json +45 -0
  86. package/scripts/bake-viewmodel-sets.mjs +137 -0
  87. package/scripts/bake-voxel-ao.mjs +119 -0
  88. package/scripts/bake-water-ripples.mjs +25 -0
  89. package/scripts/blender/README.md +129 -0
  90. package/scripts/blender/build.sh +166 -0
  91. package/scripts/blender/lib/export-scene.mjs +129 -0
  92. package/scripts/blender/lib/glb-digest.mjs +188 -0
  93. package/scripts/blender/lib/glb.py +68 -0
  94. package/scripts/blender/lib/save_blend.py +17 -0
  95. package/scripts/blender/lib/world_fixture.py +55 -0
  96. package/scripts/blender/targets.json +591 -0
  97. package/scripts/build-sdk.mjs +95 -0
  98. package/scripts/build-shardfiles.d.mts +7 -0
  99. package/scripts/build-shardfiles.mjs +206 -0
  100. package/scripts/capture-hero.mjs +137 -0
  101. package/scripts/check-lift-review.mjs +23 -0
  102. package/scripts/chromium-keychain-check.mjs +139 -0
  103. package/scripts/chromium-keychain.d.mts +1 -0
  104. package/scripts/chromium-keychain.mjs +5 -0
  105. package/scripts/compile-script.d.mts +3 -0
  106. package/scripts/compile-script.mjs +8 -0
  107. package/scripts/creature-color.mjs +255 -0
  108. package/scripts/decide/calibrate.py +127 -0
  109. package/scripts/decide/calibration/2026-10-03/labels-s1.tsv +281 -0
  110. package/scripts/decide/calibration/2026-10-03/labels-s2.tsv +97 -0
  111. package/scripts/decide/calibration/2026-10-03/labels-s3.tsv +48 -0
  112. package/scripts/decide/calibration/2026-10-03/labels-s3b.tsv +26 -0
  113. package/scripts/decide/calibration/2026-10-03/res-capture-status-v1.jsonl +376 -0
  114. package/scripts/decide/calibration/2026-10-03/res-text-garbled-strings.jsonl +48 -0
  115. package/scripts/decide/calibration/2026-10-03/res-text-garbled-v1.jsonl +73 -0
  116. package/scripts/decide/decide.py +262 -0
  117. package/scripts/decide/decide.sh +50 -0
  118. package/scripts/decide/layer-purity-pilot.mjs +41 -0
  119. package/scripts/decide/sets/capture-status.json +46 -0
  120. package/scripts/decide/sets/layer-purity.json +28 -0
  121. package/scripts/decide/sets/text-garbled.json +17 -0
  122. package/scripts/decide/test_decide.py +37 -0
  123. package/scripts/docs.mjs +15 -0
  124. package/scripts/entry-reads/crawl.ts +152 -0
  125. package/scripts/entry-reads/tsconfig.json +25 -0
  126. package/scripts/gen-format-schema.d.mts +2 -0
  127. package/scripts/gen-format-schema.mjs +21 -0
  128. package/scripts/gen-host-catalogue.d.mts +14 -0
  129. package/scripts/gen-host-catalogue.mjs +108 -0
  130. package/scripts/gen-shard-layout-doc.d.mts +4 -0
  131. package/scripts/gen-shard-layout-doc.mjs +55 -0
  132. package/scripts/gen-shards.d.mts +17 -0
  133. package/scripts/gen-shards.mjs +311 -0
  134. package/scripts/goldens/capture-inputs.d.mts +4 -0
  135. package/scripts/goldens/capture-inputs.mjs +34 -0
  136. package/scripts/goldens/colour_shift.py +27 -0
  137. package/scripts/goldens/native-residency.d.mts +10 -0
  138. package/scripts/goldens/native-residency.mjs +104 -0
  139. package/scripts/goldens/plot-inputs.d.mts +12 -0
  140. package/scripts/goldens/plot-inputs.mjs +46 -0
  141. package/scripts/gpu-texmem.mjs +98 -0
  142. package/scripts/horizon-matte/config.py +24 -0
  143. package/scripts/horizon-matte/encode.py +91 -0
  144. package/scripts/horizon-matte/key.py +141 -0
  145. package/scripts/horizon-matte/mkjobs.py +33 -0
  146. package/scripts/horizon-matte/mkjobs_day2.py +11 -0
  147. package/scripts/horizon-matte/overlap.py +80 -0
  148. package/scripts/horizon-matte/run_codex.py +57 -0
  149. package/scripts/horizon-matte/stitch.py +133 -0
  150. package/scripts/img2mesh/CC0.md +105 -0
  151. package/scripts/img2mesh/README.md +209 -0
  152. package/scripts/img2mesh/ab_board.py +102 -0
  153. package/scripts/img2mesh/birds/birds.json +255 -0
  154. package/scripts/img2mesh/birds/birds_atlas.py +150 -0
  155. package/scripts/img2mesh/birds/birds_fix_preview.mjs +103 -0
  156. package/scripts/img2mesh/birds/birds_fix_render.py +75 -0
  157. package/scripts/img2mesh/birds/birds_pack.py +110 -0
  158. package/scripts/img2mesh/birds/birds_phone_b.py +112 -0
  159. package/scripts/img2mesh/birds/birds_post.py +550 -0
  160. package/scripts/img2mesh/birds/birds_render.py +125 -0
  161. package/scripts/img2mesh/birds/birds_sheet.py +33 -0
  162. package/scripts/img2mesh/birds/birds_view.py +60 -0
  163. package/scripts/img2mesh/board.py +100 -0
  164. package/scripts/img2mesh/build_cc0.sh +52 -0
  165. package/scripts/img2mesh/build_driftwood.sh +12 -0
  166. package/scripts/img2mesh/build_faces.sh +53 -0
  167. package/scripts/img2mesh/build_props.py +81 -0
  168. package/scripts/img2mesh/cc0_export.py +186 -0
  169. package/scripts/img2mesh/driftwood_post.py +571 -0
  170. package/scripts/img2mesh/e304_faces.sh +67 -0
  171. package/scripts/img2mesh/face_remaster.py +911 -0
  172. package/scripts/img2mesh/face_views.py +95 -0
  173. package/scripts/img2mesh/faces-e304.json +9 -0
  174. package/scripts/img2mesh/faces.json +30 -0
  175. package/scripts/img2mesh/head_cut.py +100 -0
  176. package/scripts/img2mesh/hi3d_paint.py +94 -0
  177. package/scripts/img2mesh/hi3d_refine.py +161 -0
  178. package/scripts/img2mesh/hunyuan_cpu_rasterizer.sh +42 -0
  179. package/scripts/img2mesh/pine_hollow_phone.sh +13 -0
  180. package/scripts/img2mesh/props/coral-arch.json +32 -0
  181. package/scripts/img2mesh/props/ember-furnace.json +30 -0
  182. package/scripts/img2mesh/props/night-market-gate.json +10 -0
  183. package/scripts/img2mesh/render_still.py +86 -0
  184. package/scripts/img2mesh/rig_strip.mjs +46 -0
  185. package/scripts/img2mesh/rig_transfer.mjs +104 -0
  186. package/scripts/img2mesh/split_sheet.py +48 -0
  187. package/scripts/img2mesh/trellis_batch.py +110 -0
  188. package/scripts/img2mesh/versus_board.py +114 -0
  189. package/scripts/import-bundle.d.mts +2 -0
  190. package/scripts/import-bundle.mjs +20 -0
  191. package/scripts/ktx2-ab-board.py +133 -0
  192. package/scripts/ktx2-ab.mjs +111 -0
  193. package/scripts/ktx2-settings.mjs +18 -0
  194. package/scripts/land.d.mts +14 -0
  195. package/scripts/land.mjs +809 -0
  196. package/scripts/lint-dispatch.mjs +14 -0
  197. package/scripts/map-bake-frames.d.mts +4 -0
  198. package/scripts/map-bake-frames.mjs +23 -0
  199. package/scripts/map-geometry.d.mts +9 -0
  200. package/scripts/map-geometry.mjs +29 -0
  201. package/scripts/map-world.mjs +162 -0
  202. package/scripts/mockup-local.sh +46 -0
  203. package/scripts/music/export-midi.mjs +68 -0
  204. package/scripts/music/gen/analyze.py +308 -0
  205. package/scripts/music/gen/audio_jobs.py +46 -0
  206. package/scripts/music/gen/briefs.json +51 -0
  207. package/scripts/music/gen/build_page.py +334 -0
  208. package/scripts/music/gen/folk.json +3187 -0
  209. package/scripts/music/gen/gen_ace_step.py +156 -0
  210. package/scripts/music/gen/gen_heartmula.py +187 -0
  211. package/scripts/music/gen/gen_minimax.py +143 -0
  212. package/scripts/music/gen/gen_sao.py +122 -0
  213. package/scripts/music/gen/gen_sao_small.py +104 -0
  214. package/scripts/music/gen/gen_sfx.py +98 -0
  215. package/scripts/music/gen/gen_sfx_ezaudio.py +112 -0
  216. package/scripts/music/gen/gen_sfx_moss.py +112 -0
  217. package/scripts/music/gen/models.json +61 -0
  218. package/scripts/music/gen/nalati-jobs.json +104 -0
  219. package/scripts/music/gen/nalati-score-build.json +119 -0
  220. package/scripts/music/gen/nalati-score.json +3448 -0
  221. package/scripts/music/gen/ob7-fit-decisions.json +38 -0
  222. package/scripts/music/gen/ob7-score-jobs.json +152 -0
  223. package/scripts/music/gen/ob7-sfx-jobs.json +897 -0
  224. package/scripts/music/gen/ob7_build.py +469 -0
  225. package/scripts/music/gen/ob7_generate.py +67 -0
  226. package/scripts/music/gen/ob7_run.sh +42 -0
  227. package/scripts/music/gen/orchestral.json +3187 -0
  228. package/scripts/music/gen/own_score.py +486 -0
  229. package/scripts/music/gen/ph-jobs.json +27 -0
  230. package/scripts/music/gen/ph_page.py +222 -0
  231. package/scripts/music/gen/piano.json +3175 -0
  232. package/scripts/music/gen/rank_v3.py +248 -0
  233. package/scripts/music/gen/sfx-best.json +2486 -0
  234. package/scripts/music/gen/sfx-ezaudio.json +4082 -0
  235. package/scripts/music/gen/sfx-jobs.json +57 -0
  236. package/scripts/music/gen/sfx-minimax-jobs.json +16 -0
  237. package/scripts/music/gen/sfx-minimax.json +289 -0
  238. package/scripts/music/gen/sfx-moss.json +4082 -0
  239. package/scripts/music/gen/sfx-nalati-b3-jobs.json +17 -0
  240. package/scripts/music/gen/sfx-nalati-jobs.json +338 -0
  241. package/scripts/music/gen/sfx-nalati.json +11202 -0
  242. package/scripts/music/gen/sfx-nd-jobs.json +57 -0
  243. package/scripts/music/gen/sfx-nd-moss.json +2097 -0
  244. package/scripts/music/gen/sfx-nd-sa3-medium.json +2097 -0
  245. package/scripts/music/gen/sfx-nd-summary.json +38 -0
  246. package/scripts/music/gen/sfx-peaks.json +7 -0
  247. package/scripts/music/gen/sfx-ph-jobs.json +169 -0
  248. package/scripts/music/gen/sfx-ph-moss.json +6564 -0
  249. package/scripts/music/gen/sfx-ph-sa3-medium.json +7239 -0
  250. package/scripts/music/gen/sfx-ph-summary.json +63 -0
  251. package/scripts/music/gen/sfx-sa3-medium.json +4082 -0
  252. package/scripts/music/gen/sfx-sa3.json +4082 -0
  253. package/scripts/music/gen/sfx-summary.json +107 -0
  254. package/scripts/music/gen/sfx_build.py +332 -0
  255. package/scripts/music/gen/sfx_merge.py +255 -0
  256. package/scripts/music/gen/sfx_minimax.py +61 -0
  257. package/scripts/music/gen/sfx_nalati.py +331 -0
  258. package/scripts/music/gen/sfx_sprite.py +424 -0
  259. package/scripts/music/gen/stems.py +539 -0
  260. package/scripts/music/gen/test_loop_meter.py +29 -0
  261. package/scripts/music/gen/test_ob7_provenance.py +77 -0
  262. package/scripts/music/gen/v3-folk-build.json +148 -0
  263. package/scripts/music/gen/v3-folk.json +1818 -0
  264. package/scripts/music/gen/v3-jobs.json +145 -0
  265. package/scripts/music/gen/v3-orchestral-build.json +148 -0
  266. package/scripts/music/gen/v3-orchestral.json +1813 -0
  267. package/scripts/music/gen/v3-ph-folk-build.json +94 -0
  268. package/scripts/music/gen/v3-ph-folk.json +1806 -0
  269. package/scripts/music/gen/v3-ph-orchestral-build.json +94 -0
  270. package/scripts/music/gen/v3-ph-orchestral.json +1824 -0
  271. package/scripts/music/gen/v3-ph-piano-build.json +94 -0
  272. package/scripts/music/gen/v3-ph-piano.json +1818 -0
  273. package/scripts/music/gen/v3-piano-build.json +148 -0
  274. package/scripts/music/gen/v3-piano.json +1813 -0
  275. package/scripts/music/wildshard-theme.mid +0 -0
  276. package/scripts/music/wildshard-trailer30.mid +0 -0
  277. package/scripts/named-blob-output.d.mts +8 -0
  278. package/scripts/named-blob-output.mjs +48 -0
  279. package/scripts/pack-all.mjs +15 -0
  280. package/scripts/pid-lock.d.mts +1 -0
  281. package/scripts/pid-lock.mjs +63 -0
  282. package/scripts/practice/bake_dummy.py +53 -0
  283. package/scripts/practice/build_dummies.sh +43 -0
  284. package/scripts/practice/dummy_parts.py +568 -0
  285. package/scripts/practice/dummy_rig_gate.py +139 -0
  286. package/scripts/practice/gate_sheet.py +36 -0
  287. package/scripts/practice/generate_dummy_unimate.py +132 -0
  288. package/scripts/practice/pack_dummy.mjs +59 -0
  289. package/scripts/practice/repair_dummy_weights.mjs +68 -0
  290. package/scripts/practice/rig_dummy.py +828 -0
  291. package/scripts/practice/verify_unimate_skin.mjs +356 -0
  292. package/scripts/preparation-seed.mjs +15 -0
  293. package/scripts/prepare-basis-tool.mjs +6 -0
  294. package/scripts/prepare-product.d.mts +14 -0
  295. package/scripts/prepare-product.mjs +101 -0
  296. package/scripts/product-build-tools.d.mts +3 -0
  297. package/scripts/product-build-tools.json +3 -0
  298. package/scripts/product-build-tools.mjs +31 -0
  299. package/scripts/publish-public.mjs +7 -0
  300. package/scripts/push-tables.d.mts +1 -0
  301. package/scripts/push-tables.mjs +28 -0
  302. package/scripts/record-shard-mounts.mjs +133 -0
  303. package/scripts/sdk-externals.d.mts +2 -0
  304. package/scripts/sdk-externals.mjs +2 -0
  305. package/scripts/section-inventory.ts +209 -0
  306. package/scripts/select-candidate.mjs +15 -0
  307. package/scripts/shard-build-pool.d.mts +4 -0
  308. package/scripts/shard-build-pool.mjs +53 -0
  309. package/scripts/shard-line-baseline.json +17 -0
  310. package/scripts/shard-milestones.d.mts +15 -0
  311. package/scripts/shard-milestones.mjs +105 -0
  312. package/scripts/shard-output-report.d.mts +9 -0
  313. package/scripts/shard-output-report.mjs +85 -0
  314. package/scripts/shard-platform-cli.mjs +93 -0
  315. package/scripts/shard-progress.mjs +212 -0
  316. package/scripts/shard-timelapse.py +102 -0
  317. package/scripts/shardfile-cold-boot.mjs +79 -0
  318. package/scripts/shardfile-vite.d.mts +4 -0
  319. package/scripts/shardfile-vite.mjs +20 -0
  320. package/scripts/simplify-models.mjs +24 -0
  321. package/scripts/site-facts.mjs +88 -0
  322. package/scripts/test-template-gate.mjs +44 -0
  323. package/scripts/test_golden_compare.py +68 -0
  324. package/scripts/tex-tiers.cache.json +181 -0
  325. package/scripts/tex-tiers.mjs +240 -0
  326. package/scripts/texmem-probe.mjs +184 -0
  327. package/scripts/unused-assets.mjs +173 -0
  328. package/scripts/vite-tmp.d.mts +23 -0
  329. package/scripts/vite-tmp.mjs +157 -0
  330. package/scripts/wave-line-baselines.json +32 -0
  331. package/scripts/wildshard.d.mts +4 -0
  332. package/scripts/wildshard.mjs +105 -0
  333. package/scripts/witness-checkpoints.d.mts +10 -0
  334. package/scripts/witness-checkpoints.mjs +84 -0
  335. package/scripts/witness-generation.d.mts +10 -0
  336. package/scripts/witness-generation.mjs +45 -0
  337. package/scripts/witness-manifests.d.mts +8 -0
  338. package/scripts/witness-manifests.mjs +157 -0
  339. package/scripts/worktree-ignore.d.mts +4 -0
  340. package/scripts/worktree-ignore.mjs +36 -0
  341. package/scripts/worktree-reap.mjs +214 -0
  342. package/scripts/worktree.mjs +396 -0
  343. package/scripts/worldclaw/capture-front.sh +28 -0
  344. package/scripts/worldclaw/design-template.md +62 -0
  345. package/scripts/worldclaw/spec-map.py +92 -0
  346. package/scripts/worldclaw/spec.ts +96 -0
  347. package/skills/wildshard/SKILL.md +50 -0
  348. package/skills/wildshard-goldens/SKILL.md +54 -0
  349. package/skills/wildshard-mockup-to-model/SKILL.md +56 -0
  350. package/skills/wildshard-upgrade/SKILL.md +46 -0
  351. package/src/.oxfmtrc.json +50 -0
  352. package/src/.oxlintrc.json +173 -0
  353. package/src/cli/account/account.ts +199 -0
  354. package/src/cli/account/command.ts +193 -0
  355. package/src/cli/account/key.ts +154 -0
  356. package/src/cli/args.ts +97 -0
  357. package/src/cli/audio/audio.ts +24 -0
  358. package/src/cli/bin.mjs +8 -0
  359. package/src/cli/delete/delete.ts +258 -0
  360. package/src/cli/help.ts +196 -0
  361. package/src/cli/hero/adopt.ts +103 -0
  362. package/src/cli/hero/hero.ts +112 -0
  363. package/src/cli/hero/stamp.ts +298 -0
  364. package/src/cli/main.ts +292 -0
  365. package/src/cli/report.ts +16 -0
  366. package/src/cli/shardfile/command.ts +50 -0
  367. package/src/cli/shardfile/shardfile.ts +192 -0
  368. package/src/cli/upload/api.ts +246 -0
  369. package/src/cli/upload/compress.ts +55 -0
  370. package/src/cli/upload/hero.ts +62 -0
  371. package/src/cli/upload/placement.ts +115 -0
  372. package/src/cli/upload/provenance.ts +192 -0
  373. package/src/cli/upload/signature.ts +30 -0
  374. package/src/cli/upload/upload.ts +269 -0
  375. package/src/cli/upload/validate.ts +74 -0
  376. package/src/cli/upload/wire.ts +147 -0
  377. package/src/cli/version.ts +63 -0
  378. package/src/commons/bake/portableMath.ts +187 -0
  379. package/src/commons/catalogue.ts +10 -0
  380. package/src/commons/courseProgram.ts +32 -0
  381. package/src/commons/practiceCourse.ts +16 -0
  382. package/src/commons/scripts/abi.as +14 -0
  383. package/src/commons/scripts/bridge.as +14 -0
  384. package/src/commons/scripts/course.as +63 -0
  385. package/src/scripts/ask-new.sh +29 -0
  386. package/src/scripts/asks.mjs +141 -0
  387. package/src/scripts/herdr-prompt.sh +34 -0
  388. package/src/scripts/herdr-question-open.sh +67 -0
  389. package/src/scripts/md-wrap.mjs +229 -0
  390. package/src/server/app.ts +19 -0
  391. package/src/server/serve.ts +49 -0
  392. package/src/sharddev/admission.ts +7 -0
  393. package/src/sharddev/arenaView.ts +15 -0
  394. package/src/sharddev/as/groupBankV2.ts +36 -0
  395. package/src/sharddev/as/groupStepV2.ts +13 -0
  396. package/src/sharddev/as/ws.ts +30 -0
  397. package/src/sharddev/as/wsV2.ts +180 -0
  398. package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
  399. package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
  400. package/src/sharddev/assetHandle.ts +84 -0
  401. package/src/sharddev/assetOwner.ts +70 -0
  402. package/src/sharddev/assetScope.ts +30 -0
  403. package/src/sharddev/assets.ts +21 -0
  404. package/src/sharddev/audio.ts +9 -0
  405. package/src/sharddev/audioEncode.ts +211 -0
  406. package/src/sharddev/author.ts +3 -0
  407. package/src/sharddev/authorError.ts +28 -0
  408. package/src/sharddev/authorManifest.ts +39 -0
  409. package/src/sharddev/bake/annulus.ts +19 -0
  410. package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
  411. package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
  412. package/src/sharddev/bake/authoredWorld.ts +201 -0
  413. package/src/sharddev/bake/basisEncoder.ts +95 -0
  414. package/src/sharddev/bake/basisGlb.ts +85 -0
  415. package/src/sharddev/bake/basisTool.ts +74 -0
  416. package/src/sharddev/bake/basisToolInputs.ts +476 -0
  417. package/src/sharddev/bake/byteCodec.ts +33 -0
  418. package/src/sharddev/bake/canvasAtlas.ts +406 -0
  419. package/src/sharddev/bake/coarseCopy.ts +59 -0
  420. package/src/sharddev/bake/colliders.ts +87 -0
  421. package/src/sharddev/bake/compactGlb.ts +224 -0
  422. package/src/sharddev/bake/compileScript.ts +119 -0
  423. package/src/sharddev/bake/compileScriptV2.ts +75 -0
  424. package/src/sharddev/bake/contactRows.ts +84 -0
  425. package/src/sharddev/bake/creaturePlacement.ts +117 -0
  426. package/src/sharddev/bake/export.ts +67 -0
  427. package/src/sharddev/bake/facetedGeometry.ts +379 -0
  428. package/src/sharddev/bake/farImpostor.ts +120 -0
  429. package/src/sharddev/bake/forest.ts +100 -0
  430. package/src/sharddev/bake/format-hook.mjs +2 -0
  431. package/src/sharddev/bake/generatorGlb.ts +23 -0
  432. package/src/sharddev/bake/geometryBounds.ts +77 -0
  433. package/src/sharddev/bake/geometryError.ts +48 -0
  434. package/src/sharddev/bake/glb.ts +355 -0
  435. package/src/sharddev/bake/glbCompression.ts +143 -0
  436. package/src/sharddev/bake/gltfSource.ts +59 -0
  437. package/src/sharddev/bake/groundMap.ts +142 -0
  438. package/src/sharddev/bake/image.ts +20 -0
  439. package/src/sharddev/bake/isleMap.ts +64 -0
  440. package/src/sharddev/bake/json.mjs +84 -0
  441. package/src/sharddev/bake/keyedSky.ts +47 -0
  442. package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
  443. package/src/sharddev/bake/kinds.ts +137 -0
  444. package/src/sharddev/bake/lightSources.ts +31 -0
  445. package/src/sharddev/bake/mapAssembly.ts +84 -0
  446. package/src/sharddev/bake/mapRaster.ts +173 -0
  447. package/src/sharddev/bake/mapRest.ts +57 -0
  448. package/src/sharddev/bake/mapScenes.ts +234 -0
  449. package/src/sharddev/bake/materialGraph.ts +32 -0
  450. package/src/sharddev/bake/meadow.ts +27 -0
  451. package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
  452. package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
  453. package/src/sharddev/bake/nativeLattice.ts +178 -0
  454. package/src/sharddev/bake/nativeRaster.ts +106 -0
  455. package/src/sharddev/bake/nativeTerrainField.ts +11 -0
  456. package/src/sharddev/bake/navigation-json.mjs +38 -0
  457. package/src/sharddev/bake/navigation.ts +113 -0
  458. package/src/sharddev/bake/navigationAsset.ts +18 -0
  459. package/src/sharddev/bake/nearPlaceholder.ts +206 -0
  460. package/src/sharddev/bake/normalizeRig.ts +80 -0
  461. package/src/sharddev/bake/phoneAstc.ts +93 -0
  462. package/src/sharddev/bake/placeholders.ts +581 -0
  463. package/src/sharddev/bake/placement.ts +80 -0
  464. package/src/sharddev/bake/portableBytes.ts +18 -0
  465. package/src/sharddev/bake/portableBytesMemo.ts +50 -0
  466. package/src/sharddev/bake/practiceCourse.ts +49 -0
  467. package/src/sharddev/bake/primitives.ts +96 -0
  468. package/src/sharddev/bake/props.ts +443 -0
  469. package/src/sharddev/bake/questPlacement.ts +98 -0
  470. package/src/sharddev/bake/rawTexture.ts +26 -0
  471. package/src/sharddev/bake/riderArms.ts +97 -0
  472. package/src/sharddev/bake/rig.ts +95 -0
  473. package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
  474. package/src/sharddev/bake/signPlacements.ts +25 -0
  475. package/src/sharddev/bake/simplifier.ts +52 -0
  476. package/src/sharddev/bake/skinned.ts +312 -0
  477. package/src/sharddev/bake/slabChunks.ts +149 -0
  478. package/src/sharddev/bake/slabs.ts +263 -0
  479. package/src/sharddev/bake/source-loader.mjs +55 -0
  480. package/src/sharddev/bake/sourceMetadata.ts +54 -0
  481. package/src/sharddev/bake/species.ts +368 -0
  482. package/src/sharddev/bake/specimenCatalogue.ts +47 -0
  483. package/src/sharddev/bake/splatGround.ts +141 -0
  484. package/src/sharddev/bake/staticMaterials.ts +171 -0
  485. package/src/sharddev/bake/terrain.ts +195 -0
  486. package/src/sharddev/bake/texture.ts +33 -0
  487. package/src/sharddev/bake/textureWasm.ts +81 -0
  488. package/src/sharddev/bake/tileEncoder.ts +11 -0
  489. package/src/sharddev/bake/tileGrid.ts +62 -0
  490. package/src/sharddev/bake/v2Finite.ts +160 -0
  491. package/src/sharddev/bake/v2Fuel.ts +71 -0
  492. package/src/sharddev/bake/wholePartition.ts +74 -0
  493. package/src/sharddev/bake/wholePieceJoin.ts +147 -0
  494. package/src/sharddev/bake/world.ts +173 -0
  495. package/src/sharddev/bake/worldCollision.ts +128 -0
  496. package/src/sharddev/bake/worldGeometry.ts +237 -0
  497. package/src/sharddev/bake/worldGlb.ts +123 -0
  498. package/src/sharddev/bake/worldImage.ts +12 -0
  499. package/src/sharddev/bake/worldLod.ts +128 -0
  500. package/src/sharddev/bake/worldRows.ts +102 -0
  501. package/src/sharddev/bake/worldTextureMemo.ts +63 -0
  502. package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
  503. package/src/sharddev/bake.ts +193 -0
  504. package/src/sharddev/bakePublication.ts +31 -0
  505. package/src/sharddev/behaviourSource.ts +94 -0
  506. package/src/sharddev/bin/wildshard.mjs +7 -0
  507. package/src/sharddev/blobBytes.ts +65 -0
  508. package/src/sharddev/blobs.ts +138 -0
  509. package/src/sharddev/bootInventory.ts +129 -0
  510. package/src/sharddev/bossProfiles.ts +18 -0
  511. package/src/sharddev/buildBehaviour.ts +77 -0
  512. package/src/sharddev/buildCacheMetrics.ts +17 -0
  513. package/src/sharddev/buildDecisionScripts.ts +122 -0
  514. package/src/sharddev/check.ts +117 -0
  515. package/src/sharddev/checkProject.ts +126 -0
  516. package/src/sharddev/cli.ts +191 -0
  517. package/src/sharddev/clientChannels.ts +169 -0
  518. package/src/sharddev/clientScripts.ts +10 -0
  519. package/src/sharddev/commons.ts +77 -0
  520. package/src/sharddev/commonsCosts.ts +11 -0
  521. package/src/sharddev/compileMovers.ts +11 -0
  522. package/src/sharddev/configBoundary.ts +6 -0
  523. package/src/sharddev/cookInput.ts +40 -0
  524. package/src/sharddev/crowds.ts +6 -0
  525. package/src/sharddev/decisionBindingMap.ts +11 -0
  526. package/src/sharddev/decisionScriptBindings.ts +117 -0
  527. package/src/sharddev/decisionScripts.ts +28 -0
  528. package/src/sharddev/decisionSource.ts +51 -0
  529. package/src/sharddev/dev.ts +113 -0
  530. package/src/sharddev/director.ts +26 -0
  531. package/src/sharddev/directorAbi.ts +77 -0
  532. package/src/sharddev/discoveryDocument.ts +97 -0
  533. package/src/sharddev/draft.ts +11 -0
  534. package/src/sharddev/eliteEntryRows.ts +29 -0
  535. package/src/sharddev/entries.ts +76 -0
  536. package/src/sharddev/entryReads.ts +73 -0
  537. package/src/sharddev/executeBundle.ts +55 -0
  538. package/src/sharddev/finds.ts +5 -0
  539. package/src/sharddev/formatJsonSchema.ts +3 -0
  540. package/src/sharddev/generationCache.ts +257 -0
  541. package/src/sharddev/generationRecipe.ts +94 -0
  542. package/src/sharddev/handwritten.ts +110 -0
  543. package/src/sharddev/immutable.ts +14 -0
  544. package/src/sharddev/interactions.ts +38 -0
  545. package/src/sharddev/kit/bakedGeometry.ts +16 -0
  546. package/src/sharddev/kit/geometryPack.ts +110 -0
  547. package/src/sharddev/ledger.ts +13 -0
  548. package/src/sharddev/looks/tileField.ts +67 -0
  549. package/src/sharddev/materialGraphFiles.ts +57 -0
  550. package/src/sharddev/materials.ts +574 -0
  551. package/src/sharddev/measure.ts +18 -0
  552. package/src/sharddev/modes.ts +115 -0
  553. package/src/sharddev/moverPrograms.ts +213 -0
  554. package/src/sharddev/movers.ts +75 -0
  555. package/src/sharddev/nativePopulationRows.ts +46 -0
  556. package/src/sharddev/newProject.ts +247 -0
  557. package/src/sharddev/noise.ts +54 -0
  558. package/src/sharddev/outputProduct.ts +188 -0
  559. package/src/sharddev/outputRuntime.ts +66 -0
  560. package/src/sharddev/performancePolicy.ts +18 -0
  561. package/src/sharddev/phasedBoss.ts +34 -0
  562. package/src/sharddev/physics.ts +194 -0
  563. package/src/sharddev/platformSections.ts +42 -0
  564. package/src/sharddev/plumbing.ts +8 -0
  565. package/src/sharddev/productOutput.ts +128 -0
  566. package/src/sharddev/project.ts +337 -0
  567. package/src/sharddev/projectCompilerIdentity.ts +94 -0
  568. package/src/sharddev/projectDecisions.ts +66 -0
  569. package/src/sharddev/projectEntryProof.ts +32 -0
  570. package/src/sharddev/projectGeneration.ts +219 -0
  571. package/src/sharddev/projectInputFiles.ts +47 -0
  572. package/src/sharddev/projectManifest.ts +108 -0
  573. package/src/sharddev/projectMap.ts +35 -0
  574. package/src/sharddev/projectOutput.ts +242 -0
  575. package/src/sharddev/projectPolicy.ts +17 -0
  576. package/src/sharddev/projectSections.ts +27 -0
  577. package/src/sharddev/questGraph.ts +25 -0
  578. package/src/sharddev/quests.ts +65 -0
  579. package/src/sharddev/random.ts +61 -0
  580. package/src/sharddev/refusals.ts +234 -0
  581. package/src/sharddev/reportCard.ts +13 -0
  582. package/src/sharddev/returnProjectionV2.ts +81 -0
  583. package/src/sharddev/rows.ts +192 -0
  584. package/src/sharddev/runtimeImports.ts +38 -0
  585. package/src/sharddev/runtimeMirrors.ts +39 -0
  586. package/src/sharddev/runtimePerformance.ts +38 -0
  587. package/src/sharddev/scene.ts +321 -0
  588. package/src/sharddev/sceneAnimation.ts +54 -0
  589. package/src/sharddev/sceneAudio.ts +64 -0
  590. package/src/sharddev/sceneDeclarations.ts +100 -0
  591. package/src/sharddev/sceneGraph.ts +139 -0
  592. package/src/sharddev/sceneTransform.ts +12 -0
  593. package/src/sharddev/schemaValidation.ts +61 -0
  594. package/src/sharddev/sections.ts +47 -0
  595. package/src/sharddev/shardSource.ts +59 -0
  596. package/src/sharddev/sourceReader.ts +26 -0
  597. package/src/sharddev/spawns.ts +38 -0
  598. package/src/sharddev/species/clips.ts +24 -0
  599. package/src/sharddev/species.ts +29 -0
  600. package/src/sharddev/speciesBrains.ts +19 -0
  601. package/src/sharddev/synth.ts +66 -0
  602. package/src/sharddev/test/compileDualScriptV2.ts +71 -0
  603. package/src/sharddev/test/compileSimV2.ts +21 -0
  604. package/src/sharddev/test/diskScriptScenario.ts +86 -0
  605. package/src/sharddev/test/scriptScenario.ts +249 -0
  606. package/src/sharddev/test/scriptSource.ts +12 -0
  607. package/src/sharddev/version.ts +4 -0
  608. package/src/sharddev/weapons/bowProfile.ts +20 -0
  609. package/src/sharddev/weapons/firearmRows.ts +11 -0
  610. package/src/sharddev/weapons/meleeProfile.ts +71 -0
  611. package/src/sharddev/weapons/thrownProfile.ts +10 -0
  612. package/src/sharddev/worldScenes.ts +308 -0
  613. package/src/sharddev/worldSource.ts +82 -0
  614. package/src/shards/_template/README.md +78 -0
  615. package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
  616. package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
  617. package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
  618. package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
  619. package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
  620. package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
  621. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
  622. package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
  623. package/src/shards/_template/behaviour/boss.as +39 -0
  624. package/src/shards/_template/behaviour/door.as +32 -0
  625. package/src/shards/_template/behaviour/hooks.json +129 -0
  626. package/src/shards/_template/behaviour/idle.as +75 -0
  627. package/src/shards/_template/behaviour/items.as +22 -0
  628. package/src/shards/_template/card/landscape.jpg +0 -0
  629. package/src/shards/_template/card/portrait.jpg +0 -0
  630. package/src/shards/_template/card/thumb.jpg +0 -0
  631. package/src/shards/_template/data/audio.json +45 -0
  632. package/src/shards/_template/data/bossDecision.json +83 -0
  633. package/src/shards/_template/data/budgets.json +70 -0
  634. package/src/shards/_template/data/card.json +281 -0
  635. package/src/shards/_template/data/clientScripts.json +987 -0
  636. package/src/shards/_template/data/creatures.json +65 -0
  637. package/src/shards/_template/data/director.json +39 -0
  638. package/src/shards/_template/data/encounters.json +96 -0
  639. package/src/shards/_template/data/items.json +172 -0
  640. package/src/shards/_template/data/layout.json +66 -0
  641. package/src/shards/_template/data/ledger.json +32 -0
  642. package/src/shards/_template/data/look.json +521 -0
  643. package/src/shards/_template/data/map.json +64 -0
  644. package/src/shards/_template/data/moves.json +16 -0
  645. package/src/shards/_template/data/placeholder.json +8 -0
  646. package/src/shards/_template/data/plumbing.json +32 -0
  647. package/src/shards/_template/data/quests.json +223 -0
  648. package/src/shards/_template/data/rows.json +423 -0
  649. package/src/shards/_template/data/skins.json +66 -0
  650. package/src/shards/_template/data/spawn.json +6 -0
  651. package/src/shards/_template/data/targets.json +150 -0
  652. package/src/shards/_template/data/text.json +12 -0
  653. package/src/shards/_template/data/ui.json +33 -0
  654. package/src/shards/_template/data/water.json +13 -0
  655. package/src/shards/_template/generators/behaviour.ts +34 -0
  656. package/src/shards/_template/generators/boss.ts +29 -0
  657. package/src/shards/_template/generators/buildOptions.ts +2 -0
  658. package/src/shards/_template/generators/cell.ts +224 -0
  659. package/src/shards/_template/generators/districts.ts +215 -0
  660. package/src/shards/_template/generators/farLook.ts +15 -0
  661. package/src/shards/_template/generators/generate.ts +27 -0
  662. package/src/shards/_template/generators/ground.ts +15 -0
  663. package/src/shards/_template/generators/kit.ts +69 -0
  664. package/src/shards/_template/generators/landscape.ts +59 -0
  665. package/src/shards/_template/generators/landscapeNoise.ts +62 -0
  666. package/src/shards/_template/generators/mapInputs.ts +10 -0
  667. package/src/shards/_template/generators/product.ts +100 -0
  668. package/src/shards/_template/generators/productOutput.ts +18 -0
  669. package/src/shards/_template/generators/props.ts +9 -0
  670. package/src/shards/_template/generators/templatePropsSource.ts +58 -0
  671. package/src/shards/_template/generators/terrain.ts +17 -0
  672. package/src/shards/_template/generators/world.ts +630 -0
  673. package/src/shards/_template/hero.json +10 -0
  674. package/src/shards/_template/look/entry-reads.json +20 -0
  675. package/src/shards/_template/manifest.json +281 -0
  676. package/src/shards/_template/shard.config.ts +10 -0
  677. package/src/shared/health.ts +10 -0
  678. package/src/tools/build-web.ts +59 -0
  679. package/src/tsconfig.json +30 -0
  680. package/src/web/app.tsx +53 -0
  681. package/src/web/index.html +12 -0
  682. package/src/web/main.tsx +10 -0
  683. package/src/web/tsconfig.json +13 -0
  684. package/tsconfig.author.json +23 -0
  685. package/tsconfig.commons.json +21 -0
  686. package/tsconfig.json +47 -0
  687. package/tsconfig.sharddev.json +20 -0
@@ -0,0 +1,117 @@
1
+ /** Build-only ordered placement; streams and ground stay borrowed from the author. */
2
+ /** Bounded radial or indexed creature placement over an existing stream and ground owner. A radial source draws a math
3
+ * angle (x = cos, z = sin) or a compass bearing (x = sin, z = cos), scaled per axis for an elliptical region. */
4
+ export interface CreatureGroupSpec<K extends string = string> {
5
+ readonly kind: K; readonly count: number; readonly herd: number; readonly variant: string | null;
6
+ readonly firstVariant?: string | null; readonly variants?: readonly (string | null)[];
7
+ /** a fixed yaw, or a point every sample faces; omitted, each yaw is a draw after its point */
8
+ readonly yaw?: number; readonly face?: { readonly x: number; readonly z: number };
9
+ readonly source: { readonly kind: 'indexed'; readonly points: readonly { readonly x: number; readonly z: number }[] }
10
+ | { readonly kind: 'radial'; readonly centre: { readonly x: number; readonly z: number }; readonly radius: readonly [number, number];
11
+ readonly axes?: readonly [number, number]; readonly bearing?: 'math' | 'compass';
12
+ readonly firstAtCentre?: boolean; readonly radiusLaw?: 'linear' | 'area'; readonly attempts?: number; readonly fallback?: 'skip' | 'centre' };
13
+ /** Data rejection of a candidate: outside a distance band to a point, inside a clear circle, past a square bound
14
+ * (|x| or |z|), or ground below `minHeight` (read through the ground owner). */
15
+ readonly accept?: {
16
+ readonly band?: { readonly x: number; readonly z: number; readonly min: number; readonly max: number };
17
+ readonly clear?: readonly { readonly x: number; readonly z: number; readonly r: number }[];
18
+ readonly bound?: number; readonly minHeight?: number;
19
+ };
20
+ }
21
+ /** Generated pose rows retain their authored kind, variant and herd; materialization remains borrowed. */
22
+ export interface CreatureGroupSample<K extends string = string> { readonly kind: K; readonly variant: string | null; readonly herd: number; readonly x: number; readonly z: number; readonly yaw: number }
23
+ /** The engine services a group samples through: the caller's random stream and its ground (what `accept.minHeight` reads). */
24
+ export interface CreatureGroupStream { readonly next: () => number }
25
+ export interface CreatureGroupGround { readonly heightAt: (x: number, z: number) => number }
26
+ /** Sample in order from the caller's stream; rejection precedes yaw. */
27
+ export function sampleCreatureGroup<K extends string>(row: CreatureGroupSpec<K>, rng: CreatureGroupStream, ground?: CreatureGroupGround): CreatureGroupSample<K>[] {
28
+ const point = (p: { readonly x: number; readonly z: number }): boolean => Number.isFinite(p.x) && Number.isFinite(p.z);
29
+ const variant = (value: string | null): boolean => value === null || value.length > 0 && value.length <= 128;
30
+ const gate = row.accept, band = gate?.band, clear = gate?.clear ?? [], bound = gate?.bound, minHeight = gate?.minHeight;
31
+ if (!row.kind || row.kind.length > 128 || !Number.isSafeInteger(row.count) || row.count < 0 || row.count > 16 || !Number.isSafeInteger(row.herd) || row.herd < -1
32
+ || !variant(row.variant) || row.firstVariant !== undefined && !variant(row.firstVariant) || row.yaw !== undefined && !Number.isFinite(row.yaw)
33
+ || row.face !== undefined && (row.yaw !== undefined || !point(row.face))
34
+ || row.variants !== undefined && (row.variants.length !== row.count || row.variants.some(value => !variant(value)))
35
+ || band !== undefined && (!point(band) || !Number.isFinite(band.min) || !Number.isFinite(band.max) || band.min < 0 || band.max < band.min)
36
+ || clear.length > 16 || clear.some(c => !point(c) || !Number.isFinite(c.r) || c.r < 0)
37
+ || bound !== undefined && !(bound > 0) || minHeight !== undefined && (!Number.isFinite(minHeight) || ground === undefined)) throw new Error('Invalid creature sampling group');
38
+ const source = row.source;
39
+ let attempts = 1, ax = 1, az = 1, compass = false;
40
+ switch (source.kind) {
41
+ case 'indexed':
42
+ if (source.points.length > 1024 || source.points.length < row.count || source.points.some(p => !point(p))) throw new Error('Invalid indexed creature group');
43
+ break;
44
+ case 'radial':
45
+ attempts = source.attempts ?? 1; [ax, az] = source.axes ?? [1, 1]; compass = source.bearing === 'compass';
46
+ if (!point(source.centre) || !Number.isFinite(source.radius[0]) || !Number.isFinite(source.radius[1]) || source.radius[0] < 0 || source.radius[1] < source.radius[0]
47
+ || !Number.isSafeInteger(attempts) || attempts < 1 || attempts > 40 || !['linear', 'area'].includes(source.radiusLaw ?? 'linear')
48
+ || !['skip', 'centre'].includes(source.fallback ?? 'skip') || source.radiusLaw === 'area' && source.radius[0] !== 0
49
+ || !['math', 'compass'].includes(source.bearing ?? 'math') || !Number.isFinite(ax) || !Number.isFinite(az) || !(ax > 0) || !(az > 0)) throw new Error('Invalid radial creature group');
50
+ break;
51
+ default: throw new Error('Unknown creature sampling source');
52
+ }
53
+ const accepts = (x: number, z: number): boolean => {
54
+ if (band !== undefined) { const d = Math.hypot(x - band.x, z - band.z); if (d < band.min || d > band.max) return false; }
55
+ for (const c of clear) if (Math.hypot(x - c.x, z - c.z) < c.r) return false;
56
+ if (bound !== undefined && (Math.abs(x) > bound || Math.abs(z) > bound)) return false;
57
+ return minHeight === undefined || ground === undefined || !(ground.heightAt(x, z) < minHeight);
58
+ };
59
+ const samples: CreatureGroupSample<K>[] = [];
60
+ for (let index = 0; index < 16; index++) {
61
+ if (index >= row.count) break;
62
+ let x = 0, z = 0, accepted = false;
63
+ for (let attempt = 0; attempt < 40; attempt++) {
64
+ if (attempt >= attempts) break;
65
+ if (source.kind === 'indexed') {
66
+ const p = source.points[index]; if (p === undefined) throw new Error('Missing indexed creature point'); x = p.x; z = p.z;
67
+ } else {
68
+ const [r0, r1] = source.radius, angle = Math.PI * 2 * rng.next();
69
+ const radius = source.firstAtCentre === true && index === 0 && attempt === 0 ? 0 : source.radiusLaw === 'area' ? Math.sqrt(rng.next()) * r1 : r0 + (r1 - r0) * rng.next();
70
+ x = source.centre.x + (compass ? Math.sin(angle) : Math.cos(angle)) * ax * radius;
71
+ z = source.centre.z + (compass ? Math.cos(angle) : Math.sin(angle)) * az * radius;
72
+ }
73
+ if (!Number.isFinite(x) || !Number.isFinite(z)) throw new Error('Invalid sampled creature point');
74
+ if (accepts(x, z)) { accepted = true; break; }
75
+ }
76
+ if (!accepted) { if (source.kind !== 'radial' || source.fallback !== 'centre') continue; x = source.centre.x; z = source.centre.z; }
77
+ const yaw = row.face !== undefined ? Math.atan2(row.face.x - x, row.face.z - z) : row.yaw ?? Math.PI * 2 * rng.next();
78
+ if (!Number.isFinite(yaw)) throw new Error('Invalid sampled creature yaw');
79
+ samples.push({ kind: row.kind, variant: row.variants === undefined ? index === 0 && row.firstVariant !== undefined ? row.firstVariant : row.variant : row.variants[index] ?? null, x, z, yaw, herd: row.herd });
80
+ }
81
+ return samples;
82
+ }
83
+
84
+ /**
85
+ * Rank at most 1024 borrowed sites, keeping source order on tied scores. Range admission precedes the caller's
86
+ * score callback; greedy spacing follows ranking. Null rejects a site. No random stream or actor is owned here.
87
+ */
88
+ export function selectCreatureSites<T extends { readonly x: number; readonly z: number } | { readonly position: { readonly x: number; readonly z: number } }>(sites: readonly T[],
89
+ options: { readonly count: number; readonly origin?: { readonly x: number; readonly z: number }; readonly minDistance?: number; readonly maxDistance?: number; readonly separation?: number },
90
+ score: (site: T, index: number, distance: number) => number | null): { readonly site: T; readonly index: number }[] {
91
+ const point = (site: T): { readonly x: number; readonly z: number } => 'position' in site ? site.position : site;
92
+ const min = options.minDistance ?? 0, max = options.maxDistance ?? Infinity, gap = options.separation ?? 0, origin = options.origin;
93
+ if (sites.length > 1024 || !Number.isSafeInteger(options.count) || options.count < 0 || options.count > 16
94
+ || !Number.isFinite(min) || min < 0 || (options.maxDistance !== undefined && !Number.isFinite(max)) || max < min || !Number.isFinite(gap) || gap < 0
95
+ || (origin === undefined && (options.minDistance !== undefined || options.maxDistance !== undefined))
96
+ || (origin !== undefined && (!Number.isFinite(origin.x) || !Number.isFinite(origin.z)))
97
+ || sites.some(site => { const p = point(site); return !Number.isFinite(p.x) || !Number.isFinite(p.z); })) throw new RangeError('Invalid creature site selection');
98
+ const ranked: { site: T; index: number; score: number }[] = [];
99
+ for (let i = 0; i < 1024; i++) {
100
+ const site = sites[i]; if (site === undefined) break;
101
+ const p = point(site), distance = origin === undefined ? 0 : Math.hypot(p.x - origin.x, p.z - origin.z);
102
+ if (distance < min || distance > max) continue;
103
+ const value = score(site, i, distance);
104
+ if (value === null) continue;
105
+ if (!Number.isFinite(value)) throw new RangeError('Invalid creature site score');
106
+ ranked.push({ site, index: i, score: value });
107
+ }
108
+ ranked.sort((a, b) => b.score - a.score || a.index - b.index);
109
+ const selected: { site: T; index: number }[] = [];
110
+ for (let i = 0; i < 1024 && selected.length < options.count; i++) {
111
+ const row = ranked[i]; if (row === undefined) break;
112
+ const p = point(row.site);
113
+ if (selected.some(other => { const q = point(other.site); return Math.hypot(q.x - p.x, q.z - p.z) < gap; })) continue;
114
+ selected.push({ site: row.site, index: row.index });
115
+ }
116
+ return selected;
117
+ }
@@ -0,0 +1,67 @@
1
+ import { Document, NodeIO, type Accessor, type Node } from '@gltf-transform/core';
2
+ import { Matrix4, MeshStandardMaterial, type SkinnedMesh } from 'three';
3
+ import { parseGlb } from '../assets';
4
+
5
+ /** Uniform local TRS samples for the mesh root and each joint, in the declared skeleton order. */
6
+ export interface SampledSkinClip { name: string; times: Float32Array; root: { translation: Float32Array; rotation: Float32Array; scale: Float32Array }; joints: { translation: Float32Array; rotation: Float32Array; scale: Float32Array }[] }
7
+ /** Sample an existing pose closure at bounded cadence, including both endpoints; restore the mesh's initial joint pose afterward. */
8
+ export function sampleSkinClip(mesh: SkinnedMesh, name: string, duration: number, pose: (time: number, dt: number) => void, rate = 60): SampledSkinClip {
9
+ if (!/^[a-z][a-z0-9.-]*$/u.test(name) || !Number.isFinite(duration) || duration <= 0 || duration > 60 || !Number.isInteger(rate) || rate < 30 || rate > 120 || Math.ceil(duration * rate) > 4096) throw new Error('Skin clip sampling cap');
10
+ const bones = [mesh, ...mesh.skeleton.bones], rest = bones.map((bone) => ({ p: bone.position.clone(), q: bone.quaternion.clone(), s: bone.scale.clone() })), n = Math.ceil(duration * rate), times = new Float32Array(n + 1), joints = bones.map(() => ({ translation: new Float32Array((n + 1) * 3), rotation: new Float32Array((n + 1) * 4), scale: new Float32Array((n + 1) * 3) }));
11
+ try {
12
+ for (let frame = 0; frame <= n; frame++) {
13
+ const time = frame * duration / n; times[frame] = time; pose(time, frame === 0 ? 0 : duration / n); mesh.updateMatrixWorld(true);
14
+ bones.forEach((bone, i) => { const joint = joints[i]; if (joint === undefined) throw new Error('Missing sampled joint');
15
+ joint.translation.set(bone.position.toArray(), frame * 3); joint.scale.set(bone.scale.toArray(), frame * 3);
16
+ const q = bone.quaternion.toArray(), previous = frame * 4 - 4;
17
+ const sign = frame > 0 && q.reduce((sum, value, c) => sum + value * (joint.rotation[previous + c] ?? 0), 0) < 0 ? -1 : 1;
18
+ joint.rotation.set(q.map((value) => value * sign), frame * 4);
19
+ });
20
+ }
21
+ } finally { bones.forEach((bone, i) => { const value = rest[i]; if (value !== undefined) { bone.position.copy(value.p); bone.quaternion.copy(value.q); bone.scale.copy(value.s); } }); mesh.updateMatrixWorld(true); }
22
+ const root = joints[0]; if (root === undefined) throw new Error('Missing sampled root');
23
+ return { name, times, root, joints: joints.slice(1) };
24
+ }
25
+ /** Deterministic self-contained GLB of actual geometry, joint order, weights, inverse binds and sampled clips (constant channels keep only their endpoints); textures stay external KTX2 declarations. */
26
+ export async function skinnedGlb(mesh: SkinnedMesh, clips: readonly SampledSkinClip[], name = 'baked-skin'): Promise<Uint8Array> {
27
+ const bones = mesh.skeleton.bones;
28
+ if (bones.length === 0 || bones.length > 128 || new Set(bones.map((bone) => bone.name)).size !== bones.length || bones.some((bone) => !/^[A-Za-z][A-Za-z0-9_.-]*$/u.test(bone.name)) || clips.length > 32 || new Set(clips.map((clip) => clip.name)).size !== clips.length) throw new Error('Skin joints or clips cap');
29
+ mesh.updateMatrixWorld(true);
30
+ const doc = new Document(), buffer = doc.createBuffer(), scene = doc.createScene(name), root = doc.createNode(name).setTranslation(mesh.position.toArray()).setRotation(mesh.quaternion.toArray()).setScale(mesh.scale.toArray()); scene.addChild(root); doc.getRoot().setDefaultScene(scene);
31
+ const accessor = (values: Float32Array | Uint16Array | Uint32Array, type: Parameters<Accessor['setType']>[0]) => { if (values.length === 0 || values.some((value) => !Number.isFinite(value))) throw new Error('Finite skin accessor required'); return doc.createAccessor().setType(type).setArray(values instanceof Uint16Array ? new Uint16Array(values) : values instanceof Uint32Array ? new Uint32Array(values) : new Float32Array(values)).setBuffer(buffer); };
32
+ const nodes: Node[] = bones.map((bone) => doc.createNode(bone.name).setTranslation(bone.position.toArray()).setRotation(bone.quaternion.toArray()).setScale(bone.scale.toArray()));
33
+ bones.forEach((bone, i) => { const node = nodes[i]; if (node === undefined) throw new Error('Missing joint'); const parent = bones.findIndex((candidate) => candidate.uuid === bone.parent?.uuid); if (parent === -1) { if (bone.parent !== mesh) throw new Error('Joint hierarchy must belong to the mesh'); root.addChild(node); } else { const owner = nodes[parent]; if (owner === undefined) throw new Error('Missing parent joint'); owner.addChild(node); } });
34
+ const skin = doc.createSkin(name); for (const node of nodes) skin.addJoint(node);
35
+ const inverse = new Float32Array(bones.length * 16); bones.forEach((_bone, i) => { const matrix = mesh.skeleton.boneInverses[i]; if (matrix === undefined) throw new Error('Missing inverse bind'); inverse.set(new Matrix4().multiplyMatrices(matrix, mesh.bindMatrix).elements, i * 16); }); skin.setInverseBindMatrices(accessor(inverse, 'MAT4')); root.setSkin(skin);
36
+ const geometry = mesh.geometry, position = geometry.getAttribute('position'); if (!geometry.hasAttribute('position') || position.count > 400000) throw new Error('Skin geometry cap');
37
+ const attrs = new Map<string, Accessor>();
38
+ for (const [key, semantic, width] of [['position', 'POSITION', 3], ['normal', 'NORMAL', 3], ['uv', 'TEXCOORD_0', 2], ['color', 'COLOR_0', 3], ['skinIndex', 'JOINTS_0', 4], ['skinWeight', 'WEIGHTS_0', 4]] as const) {
39
+ if (!geometry.hasAttribute(key)) { if (key === 'skinIndex' || key === 'skinWeight') throw new Error('Missing skin weights'); continue; }
40
+ const attr = geometry.getAttribute(key); if (attr.count !== position.count || attr.itemSize !== width) throw new Error('Skin attribute shape');
41
+ const values = Array.from({ length: attr.count * width }, (_, i) => attr.getComponent(Math.floor(i / width), i % width));
42
+ if (key === 'skinIndex' && values.some((value) => !Number.isInteger(value) || value < 0 || value >= bones.length)) throw new Error('Skin joint index');
43
+ attrs.set(semantic, accessor(key === 'skinIndex' ? Uint16Array.from(values) : Float32Array.from(values), width === 4 ? 'VEC4' : width === 3 ? 'VEC3' : 'VEC2'));
44
+ }
45
+ const index = geometry.getIndex(), indices = index === null ? Array.from({ length: position.count }, (_, i) => i) : Array.from(index.array), groups = geometry.groups.length === 0 ? [{ start: 0, count: indices.length, materialIndex: 0 }] : geometry.groups;
46
+ if (indices.some((i) => !Number.isInteger(i) || i < 0 || i >= position.count) || indices.length % 3 !== 0) throw new Error('Skin triangle indices');
47
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material], output = doc.createMesh(name);
48
+ for (const group of groups) {
49
+ const mat = materials[group.materialIndex ?? 0]; if (!(mat instanceof MeshStandardMaterial) || mat.map !== null || mat.normalMap !== null || mat.alphaMap !== null || mat.roughnessMap !== null || mat.metalnessMap !== null) throw new Error('Skin material requires external KTX2 bindings');
50
+ const material = doc.createMaterial(mat.name).setBaseColorFactor([mat.color.r, mat.color.g, mat.color.b, mat.opacity]).setMetallicFactor(mat.metalness).setRoughnessFactor(mat.roughness).setDoubleSided(mat.side === 2), primitive = doc.createPrimitive().setMaterial(material).setIndices(accessor(Uint32Array.from(indices.slice(group.start, group.start + group.count)), 'SCALAR'));
51
+ for (const [semantic, a] of attrs) primitive.setAttribute(semantic, a); output.addPrimitive(primitive);
52
+ }
53
+ root.setMesh(output).setExtras({ castShadow: mesh.castShadow });
54
+ for (const clip of clips) {
55
+ if (clip.joints.length !== bones.length || clip.times.length < 2 || clip.times.length > 4097) throw new Error('Skin clip shape');
56
+ const animation = doc.createAnimation(clip.name), times = accessor(clip.times, 'SCALAR');
57
+ [clip.root, ...clip.joints].forEach((joint, i) => { const node = i === 0 ? root : nodes[i - 1]; if (node === undefined) throw new Error('Missing animation joint');
58
+ for (const path of ['translation', 'rotation', 'scale'] as const) { const values = joint[path], width = path === 'rotation' ? 4 : 3; if (values.length !== clip.times.length * width) throw new Error('Skin clip channel shape');
59
+ const constant = values.every((value, componentIndex) => value === values[componentIndex % width]);
60
+ const input = constant ? accessor(Float32Array.of(clip.times[0] ?? 0, clip.times.at(-1) ?? 0), 'SCALAR') : times;
61
+ const channelValues = constant ? Float32Array.from([...values.slice(0, width), ...values.slice(0, width)]) : values;
62
+ const sampler = doc.createAnimationSampler().setInput(input).setOutput(accessor(channelValues, width === 4 ? 'VEC4' : 'VEC3')).setInterpolation('LINEAR'); animation.addSampler(sampler).addChannel(doc.createAnimationChannel().setSampler(sampler).setTargetNode(node).setTargetPath(path));
63
+ }
64
+ });
65
+ }
66
+ const bytes = await new NodeIO().writeBinary(doc); parseGlb(bytes); return bytes;
67
+ }
@@ -0,0 +1,379 @@
1
+ /** Offline face paint, deformation, AO and culling. No view or material is constructed. */
2
+ import * as THREE from 'three';
3
+ import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
4
+ import { Rng } from '../random';
5
+ import { voxelAO, aoTint, hemisphere, addVoxelAOBake } from '@wildshard/engine/world/voxelAO';
6
+ import { bakedGeometry } from '@wildshard/engine/world/geometryBake';
7
+
8
+ /** Compile an offline geometry through the native scoped bake/recorder protocol.
9
+ * IDs, quantized keys, owned cache copies and complete RNG continuation stay native. */
10
+ export function bakeCachedGeometry(...args: Parameters<typeof bakedGeometry>): ReturnType<typeof bakedGeometry> { return bakedGeometry(...args); }
11
+
12
+ /** Compile ordered offline hemisphere rays with the native ring arithmetic. */
13
+ export function bakeOcclusionDirections(...args: Parameters<typeof hemisphere>): ReturnType<typeof hemisphere> { return hemisphere(...args); }
14
+
15
+ /** Bake native face, welded-position or vertex occlusion over caller-owned geometry.
16
+ * Bounds, ground callbacks, recorder keys and scoped cache loans retain their defining law. */
17
+ export function bakeVoxelOcclusion(...args: Parameters<typeof voxelAO>): ReturnType<typeof voxelAO> { return voxelAO(...args); }
18
+
19
+ /** Apply native occlusion to the supplied colour attribute, preserving other channels. */
20
+ export function bakeOcclusionTint(...args: Parameters<typeof aoTint>): void { aoTint(...args); }
21
+
22
+ function wobble(g: THREE.BufferGeometry, amp: number, rng: Pick<Rng, 'range'>): void {
23
+ const pos = g.getAttribute('position');
24
+ const seen = new Map<string, [number, number, number]>();
25
+ for (let i = 0; i < pos.count; i++) {
26
+ const key = `${pos.getX(i).toFixed(4)},${pos.getY(i).toFixed(4)},${pos.getZ(i).toFixed(4)}`;
27
+ let d = seen.get(key);
28
+ if (!d) { d = [rng.range(-amp, amp), rng.range(-amp, amp), rng.range(-amp, amp)]; seen.set(key, d); }
29
+ pos.setXYZ(i, pos.getX(i) + d[0], pos.getY(i) + d[1], pos.getZ(i) + d[2]);
30
+ }
31
+ pos.needsUpdate = true;
32
+ }
33
+ function swayByHeight(g: THREE.BufferGeometry, w: number, y0: number, y1: number, phase: number): void {
34
+ const pos = g.getAttribute('position'), a = new Float32Array(pos.count * 2), span = y1 - y0 || 1;
35
+ for (let i = 0; i < pos.count; i++) { a[i * 2] = w * Math.min(1, Math.max(0, (pos.getY(i) - y0) / span)); a[i * 2 + 1] = phase; }
36
+ g.setAttribute('aSway', new THREE.BufferAttribute(a, 2));
37
+ }
38
+
39
+ export type ColorLike = THREE.Color | string;
40
+
41
+ const tmpColor = new THREE.Color();
42
+ const asColor = (c: ColorLike): THREE.Color => (typeof c === 'string' ? tmpColor.set(c) : c);
43
+
44
+ export interface FacetedPartOptions {
45
+ /** per-face lightness jitter, ± fraction (default 0.06) */
46
+ jitter?: number;
47
+ /** applied to the geometry before it is merged */
48
+ matrix?: THREE.Matrix4;
49
+ /** random per-vertex displacement in metres (hand-cut look; default 0) — applied before the matrix */
50
+ wobble?: number;
51
+ /** sways in the shared wind (M5, wind.ts): weight `w` (~1 = cloth), rising with height from the part's base — or, with
52
+ * `hang`, from its top down (a sail, a banner, weed hanging off a rail). Meshes with swaying parts want
53
+ * a sway-patched `mesh.customDepthMaterial` so their shadows move too. */
54
+ sway?: { w: number; phase?: number; hang?: boolean; /** absolute (post-matrix) y where the weight is 0 → where it reaches w (a sail built from many quads) */ span?: [number, number] };
55
+ }
56
+
57
+ export class FacetedGeometryBuilder {
58
+ readonly rng: Rng;
59
+ private parts: THREE.BufferGeometry[] = [];
60
+
61
+ constructor(seed: number) { this.rng = new Rng(seed); }
62
+
63
+ /** add a geometry painted one colour (per-face jitter); the input is consumed */
64
+ add(g: THREE.BufferGeometry, col: ColorLike, opts: FacetedPartOptions = {}): void {
65
+ const jitter = opts.jitter ?? 0.06;
66
+ if (g.hasAttribute('uv')) g.deleteAttribute('uv');
67
+ if (g.hasAttribute('normal')) g.deleteAttribute('normal');
68
+ if (g.hasAttribute('color')) g.deleteAttribute('color');
69
+ if (opts.wobble !== undefined && opts.wobble > 0) wobble(g, opts.wobble, this.rng);
70
+ const ni = g.index ? g.toNonIndexed() : g;
71
+ if (ni !== g) g.dispose();
72
+ if (opts.matrix) ni.applyMatrix4(opts.matrix);
73
+ const c = asColor(col), r = c.r, gg = c.g, b = c.b;
74
+ const n = ni.getAttribute('position').count, out = new Float32Array(n * 3);
75
+ for (let i = 0; i < n; i += 3) {
76
+ const k = 1 - jitter + this.rng.next() * jitter * 2;
77
+ for (let j = 0; j < 3; j++) { const o = (i + j) * 3; out[o] = r * k; out[o + 1] = gg * k; out[o + 2] = b * k; }
78
+ }
79
+ ni.setAttribute('color', new THREE.BufferAttribute(out, 3));
80
+ if (opts.sway) this.sway(ni, opts.sway);
81
+ this.parts.push(ni);
82
+ }
83
+
84
+ private sway(g: THREE.BufferGeometry, sw: NonNullable<FacetedPartOptions['sway']>): void {
85
+ g.computeBoundingBox();
86
+ const bb = g.boundingBox;
87
+ if (!bb) return;
88
+ const phase = sw.phase ?? this.rng.range(0, Math.PI * 2);
89
+ if (sw.span) swayByHeight(g, sw.w, sw.span[0], sw.span[1], phase);
90
+ else if (sw.hang) swayByHeight(g, sw.w, bb.max.y, bb.min.y, phase); else swayByHeight(g, sw.w, bb.min.y, bb.max.y, phase);
91
+ }
92
+
93
+ /**
94
+ * add a geometry painted by facing: faces whose (post-matrix) normal points up past `minY` take `top` (moss on a rock,
95
+ * grass on a ledge, sand on a step), the rest `side`; per-face jitter as `add`. The input is consumed.
96
+ */
97
+ addTopped(g: THREE.BufferGeometry, side: ColorLike, top: ColorLike, opts: FacetedPartOptions & { minY?: number } = {}): void {
98
+ const jitter = opts.jitter ?? 0.06, minY = opts.minY ?? 0.55;
99
+ if (g.hasAttribute('uv')) g.deleteAttribute('uv');
100
+ if (g.hasAttribute('normal')) g.deleteAttribute('normal');
101
+ if (g.hasAttribute('color')) g.deleteAttribute('color');
102
+ if (opts.wobble !== undefined && opts.wobble > 0) wobble(g, opts.wobble, this.rng);
103
+ const ni = g.index ? g.toNonIndexed() : g;
104
+ if (ni !== g) g.dispose();
105
+ if (opts.matrix) ni.applyMatrix4(opts.matrix);
106
+ const s = asColor(side).clone(), t = asColor(top).clone();
107
+ const pos = ni.getAttribute('position'), n = pos.count, out = new Float32Array(n * 3);
108
+ const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
109
+ for (let i = 0; i < n; i += 3) {
110
+ a.fromBufferAttribute(pos, i); b.fromBufferAttribute(pos, i + 1); c.fromBufferAttribute(pos, i + 2);
111
+ b.sub(a); c.sub(a); b.cross(c).normalize();
112
+ const col = b.y > minY ? t : s, k = 1 - jitter + this.rng.next() * jitter * 2;
113
+ for (let j = 0; j < 3; j++) { const o = (i + j) * 3; out[o] = col.r * k; out[o + 1] = col.g * k; out[o + 2] = col.b * k; }
114
+ }
115
+ ni.setAttribute('color', new THREE.BufferAttribute(out, 3));
116
+ this.parts.push(ni);
117
+ }
118
+
119
+ /** add several [geometry, colour] parts (a plant, a statue) under one matrix */
120
+ addParts(parts: [THREE.BufferGeometry, ColorLike][], opts: FacetedPartOptions = {}): void {
121
+ for (const [g, c] of parts) this.add(g, c, opts);
122
+ }
123
+
124
+ /** add a geometry that already carries a `color` attribute (non-indexed or indexed) */
125
+ addPainted(g: THREE.BufferGeometry, matrix?: THREE.Matrix4): void {
126
+ if (g.hasAttribute('uv')) g.deleteAttribute('uv');
127
+ if (g.hasAttribute('normal')) g.deleteAttribute('normal');
128
+ const ni = g.index ? g.toNonIndexed() : g;
129
+ if (matrix) ni.applyMatrix4(matrix);
130
+ this.parts.push(ni);
131
+ }
132
+
133
+ get triangleCount(): number { let n = 0; for (const p of this.parts) n += p.getAttribute('position').count / 3; return n; }
134
+
135
+ /** merge everything, flat normals, optional AO bake; the kit is empty afterwards. `hidden` drops the faces no one can
136
+ * see (inside another closed part, or buried: hiddenFaces.ts) after the AO bake, so the kept faces bake as before. */
137
+ finish(opts: { ao?: FacetedAOOptions | false; hidden?: FacetedHiddenOptions } = {}): THREE.BufferGeometry {
138
+ // read before the still parts take a zero aSway: a swaying part never hides another
139
+ const hidden = opts.hidden === undefined ? null : hiddenTriangles(this.parts, opts.hidden);
140
+ // the parts must share their attributes to merge: if any part sways, the still ones get a zero aSway
141
+ if (this.parts.some((p) => p.hasAttribute('aSway'))) for (const p of this.parts) if (!p.hasAttribute('aSway')) p.setAttribute('aSway', new THREE.BufferAttribute(new Float32Array(p.getAttribute('position').count * 2), 2));
142
+ let geo = mergeGeometries(this.parts, false);
143
+ for (const p of this.parts) p.dispose();
144
+ this.parts = [];
145
+ geo.computeVertexNormals(); // non-indexed → flat per-face normals
146
+ if (opts.ao !== false) bakeFacetedAO(geo, opts.ao ?? {});
147
+ if (hidden !== null) {
148
+ const flags = new Uint8Array(hidden.reduce((n, part) => n + part.length, 0));
149
+ let at = 0;
150
+ for (const part of hidden) { flags.set(part, at); at += part.length; }
151
+ geo = dropTriangles(geo, flags);
152
+ }
153
+ geo.computeBoundingSphere();
154
+ geo.computeBoundingBox();
155
+ return geo;
156
+ }
157
+ }
158
+
159
+ /** Structural paint sink accepted by higher-level author recipes; no private builder state is borrowed. */
160
+ export type FacetedGeometrySink = Pick<FacetedGeometryBuilder, 'rng' | 'add' | 'addTopped' | 'addParts' | 'addPainted' | 'finish'>;
161
+
162
+ export interface FacetedAOOptions {
163
+ /** terrain height under (x, z) in the geometry's space — cells below it are solid (ground contact AO) */
164
+ ground?: (x: number, z: number) => number;
165
+ /** a constant floor instead of `ground` (creatures / props built at the origin) */
166
+ floorY?: number;
167
+ /** occupancy cell size in metres (default: fit the bbox into ~72 cells on the longest axis, ≥ 0.12) */
168
+ cell?: number;
169
+ /** ray length in metres (default 6 cells) */
170
+ dist?: number;
171
+ /** 0..1 how dark a fully occluded face goes (default 0.62) */
172
+ strength?: number;
173
+ /** colour a fully occluded face is pulled toward (a cool shadow, default a dusky violet) */
174
+ tint?: ColorLike;
175
+ /** faces pointing down lose this much extra light (sky occlusion by orientation, default 0.18) */
176
+ downDark?: number;
177
+ }
178
+
179
+ // 14 hemisphere directions in a +Z-up tangent frame (cosine-ish spread, fixed so bakes are deterministic)
180
+ const HEMI = hemisphere([[0.95, 1], [0.72, 5], [0.38, 8]], 1.7);
181
+
182
+ /**
183
+ * Darken each face of a non-indexed, vertex-coloured geometry by how enclosed it is (the one `voxelAO`, per face). Works
184
+ * in the geometry's own coordinate space (world for placed props, local for creatures).
185
+ */
186
+ function bakeFacetedAO(geo: THREE.BufferGeometry, o: FacetedAOOptions = {}): void {
187
+ if (!geo.hasAttribute('color') || geo.index !== null) return;
188
+ geo.computeBoundingBox();
189
+ const bb = geo.boundingBox;
190
+ if (bb === null) return;
191
+ const ext = new THREE.Vector3().subVectors(bb.max, bb.min);
192
+ const cell = o.cell ?? Math.max(0.12, Math.max(ext.x, ext.y, ext.z) / 72);
193
+ const { ground, floorY } = o;
194
+ const dist = o.dist ?? cell * 6;
195
+ const tint = new THREE.Color().copy(asColor(o.tint ?? '#4a4466'));
196
+ if (!geo.hasAttribute('normal')) geo.computeVertexNormals();
197
+ const k = voxelAO(geo, {
198
+ box: bb, cell, pad: 2, spacing: 0.7, maxSamples: 400, indexed: false,
199
+ ...(ground ? { ground: { columns: ground } } : floorY !== undefined ? { ground: { columns: () => floorY } } : {}),
200
+ sample: 'face', offset: 1.05, hemi: HEMI, steps: Math.max(3, Math.round(dist / cell)), stepLen: cell, falloff: 0.5,
201
+ strength: o.strength ?? 0.62, downDark: o.downDark ?? 0.18,
202
+ });
203
+ aoTint(geo.getAttribute('color'), k, tint);
204
+ }
205
+
206
+
207
+
208
+ /**
209
+ * Faces nobody can see, found at bake time (T8: Driftwood's over-cap tiles). A merged low-poly model is a heap of closed
210
+ * parts: crag boulders piled into one another, planks lapped over their neighbours, steps standing on steps. A triangle
211
+ * whose three corners lie inside one other closed part (behind every one of its face planes) is inside that solid, since
212
+ * the region behind all of a closed mesh's planes is convex and lies within it; one resting on such a part's face and
213
+ * turned into it is covered by that face, as is one two closed parts share face to face (a plank's end on the next
214
+ * plank's). A triangle wholly under the terrain is buried. Dropping them leaves every visible pixel as it was.
215
+ * `LowPolyKit.finish({ hidden })` reads this after its AO bake, so the colours the kept faces bake are the ones they
216
+ * always had.
217
+ *
218
+ * A part counts as an occluder only when it is watertight (every edge shared by exactly two of its triangles) and does
219
+ * not sway; parts are non-indexed, world-space triangle soups (the kit's own form).
220
+ */
221
+ export interface FacetedHiddenOptions {
222
+ /** the terrain height under (x, z): triangles wholly below it by `margin` are buried */
223
+ readonly ground?: (x: number, z: number) => number;
224
+ /** metres below the ground a buried triangle's corners, edge midpoints and centre must all sit (default 0.25) */
225
+ readonly margin?: number;
226
+ }
227
+
228
+ /** metres: a corner this close to a plane is on it */
229
+ const ON = 1e-3;
230
+ /** the occluder lookup grid's cell (m, x / z) */
231
+ const CELL = 2;
232
+
233
+ interface Occluder { readonly part: number; readonly min: THREE.Vector3; readonly max: THREE.Vector3; readonly planes: Float64Array; readonly faces: readonly string[] }
234
+
235
+ /** a triangle's corners in winding order from its smallest corner (the reverse winding reads as the touching face's) */
236
+ const faceKey = (k: readonly string[], reverse: boolean): string => {
237
+ const order = reverse ? [k[0] ?? '', k[2] ?? '', k[1] ?? ''] : [k[0] ?? '', k[1] ?? '', k[2] ?? ''];
238
+ let start = 0;
239
+ for (let i = 1; i < 3; i++) if ((order[i] ?? '') < (order[start] ?? '')) start = i;
240
+ return `${order[start] ?? ''}|${order[(start + 1) % 3] ?? ''}|${order[(start + 2) % 3] ?? ''}`;
241
+ };
242
+
243
+ function occluder(g: THREE.BufferGeometry, part: number): Occluder | null {
244
+ const p = g.getAttribute('position').array, n = p.length / 9;
245
+ if (n < 4 || g.hasAttribute('aSway')) return null;
246
+ const key = (i: number): string => `${Math.round((p[i] ?? 0) * 1e4)},${Math.round((p[i + 1] ?? 0) * 1e4)},${Math.round((p[i + 2] ?? 0) * 1e4)}`;
247
+ const edges = new Map<string, number>(), faces: string[] = [];
248
+ for (let t = 0; t < n; t++) {
249
+ const k = [key(t * 9), key(t * 9 + 3), key(t * 9 + 6)];
250
+ faces.push(faceKey(k, false));
251
+ for (let e = 0; e < 3; e++) {
252
+ const a = k[e] ?? '', b = k[(e + 1) % 3] ?? '';
253
+ if (a === b) continue;
254
+ const edge = a < b ? `${a}|${b}` : `${b}|${a}`;
255
+ edges.set(edge, (edges.get(edge) ?? 0) + 1);
256
+ }
257
+ }
258
+ for (const uses of edges.values()) if (uses !== 2) return null;
259
+ const planes: number[] = [], min = new THREE.Vector3(Infinity, Infinity, Infinity), max = new THREE.Vector3(-Infinity, -Infinity, -Infinity);
260
+ const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
261
+ let volume = 0;
262
+ for (let t = 0; t < n; t++) {
263
+ a.fromArray(p, t * 9); b.fromArray(p, t * 9 + 3); c.fromArray(p, t * 9 + 6);
264
+ min.min(a).min(b).min(c); max.max(a).max(b).max(c);
265
+ volume += a.dot(b.clone().cross(c));
266
+ b.sub(a); c.sub(a); b.cross(c);
267
+ const length = b.length();
268
+ if (length < 1e-9) continue;
269
+ b.divideScalar(length);
270
+ planes.push(b.x, b.y, b.z, b.dot(a));
271
+ }
272
+ // inward-wound (or inside-out) parts are not trusted as solids
273
+ return volume > 0 ? { part, min, max, planes: Float64Array.from(planes), faces } : null;
274
+ }
275
+
276
+ /** Whether triangle (a, b, c) with unit normal `normal` is inside `o`, or on one of its faces and turned into it. */
277
+ function covered(o: Occluder, corners: Float32Array | Float64Array, at: number, normal: THREE.Vector3): boolean {
278
+ for (let j = 0; j < 3; j++) {
279
+ const x = corners[at + j * 3] ?? 0, y = corners[at + j * 3 + 1] ?? 0, z = corners[at + j * 3 + 2] ?? 0;
280
+ if (x < o.min.x - ON || y < o.min.y - ON || z < o.min.z - ON || x > o.max.x + ON || y > o.max.y + ON || z > o.max.z + ON) return false;
281
+ }
282
+ const pl = o.planes;
283
+ for (let i = 0; i < pl.length; i += 4) {
284
+ const nx = pl[i] ?? 0, ny = pl[i + 1] ?? 0, nz = pl[i + 2] ?? 0, d = pl[i + 3] ?? 0;
285
+ let far = -Infinity, near = Infinity;
286
+ for (let j = 0; j < 3; j++) {
287
+ const s = nx * (corners[at + j * 3] ?? 0) + ny * (corners[at + j * 3 + 1] ?? 0) + nz * (corners[at + j * 3 + 2] ?? 0) - d;
288
+ far = Math.max(far, s); near = Math.min(near, s);
289
+ }
290
+ if (far > ON) return false;
291
+ // lying in this face's plane: only a triangle facing into the solid is covered by it (one facing out would show)
292
+ if (near > -ON && nx * normal.x + ny * normal.y + nz * normal.z > -0.999) return false;
293
+ }
294
+ return true;
295
+ }
296
+
297
+ /** Per part, 1 for each triangle no viewpoint outside the solids and above the ground can see. */
298
+ function hiddenTriangles(parts: readonly THREE.BufferGeometry[], options: FacetedHiddenOptions = {}): Uint8Array[] {
299
+ const grid = new Map<string, Occluder[]>(), cell = (x: number, z: number): string => `${Math.floor(x / CELL)},${Math.floor(z / CELL)}`;
300
+ // the faces of the closed parts, by winding: a face another closed part shares reversed lies between the two solids
301
+ const faces = new Map<string, number>(), solid: (Occluder | null)[] = [];
302
+ parts.forEach((g, part) => {
303
+ const o = occluder(g, part);
304
+ solid.push(o);
305
+ if (o === null) return;
306
+ for (const face of o.faces) faces.set(face, faces.has(face) && faces.get(face) !== part ? -1 : part);
307
+ for (let gx = Math.floor(o.min.x / CELL); gx <= Math.floor(o.max.x / CELL); gx++) for (let gz = Math.floor(o.min.z / CELL); gz <= Math.floor(o.max.z / CELL); gz++) {
308
+ const k = `${gx},${gz}`, list = grid.get(k);
309
+ if (list === undefined) grid.set(k, [o]); else list.push(o);
310
+ }
311
+ });
312
+ const { ground } = options, margin = options.margin ?? 0.25;
313
+ const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3(), normal = new THREE.Vector3();
314
+ const buried = (): boolean => {
315
+ if (ground === undefined) return false;
316
+ const below = (x: number, y: number, z: number): boolean => y < ground(x, z) - margin;
317
+ return below(a.x, a.y, a.z) && below(b.x, b.y, b.z) && below(c.x, c.y, c.z)
318
+ && below((a.x + b.x) / 2, (a.y + b.y) / 2, (a.z + b.z) / 2) && below((b.x + c.x) / 2, (b.y + c.y) / 2, (b.z + c.z) / 2)
319
+ && below((c.x + a.x) / 2, (c.y + a.y) / 2, (c.z + a.z) / 2) && below((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3, (a.z + b.z + c.z) / 3);
320
+ };
321
+ return parts.map((g, part) => {
322
+ const p = g.getAttribute('position').array, n = p.length / 9, out = new Uint8Array(n);
323
+ if (!(p instanceof Float32Array)) return out;
324
+ for (let t = 0; t < n; t++) {
325
+ a.fromArray(p, t * 9); b.fromArray(p, t * 9 + 3); c.fromArray(p, t * 9 + 6);
326
+ if (buried()) { out[t] = 1; continue; }
327
+ normal.subVectors(c, a).cross(b.clone().sub(a)).negate();
328
+ const length = normal.length();
329
+ if (length < 1e-12) continue;
330
+ normal.divideScalar(length);
331
+ const own = solid[part]?.faces[t];
332
+ if (own !== undefined) {
333
+ const touching = faces.get(faceKey(own.split('|'), true));
334
+ if (touching !== undefined && touching !== part) { out[t] = 1; continue; }
335
+ }
336
+ for (const o of grid.get(cell(a.x, a.z)) ?? []) if (o.part !== part && covered(o, p, t * 9, normal)) { out[t] = 1; break; }
337
+ }
338
+ return out;
339
+ });
340
+ }
341
+
342
+ /** `geometry` without the triangles `hidden` marks (non-indexed; every attribute kept per remaining vertex). */
343
+ function dropTriangles(geometry: THREE.BufferGeometry, hidden: Uint8Array): THREE.BufferGeometry {
344
+ const triangles = geometry.getAttribute('position').count / 3;
345
+ let kept = 0;
346
+ for (let t = 0; t < triangles; t++) if (hidden[t] !== 1) kept++;
347
+ if (kept === triangles) return geometry;
348
+ const out = new THREE.BufferGeometry();
349
+ for (const [name, attribute] of Object.entries(geometry.attributes)) {
350
+ if (!(attribute instanceof THREE.BufferAttribute)) throw new Error(`Interleaved attribute ${name} cannot drop triangles`);
351
+ const size = attribute.itemSize * 3, source = attribute.array, array = source.slice(0, kept * size);
352
+ for (let t = 0, at = 0; t < triangles; t++) if (hidden[t] !== 1) { array.set(source.subarray(t * size, (t + 1) * size), at); at += size; }
353
+ out.setAttribute(name, new THREE.BufferAttribute(array, attribute.itemSize, attribute.normalized));
354
+ }
355
+ out.userData = geometry.userData;
356
+ geometry.dispose();
357
+ return out;
358
+ }
359
+
360
+ /** Cull finished non-indexed parts against each other and an explicit optional ground.
361
+ * Unchanged parts retain identity; replaced parts are consumed. All retained attribute bits,
362
+ * normalized flags and userData ownership survive in original part/triangle order. */
363
+ export function cullFacetedParts(parts: readonly THREE.BufferGeometry[], options: FacetedHiddenOptions = {}): THREE.BufferGeometry[] {
364
+ const hidden = hiddenTriangles(parts, options);
365
+ return parts.map((geometry, i) => dropTriangles(geometry, hidden[i] ?? new Uint8Array(0)));
366
+ }
367
+
368
+ /** Compile synchronously with a private copy of a committed native AO table.
369
+ * Nested scopes retain prior entries; the new entries are released after success or failure.
370
+ * Malformed tables keep the native fallback march. Thenable results refuse. */
371
+ export function withFacetedAO<T>(bytes: Uint8Array, compile: () => T): T {
372
+ const owned = Uint8Array.from(bytes), release = addVoxelAOBake(owned.buffer);
373
+ try {
374
+ const result = compile();
375
+ if (result !== null && (typeof result === 'object' || typeof result === 'function') && 'then' in result && typeof result.then === 'function')
376
+ throw new TypeError('Faceted AO compilation must be synchronous');
377
+ return result;
378
+ } finally { release(); }
379
+ }