@wildshard/sdk 0.0.1 → 0.2.4

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 (688) hide show
  1. package/GUIDE.md +895 -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 +47 -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 +39 -0
  358. package/src/cli/bin.mjs +8 -0
  359. package/src/cli/delete/delete.ts +258 -0
  360. package/src/cli/help.ts +204 -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 +291 -0
  365. package/src/cli/report.ts +20 -0
  366. package/src/cli/shardfile/command.ts +49 -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/agentFiles.ts +127 -0
  394. package/src/sharddev/arenaView.ts +15 -0
  395. package/src/sharddev/as/groupBankV2.ts +36 -0
  396. package/src/sharddev/as/groupStepV2.ts +13 -0
  397. package/src/sharddev/as/ws.ts +30 -0
  398. package/src/sharddev/as/wsV2.ts +180 -0
  399. package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
  400. package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
  401. package/src/sharddev/assetHandle.ts +84 -0
  402. package/src/sharddev/assetOwner.ts +70 -0
  403. package/src/sharddev/assetScope.ts +30 -0
  404. package/src/sharddev/assets.ts +21 -0
  405. package/src/sharddev/audio.ts +9 -0
  406. package/src/sharddev/audioEncode.ts +211 -0
  407. package/src/sharddev/author.ts +3 -0
  408. package/src/sharddev/authorError.ts +28 -0
  409. package/src/sharddev/authorManifest.ts +39 -0
  410. package/src/sharddev/bake/annulus.ts +19 -0
  411. package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
  412. package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
  413. package/src/sharddev/bake/authoredWorld.ts +201 -0
  414. package/src/sharddev/bake/basisEncoder.ts +95 -0
  415. package/src/sharddev/bake/basisGlb.ts +85 -0
  416. package/src/sharddev/bake/basisTool.ts +74 -0
  417. package/src/sharddev/bake/basisToolInputs.ts +476 -0
  418. package/src/sharddev/bake/byteCodec.ts +33 -0
  419. package/src/sharddev/bake/canvasAtlas.ts +406 -0
  420. package/src/sharddev/bake/coarseCopy.ts +59 -0
  421. package/src/sharddev/bake/colliders.ts +87 -0
  422. package/src/sharddev/bake/compactGlb.ts +224 -0
  423. package/src/sharddev/bake/compileScript.ts +119 -0
  424. package/src/sharddev/bake/compileScriptV2.ts +75 -0
  425. package/src/sharddev/bake/contactRows.ts +84 -0
  426. package/src/sharddev/bake/creaturePlacement.ts +117 -0
  427. package/src/sharddev/bake/export.ts +67 -0
  428. package/src/sharddev/bake/facetedGeometry.ts +379 -0
  429. package/src/sharddev/bake/farImpostor.ts +120 -0
  430. package/src/sharddev/bake/forest.ts +100 -0
  431. package/src/sharddev/bake/format-hook.mjs +2 -0
  432. package/src/sharddev/bake/generatorGlb.ts +23 -0
  433. package/src/sharddev/bake/geometryBounds.ts +77 -0
  434. package/src/sharddev/bake/geometryError.ts +48 -0
  435. package/src/sharddev/bake/glb.ts +355 -0
  436. package/src/sharddev/bake/glbCompression.ts +143 -0
  437. package/src/sharddev/bake/gltfSource.ts +59 -0
  438. package/src/sharddev/bake/groundMap.ts +142 -0
  439. package/src/sharddev/bake/image.ts +20 -0
  440. package/src/sharddev/bake/isleMap.ts +64 -0
  441. package/src/sharddev/bake/json.mjs +84 -0
  442. package/src/sharddev/bake/keyedSky.ts +47 -0
  443. package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
  444. package/src/sharddev/bake/kinds.ts +137 -0
  445. package/src/sharddev/bake/lightSources.ts +31 -0
  446. package/src/sharddev/bake/mapAssembly.ts +84 -0
  447. package/src/sharddev/bake/mapRaster.ts +173 -0
  448. package/src/sharddev/bake/mapRest.ts +57 -0
  449. package/src/sharddev/bake/mapScenes.ts +234 -0
  450. package/src/sharddev/bake/materialGraph.ts +32 -0
  451. package/src/sharddev/bake/meadow.ts +27 -0
  452. package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
  453. package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
  454. package/src/sharddev/bake/nativeLattice.ts +178 -0
  455. package/src/sharddev/bake/nativeRaster.ts +106 -0
  456. package/src/sharddev/bake/nativeTerrainField.ts +11 -0
  457. package/src/sharddev/bake/navigation-json.mjs +38 -0
  458. package/src/sharddev/bake/navigation.ts +113 -0
  459. package/src/sharddev/bake/navigationAsset.ts +18 -0
  460. package/src/sharddev/bake/nearPlaceholder.ts +206 -0
  461. package/src/sharddev/bake/normalizeRig.ts +80 -0
  462. package/src/sharddev/bake/phoneAstc.ts +93 -0
  463. package/src/sharddev/bake/placeholders.ts +581 -0
  464. package/src/sharddev/bake/placement.ts +80 -0
  465. package/src/sharddev/bake/portableBytes.ts +18 -0
  466. package/src/sharddev/bake/portableBytesMemo.ts +50 -0
  467. package/src/sharddev/bake/practiceCourse.ts +49 -0
  468. package/src/sharddev/bake/primitives.ts +96 -0
  469. package/src/sharddev/bake/props.ts +443 -0
  470. package/src/sharddev/bake/questPlacement.ts +98 -0
  471. package/src/sharddev/bake/rawTexture.ts +26 -0
  472. package/src/sharddev/bake/riderArms.ts +97 -0
  473. package/src/sharddev/bake/rig.ts +95 -0
  474. package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
  475. package/src/sharddev/bake/signPlacements.ts +25 -0
  476. package/src/sharddev/bake/simplifier.ts +52 -0
  477. package/src/sharddev/bake/skinned.ts +312 -0
  478. package/src/sharddev/bake/slabChunks.ts +149 -0
  479. package/src/sharddev/bake/slabs.ts +263 -0
  480. package/src/sharddev/bake/source-loader.mjs +55 -0
  481. package/src/sharddev/bake/sourceMetadata.ts +54 -0
  482. package/src/sharddev/bake/species.ts +368 -0
  483. package/src/sharddev/bake/specimenCatalogue.ts +47 -0
  484. package/src/sharddev/bake/splatGround.ts +141 -0
  485. package/src/sharddev/bake/staticMaterials.ts +171 -0
  486. package/src/sharddev/bake/terrain.ts +195 -0
  487. package/src/sharddev/bake/texture.ts +33 -0
  488. package/src/sharddev/bake/textureWasm.ts +81 -0
  489. package/src/sharddev/bake/tileEncoder.ts +11 -0
  490. package/src/sharddev/bake/tileGrid.ts +62 -0
  491. package/src/sharddev/bake/v2Finite.ts +160 -0
  492. package/src/sharddev/bake/v2Fuel.ts +71 -0
  493. package/src/sharddev/bake/wholePartition.ts +74 -0
  494. package/src/sharddev/bake/wholePieceJoin.ts +147 -0
  495. package/src/sharddev/bake/world.ts +173 -0
  496. package/src/sharddev/bake/worldCollision.ts +128 -0
  497. package/src/sharddev/bake/worldGeometry.ts +237 -0
  498. package/src/sharddev/bake/worldGlb.ts +123 -0
  499. package/src/sharddev/bake/worldImage.ts +12 -0
  500. package/src/sharddev/bake/worldLod.ts +128 -0
  501. package/src/sharddev/bake/worldRows.ts +102 -0
  502. package/src/sharddev/bake/worldTextureMemo.ts +63 -0
  503. package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
  504. package/src/sharddev/bake.ts +193 -0
  505. package/src/sharddev/bakePublication.ts +31 -0
  506. package/src/sharddev/behaviourSource.ts +94 -0
  507. package/src/sharddev/bin/wildshard.mjs +7 -0
  508. package/src/sharddev/blobBytes.ts +65 -0
  509. package/src/sharddev/blobs.ts +138 -0
  510. package/src/sharddev/bootInventory.ts +129 -0
  511. package/src/sharddev/bossProfiles.ts +18 -0
  512. package/src/sharddev/buildBehaviour.ts +77 -0
  513. package/src/sharddev/buildCacheMetrics.ts +17 -0
  514. package/src/sharddev/buildDecisionScripts.ts +122 -0
  515. package/src/sharddev/check.ts +118 -0
  516. package/src/sharddev/checkProject.ts +127 -0
  517. package/src/sharddev/cli.ts +200 -0
  518. package/src/sharddev/clientChannels.ts +169 -0
  519. package/src/sharddev/clientScripts.ts +10 -0
  520. package/src/sharddev/commons.ts +77 -0
  521. package/src/sharddev/commonsCosts.ts +11 -0
  522. package/src/sharddev/compileMovers.ts +11 -0
  523. package/src/sharddev/configBoundary.ts +6 -0
  524. package/src/sharddev/cookInput.ts +40 -0
  525. package/src/sharddev/crowds.ts +6 -0
  526. package/src/sharddev/decisionBindingMap.ts +11 -0
  527. package/src/sharddev/decisionScriptBindings.ts +117 -0
  528. package/src/sharddev/decisionScripts.ts +28 -0
  529. package/src/sharddev/decisionSource.ts +51 -0
  530. package/src/sharddev/dev.ts +113 -0
  531. package/src/sharddev/director.ts +26 -0
  532. package/src/sharddev/directorAbi.ts +77 -0
  533. package/src/sharddev/discoveryDocument.ts +97 -0
  534. package/src/sharddev/draft.ts +11 -0
  535. package/src/sharddev/eliteEntryRows.ts +29 -0
  536. package/src/sharddev/entries.ts +76 -0
  537. package/src/sharddev/entryReads.ts +73 -0
  538. package/src/sharddev/executeBundle.ts +55 -0
  539. package/src/sharddev/finds.ts +5 -0
  540. package/src/sharddev/formatJsonSchema.ts +3 -0
  541. package/src/sharddev/generationCache.ts +257 -0
  542. package/src/sharddev/generationRecipe.ts +94 -0
  543. package/src/sharddev/handwritten.ts +110 -0
  544. package/src/sharddev/immutable.ts +14 -0
  545. package/src/sharddev/interactions.ts +38 -0
  546. package/src/sharddev/kit/bakedGeometry.ts +16 -0
  547. package/src/sharddev/kit/geometryPack.ts +110 -0
  548. package/src/sharddev/ledger.ts +13 -0
  549. package/src/sharddev/looks/tileField.ts +67 -0
  550. package/src/sharddev/materialGraphFiles.ts +57 -0
  551. package/src/sharddev/materials.ts +574 -0
  552. package/src/sharddev/measure.ts +18 -0
  553. package/src/sharddev/modes.ts +115 -0
  554. package/src/sharddev/moverPrograms.ts +213 -0
  555. package/src/sharddev/movers.ts +75 -0
  556. package/src/sharddev/nativePopulationRows.ts +46 -0
  557. package/src/sharddev/newProject.ts +226 -0
  558. package/src/sharddev/noise.ts +54 -0
  559. package/src/sharddev/outputProduct.ts +188 -0
  560. package/src/sharddev/outputRuntime.ts +66 -0
  561. package/src/sharddev/performancePolicy.ts +29 -0
  562. package/src/sharddev/phasedBoss.ts +34 -0
  563. package/src/sharddev/physics.ts +194 -0
  564. package/src/sharddev/platformSections.ts +42 -0
  565. package/src/sharddev/plumbing.ts +8 -0
  566. package/src/sharddev/productOutput.ts +128 -0
  567. package/src/sharddev/project.ts +337 -0
  568. package/src/sharddev/projectCompilerIdentity.ts +94 -0
  569. package/src/sharddev/projectDecisions.ts +66 -0
  570. package/src/sharddev/projectEntryProof.ts +32 -0
  571. package/src/sharddev/projectGeneration.ts +219 -0
  572. package/src/sharddev/projectInputFiles.ts +47 -0
  573. package/src/sharddev/projectManifest.ts +108 -0
  574. package/src/sharddev/projectMap.ts +35 -0
  575. package/src/sharddev/projectOutput.ts +242 -0
  576. package/src/sharddev/projectPolicy.ts +17 -0
  577. package/src/sharddev/projectSections.ts +27 -0
  578. package/src/sharddev/questGraph.ts +25 -0
  579. package/src/sharddev/quests.ts +65 -0
  580. package/src/sharddev/random.ts +61 -0
  581. package/src/sharddev/refusals.ts +304 -0
  582. package/src/sharddev/reportCard.ts +13 -0
  583. package/src/sharddev/returnProjectionV2.ts +81 -0
  584. package/src/sharddev/rows.ts +192 -0
  585. package/src/sharddev/runtimeImports.ts +38 -0
  586. package/src/sharddev/runtimeMirrors.ts +39 -0
  587. package/src/sharddev/runtimePerformance.ts +38 -0
  588. package/src/sharddev/scene.ts +321 -0
  589. package/src/sharddev/sceneAnimation.ts +54 -0
  590. package/src/sharddev/sceneAudio.ts +64 -0
  591. package/src/sharddev/sceneDeclarations.ts +100 -0
  592. package/src/sharddev/sceneGraph.ts +139 -0
  593. package/src/sharddev/sceneTransform.ts +12 -0
  594. package/src/sharddev/schemaValidation.ts +61 -0
  595. package/src/sharddev/sections.ts +47 -0
  596. package/src/sharddev/shardSource.ts +59 -0
  597. package/src/sharddev/sourceReader.ts +26 -0
  598. package/src/sharddev/spawns.ts +38 -0
  599. package/src/sharddev/species/clips.ts +24 -0
  600. package/src/sharddev/species.ts +29 -0
  601. package/src/sharddev/speciesBrains.ts +19 -0
  602. package/src/sharddev/synth.ts +66 -0
  603. package/src/sharddev/test/compileDualScriptV2.ts +71 -0
  604. package/src/sharddev/test/compileSimV2.ts +21 -0
  605. package/src/sharddev/test/diskScriptScenario.ts +86 -0
  606. package/src/sharddev/test/scriptScenario.ts +249 -0
  607. package/src/sharddev/test/scriptSource.ts +12 -0
  608. package/src/sharddev/version.ts +4 -0
  609. package/src/sharddev/weapons/bowProfile.ts +20 -0
  610. package/src/sharddev/weapons/firearmRows.ts +11 -0
  611. package/src/sharddev/weapons/meleeProfile.ts +71 -0
  612. package/src/sharddev/weapons/thrownProfile.ts +10 -0
  613. package/src/sharddev/worldScenes.ts +308 -0
  614. package/src/sharddev/worldSource.ts +82 -0
  615. package/src/shards/_template/README.md +78 -0
  616. package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
  617. package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
  618. package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
  619. package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
  620. package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
  621. package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
  622. package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
  623. package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
  624. package/src/shards/_template/behaviour/boss.as +39 -0
  625. package/src/shards/_template/behaviour/door.as +32 -0
  626. package/src/shards/_template/behaviour/hooks.json +129 -0
  627. package/src/shards/_template/behaviour/idle.as +75 -0
  628. package/src/shards/_template/behaviour/items.as +22 -0
  629. package/src/shards/_template/card/landscape.jpg +0 -0
  630. package/src/shards/_template/card/portrait.jpg +0 -0
  631. package/src/shards/_template/card/thumb.jpg +0 -0
  632. package/src/shards/_template/data/audio.json +45 -0
  633. package/src/shards/_template/data/bossDecision.json +83 -0
  634. package/src/shards/_template/data/budgets.json +70 -0
  635. package/src/shards/_template/data/card.json +281 -0
  636. package/src/shards/_template/data/clientScripts.json +987 -0
  637. package/src/shards/_template/data/creatures.json +65 -0
  638. package/src/shards/_template/data/director.json +39 -0
  639. package/src/shards/_template/data/encounters.json +96 -0
  640. package/src/shards/_template/data/items.json +172 -0
  641. package/src/shards/_template/data/layout.json +66 -0
  642. package/src/shards/_template/data/ledger.json +32 -0
  643. package/src/shards/_template/data/look.json +521 -0
  644. package/src/shards/_template/data/map.json +64 -0
  645. package/src/shards/_template/data/moves.json +16 -0
  646. package/src/shards/_template/data/placeholder.json +8 -0
  647. package/src/shards/_template/data/plumbing.json +32 -0
  648. package/src/shards/_template/data/quests.json +223 -0
  649. package/src/shards/_template/data/rows.json +423 -0
  650. package/src/shards/_template/data/skins.json +66 -0
  651. package/src/shards/_template/data/spawn.json +6 -0
  652. package/src/shards/_template/data/targets.json +150 -0
  653. package/src/shards/_template/data/text.json +12 -0
  654. package/src/shards/_template/data/ui.json +33 -0
  655. package/src/shards/_template/data/water.json +13 -0
  656. package/src/shards/_template/generators/behaviour.ts +34 -0
  657. package/src/shards/_template/generators/boss.ts +29 -0
  658. package/src/shards/_template/generators/buildOptions.ts +2 -0
  659. package/src/shards/_template/generators/cell.ts +224 -0
  660. package/src/shards/_template/generators/districts.ts +215 -0
  661. package/src/shards/_template/generators/farLook.ts +15 -0
  662. package/src/shards/_template/generators/generate.ts +27 -0
  663. package/src/shards/_template/generators/ground.ts +15 -0
  664. package/src/shards/_template/generators/kit.ts +69 -0
  665. package/src/shards/_template/generators/landscape.ts +59 -0
  666. package/src/shards/_template/generators/landscapeNoise.ts +62 -0
  667. package/src/shards/_template/generators/mapInputs.ts +10 -0
  668. package/src/shards/_template/generators/product.ts +100 -0
  669. package/src/shards/_template/generators/productOutput.ts +18 -0
  670. package/src/shards/_template/generators/props.ts +9 -0
  671. package/src/shards/_template/generators/templatePropsSource.ts +58 -0
  672. package/src/shards/_template/generators/terrain.ts +17 -0
  673. package/src/shards/_template/generators/world.ts +630 -0
  674. package/src/shards/_template/hero.json +10 -0
  675. package/src/shards/_template/look/entry-reads.json +20 -0
  676. package/src/shards/_template/manifest.json +281 -0
  677. package/src/shards/_template/shard.config.ts +10 -0
  678. package/src/shared/health.ts +10 -0
  679. package/src/tools/build-web.ts +59 -0
  680. package/src/tsconfig.json +30 -0
  681. package/src/web/app.tsx +53 -0
  682. package/src/web/index.html +12 -0
  683. package/src/web/main.tsx +10 -0
  684. package/src/web/tsconfig.json +13 -0
  685. package/tsconfig.author.json +23 -0
  686. package/tsconfig.commons.json +21 -0
  687. package/tsconfig.json +47 -0
  688. package/tsconfig.sharddev.json +20 -0
@@ -0,0 +1,171 @@
1
+ import { MeshStandardMaterial, type BufferGeometry } from 'three';
2
+ import type { Shardfile } from '@wildshard/engine/host/shardfile';
3
+ import { parseKtx2 } from '../assets';
4
+ import { hashImmutableBytes } from '../immutable';
5
+ import type { WorldMaterial, WorldTexture } from './world';
6
+ import type { GlbPrimitive } from './glb';
7
+ import type { GraphIr } from '@wildshard/format/materialGraph';
8
+
9
+ const slots = ['colour', 'normal', 'metallicRoughness', 'occlusion', 'emissive'] as const;
10
+ type Bindings = NonNullable<Shardfile['props']>['materials'];
11
+ type BoundMaterial = NonNullable<Bindings>[string];
12
+ const nameOk = (name: string): boolean => name.length > 0 && name.length <= 128 && name.trim() === name && !/\p{Cc}/u.test(name) && !['__proto__', 'prototype', 'constructor'].includes(name);
13
+ const colourSlot = (slot: typeof slots[number]): boolean => slot === 'colour' || slot === 'emissive';
14
+ function wrap(value: number): NonNullable<BoundMaterial['colour']>['wrapS'] {
15
+ if (value === 33071 || value === 33648 || value === 10497) return value;
16
+ throw new Error('Unsupported static texture wrap');
17
+ }
18
+ function minFilter(value: number | null): NonNullable<BoundMaterial['colour']>['minFilter'] {
19
+ if (value === null || value === 9728 || value === 9729 || value === 9984 || value === 9985 || value === 9986 || value === 9987) return value;
20
+ throw new Error('Unsupported static texture minification');
21
+ }
22
+ function magFilter(value: number | null): NonNullable<BoundMaterial['colour']>['magFilter'] {
23
+ if (value === null || value === 9728 || value === 9729) return value;
24
+ throw new Error('Unsupported static texture magnification');
25
+ }
26
+ function checkSource(row: WorldMaterial): void {
27
+ if (!nameOk(row.name) || !/^[a-z][a-z0-9.-]{0,127}$/u.test(row.id) || row.colour.length !== 4 || row.emissive.length !== 3
28
+ || ![...row.colour, ...row.emissive, row.roughness, row.metalness, row.alphaCutoff, row.occlusion].every(value => Number.isFinite(value) && value >= 0 && value <= 1)
29
+ || !Number.isFinite(row.normalScale) || row.normalScale < 0 || row.normalScale > 4 || !['OPAQUE', 'MASK', 'BLEND'].includes(row.alpha)) throw new Error('Static material factors require an explicit bounded adapter');
30
+ }
31
+
32
+ /** Return complete mipmapped KTX2 pixels for this exact original image, orientation and colour/data role.
33
+ * Canvas atlases must be captured with the real producer/font/rasteriser. Atlas UV rectangles are never repacked. */
34
+ export type StaticTextureResolver = (source: Readonly<WorldTexture>, role: 'srgb' | 'linear') => Uint8Array;
35
+
36
+ /** Named multi-material transport for both native-world and normalized-GLB bakes.
37
+ * Every source slot is explicit. Geometry is borrowed; generated wire materials and faceted copies are owned until dispose(). */
38
+ export class StaticMaterialCatalogue {
39
+ private readonly rows = new Map<string, { source: WorldMaterial & { vertexColours?: boolean; faceted?: boolean }; binding: BoundMaterial; material: MeshStandardMaterial; dependencies: string[]; additive: boolean; modelSpace: boolean }>();
40
+ private readonly textures = new Map<string, Uint8Array>();
41
+ private readonly samplers = new Map<string, string>();
42
+ private readonly geometry = new Set<BufferGeometry>();
43
+ private disposed = false;
44
+
45
+ constructor(sources: readonly (WorldMaterial & { vertexColours?: boolean; faceted?: boolean })[], look: Shardfile['look']['materials'], graphs: ReadonlyMap<string, GraphIr>, resolve: StaticTextureResolver) {
46
+ if (sources.length === 0 || sources.length > 256) throw new Error('Static material catalogue requires 1–256 source slots');
47
+ try { for (const source of sources) {
48
+ checkSource(source);
49
+ const entry = Object.hasOwn(look, source.id) ? look[source.id] : undefined;
50
+ if (!nameOk(source.name) || this.rows.has(source.name) || entry === undefined) throw new Error(`Static material ${source.name || '(unnamed)'} is duplicated or has no explicit look entry`);
51
+ // colourOrVertex explicitly binds this colour slot at runtime. Its opaque picture replaces vertex colour;
52
+ // non-unit factors, other texture roles and an authored emissive term still need their own adapters.
53
+ const graph = graphs.get(source.id);
54
+ const colourGraph = graph?.model === 'unlit'
55
+ && Object.values(graph.nodes).some(node => node.op === 'meshMap' && node.name === 'colourOrVertex')
56
+ && source.alpha === 'OPAQUE' && source.colour.every(value => value === 1) && source.emissive.every(value => value === 0)
57
+ && slots.every(slot => slot === 'colour' || source.maps[slot] === null);
58
+ if (entry.family === 'graph' && Object.values(source.maps).some(map => map !== null) && !colourGraph) throw new Error('Static graph transport needs an explicit factor-binding adapter');
59
+ const cutoff = source.alpha === 'MASK' ? source.alphaCutoff : 0;
60
+ if (('alphaCutoff' in entry ? entry.alphaCutoff : 0) !== cutoff) throw new Error(`Static material ${source.name}: catalogue alpha cutoff differs from source`);
61
+ const binding: BoundMaterial = { id: source.id, colour: null, normal: null, metallicRoughness: null, occlusion: null, emissive: null }, dependencies: string[] = [];
62
+ for (const slot of slots) {
63
+ const map = source.maps[slot]; if (map === null) continue;
64
+ if ((entry.family === 'painterly' && slot === 'metallicRoughness') || (entry.family === 'emissive' && slot !== 'colour')) throw new Error(`Static material ${source.name}: family cannot draw ${slot}`);
65
+ if (![33071, 33648, 10497].includes(map.wrapS) || ![33071, 33648, 10497].includes(map.wrapT)
66
+ || (map.minFilter !== null && ![9728, 9729, 9984, 9985, 9986, 9987].includes(map.minFilter)) || (map.magFilter !== null && ![9728, 9729].includes(map.magFilter))
67
+ || !Number.isInteger(map.anisotropy ?? 1) || (map.anisotropy ?? 1) < 1 || (map.anisotropy ?? 1) > 16) throw new Error('Unsupported static texture sampler');
68
+ const bytes = resolve(structuredClone(map), colourSlot(slot) ? 'srgb' : 'linear'); parseKtx2(bytes);
69
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength), dfd = header.getUint32(48, true);
70
+ if (bytes[dfd + 14] !== (colourSlot(slot) ? 2 : 1)) throw new Error('Static texture transfer differs from its source slot role');
71
+ if ((map.width !== undefined && header.getUint32(20, true) !== map.width) || (map.height !== undefined && header.getUint32(24, true) !== map.height)) throw new Error('Static atlas extent changed; cropping/repacking requires an explicit UV adapter');
72
+ const file = hashImmutableBytes(bytes), sampler = { file, wrapS: wrap(map.wrapS), wrapT: wrap(map.wrapT), minFilter: minFilter(map.minFilter), magFilter: magFilter(map.magFilter), anisotropy: map.anisotropy ?? 1 };
73
+ const identity = JSON.stringify({ ...sampler, role: colourSlot(slot) ? 'srgb' : 'linear' }), previous = this.samplers.get(file);
74
+ if (previous !== undefined && previous !== identity) throw new Error('Static texture bytes cannot mix samplers or colour/data roles');
75
+ this.samplers.set(file, identity); this.textures.set(file, Uint8Array.from(bytes)); dependencies.push(file);
76
+ if (slot === 'normal') binding.normal = { ...sampler, scale: source.normalScale };
77
+ else if (slot === 'occlusion') binding.occlusion = { ...sampler, strength: source.occlusion };
78
+ else binding[slot] = sampler;
79
+ }
80
+ const material = new MeshStandardMaterial(); material.name = source.name;
81
+ material.color.fromArray(source.colour); material.opacity = source.colour[3] ?? 1;
82
+ material.roughness = source.roughness; material.metalness = source.metalness; material.emissive.fromArray(source.emissive);
83
+ material.side = source.doubleSided ? 2 : 0; material.transparent = source.alpha === 'BLEND'; material.alphaTest = cutoff;
84
+ const additive = graph?.effectState?.blend === 'additive';
85
+ // a graph that reads the mesh's own model-space position (the hologram's turn about its pivot) needs the authored
86
+ // metres there, not a tile grid's units
87
+ const modelSpace = graph !== undefined && Object.values(graph.nodes).some(node => node.op === 'positionLocal' || node.op === 'positionGeometry');
88
+ this.rows.set(source.name, { source: structuredClone(source), binding, material, dependencies: [...new Set(dependencies)].sort(), additive, modelSpace });
89
+ } } catch (error) { this.dispose(); throw error; }
90
+ }
91
+
92
+ /** Whether slot `name`'s graph reads the mesh's model-space position: such a primitive keeps float positions in metres,
93
+ * never a tile grid's quantized units (RM8.1e). */
94
+ modelSpace(name: string): boolean {
95
+ const row = this.rows.get(name); if (row === undefined) throw new Error(`Unmapped static primitive material ${name}`);
96
+ return row.modelSpace;
97
+ }
98
+
99
+ /** Assign one source material slot to one primitive; multi-material meshes split by their actual geometry groups first. */
100
+ primitive(name: string, geometry: BufferGeometry, options: Omit<GlbPrimitive, 'geometry' | 'material'> = {}): GlbPrimitive {
101
+ if (this.disposed) throw new Error('Static material catalogue disposed');
102
+ const row = this.rows.get(name); if (row === undefined) throw new Error(`Unmapped static primitive material ${name}`);
103
+ if (!geometry.hasAttribute('position') || geometry.drawRange.start !== 0 || geometry.drawRange.count < (geometry.index?.count ?? geometry.getAttribute('position').count)) throw new Error('Static primitive requires its complete authored triangle range');
104
+ if (Object.values(row.source.maps).some(value => value !== null) && !geometry.hasAttribute('uv')) throw new Error(`Static atlas primitive ${name} needs its original UV0`);
105
+ if (row.source.vertexColours === false && geometry.hasAttribute('color')) throw new Error('Disabled source vertex colour needs an explicit geometry adapter');
106
+ let actual = geometry;
107
+ // an additive graph (a hologram) is light, with no surface to cast a shadow
108
+ if (row.additive) return { ...options, geometry: actual, material: row.material, castShadow: false };
109
+ if (row.source.faceted === true) { actual = geometry.index === null ? geometry.clone() : geometry.toNonIndexed(); actual.computeVertexNormals(); this.geometry.add(actual); }
110
+ return { ...options, geometry: actual, material: row.material };
111
+ }
112
+
113
+ /** Assign an actual mesh material array through its indexed triangle groups. Single-material meshes use all faces.
114
+ * Split groups preserve every original attribute and instance matrix; gaps, overlaps and unknown slots refuse. */
115
+ primitives(geometry: BufferGeometry, names: readonly string[], options: Omit<GlbPrimitive, 'geometry' | 'material'> = {}): GlbPrimitive[] {
116
+ if (names.length === 1) { const name = names[0]; if (name === undefined) throw new Error('Missing static slot'); return [this.primitive(name, geometry, options)]; }
117
+ const position = geometry.getAttribute('position'), index = geometry.index;
118
+ const count = index?.count ?? position.count;
119
+ if (names.length === 0 || names.length > 256 || count % 3 !== 0 || geometry.groups.length === 0 || geometry.drawRange.start !== 0 || geometry.drawRange.count < count) throw new Error('Static multi-material mesh needs complete triangle groups');
120
+ const groups = [...geometry.groups].sort((a, b) => a.start - b.start), assigned = new Map<string, number[]>(); let end = 0;
121
+ for (const group of groups) {
122
+ const slot = group.materialIndex ?? 0, name = names[slot];
123
+ if (!Number.isInteger(slot) || slot < 0 || name === undefined || !Number.isInteger(group.start) || !Number.isInteger(group.count) || group.start !== end || group.count < 1 || group.count % 3 !== 0 || group.start + group.count > count) throw new Error('Static material groups have missing, overlapping or unknown triangles');
124
+ const triangles = assigned.get(name) ?? [];
125
+ for (let i = group.start; i < group.start + group.count; i++) triangles.push(index?.getX(i) ?? i);
126
+ assigned.set(name, triangles); end += group.count;
127
+ }
128
+ if (end !== count) throw new Error('Static material groups omit triangles');
129
+ return [...assigned].map(([name, indices]) => {
130
+ const part = geometry.clone(); part.clearGroups(); part.setIndex(indices); this.geometry.add(part);
131
+ return this.primitive(name, part, options);
132
+ });
133
+ }
134
+
135
+ /** Distinct exact slot dependencies for this GLB only. Include ground and props material names before final row packing. */
136
+ dependencies(names: readonly string[]): string[] {
137
+ if (this.disposed) throw new Error('Static material catalogue disposed');
138
+ return [...new Set(names.flatMap(name => { const row = this.rows.get(name); if (row === undefined) throw new Error(`Unmapped static primitive material ${name}`); return row.dependencies; }))].sort();
139
+ }
140
+ /** Independent named format bindings and immutable texture bytes; pack textures before their GLB users. */
141
+ snapshot(): { materials: NonNullable<Bindings>; textures: Map<string, Uint8Array> } {
142
+ if (this.disposed) throw new Error('Static material catalogue disposed');
143
+ return { materials: Object.fromEntries([...this.rows].map(([name, row]) => [name, structuredClone(row.binding)])), textures: new Map([...this.textures].map(([hash, bytes]) => [hash, Uint8Array.from(bytes)])) };
144
+ }
145
+ /** Dispose transport-only resources, never borrowed source geometry or source materials. */
146
+ dispose(): void { if (this.disposed) return; this.disposed = true; for (const row of this.rows.values()) row.material.dispose(); for (const geometry of this.geometry) geometry.dispose(); }
147
+ }
148
+
149
+ /** Read exact emitted names from a byte-admitted GLB, including an empty name so named packing refuses it. */
150
+ export function staticMaterialNames(bytes: Uint8Array): string[] {
151
+ if (bytes.length < 28) throw new Error('Truncated static GLB');
152
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength), size = header.getUint32(12, true);
153
+ if (header.getUint32(0, true) !== 0x46546c67 || header.getUint32(16, true) !== 0x4e4f534a || size > 2_000_000 || 28 + size > bytes.length) throw new Error('Invalid static GLB JSON');
154
+ const document: unknown = JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + size)));
155
+ if (typeof document !== 'object' || document === null || !('materials' in document) || !Array.isArray(document.materials)) throw new Error('Static GLB needs material slots');
156
+ return document.materials.map((row: unknown) => {
157
+ if (typeof row !== 'object' || row === null || !('name' in row) || typeof row.name !== 'string') return '';
158
+ return row.name;
159
+ });
160
+ }
161
+
162
+ /** Each named GLB directly depends on every texture its own material slots use, rather than another tile's union. */
163
+ export function checkStaticMaterialDependencies(bytes: Uint8Array, materials: NonNullable<Bindings>, dependencies: readonly string[]): void {
164
+ for (const name of staticMaterialNames(bytes)) {
165
+ const row = Object.hasOwn(materials, name) ? materials[name] : undefined;
166
+ if (row === undefined) throw new Error(`Unmapped static GLB material ${name || '(unnamed)'}`);
167
+ for (const slot of slots) {
168
+ const texture = row[slot]; if (texture !== null && !dependencies.includes(texture.file)) throw new Error(`Static GLB material ${name}: missing its own ${slot} dependency`);
169
+ }
170
+ }
171
+ }
@@ -0,0 +1,195 @@
1
+ import { PAINTED_TERRAIN_ATTRIBUTES } from '@wildshard/format/materialFamilies';
2
+ import { CELL_ABOVE, CELL_BELOW, CONTENT_CAPS } from '@wildshard/format/contentBounds';
3
+ import { bilinearTerrainSamplers, decodeTerrainTile, encodeTerrainTile, terrainTileCost, terrainTileHeight, type TerrainTileData } from '@wildshard/format/terrainTileBytes';
4
+ import { validateTerrainAssets } from '@wildshard/format/product';
5
+ import { TerrainSchema, type ShardTerrain } from '@wildshard/format/terrain';
6
+ import type { Shardfile } from '@wildshard/format/shardSchema';
7
+ import * as v from 'valibot';
8
+ import { hashImmutableBytes as contentHash } from '../immutable';
9
+ import { parseBakedTerrain, type BakedGrid } from '@wildshard/format/bakedTerrainBytes';
10
+ import { bakedSamplers, type BakedTerrainSamplers } from '@wildshard/format/bakedTerrainSampling';
11
+ import { ScalarLatticeSchema, decodeScalarStorage } from '@wildshard/format/scalarChannel';
12
+ import { unzlibSync } from 'fflate';
13
+
14
+ /** Read an owned WTT source using its original native triangular sampling law.
15
+ * No resampling, physics owner or rendering allocation is introduced. */
16
+ export function readTerrainTileSource(bytes: Uint8Array): { heightAt: (x: number, z: number) => number } {
17
+ const ground = decodeTerrainTile(bytes);
18
+ return { heightAt: (x, z) => terrainTileHeight(ground, x, z) };
19
+ }
20
+ /** Original renderer lattice and its defining native queries; this is not a physics-grid substitute. */
21
+ export interface NativeTerrainSource extends BakedTerrainSamplers { readonly grid: BakedGrid }
22
+
23
+ /** Admit bounded original WSTR bytes for author placements, keeping native samples, clamping and arithmetic exact.
24
+ * Copies only the supplied byte view; it never reads a host, selects a level or installs runtime services. */
25
+ export function readNativeTerrain(bytes: Uint8Array): NativeTerrainSource {
26
+ if (bytes.byteLength < 24 || bytes.byteLength > 8_000_000) throw new Error('Native terrain byte cap');
27
+ const buffer = Uint8Array.from(bytes).buffer, header = new DataView(buffer);
28
+ const resolution = header.getUint32(8, true), size = header.getFloat32(12, true);
29
+ if ((resolution !== 256 && resolution !== 257) || !Number.isFinite(size) || size <= 0 || size > 500) throw new Error('Native terrain grid cap');
30
+ const end = 24 + resolution ** 2 * 8;
31
+ if (buffer.byteLength > end && (buffer.byteLength < end + 16 || header.getUint32(end + 8, true) > 4_000_000
32
+ || header.getUint32(end + 12, true) > 64)) throw new Error('Native terrain placement cap');
33
+ const grid = parseBakedTerrain(buffer);
34
+ if (grid === null || grid.heights.some(height => !Number.isFinite(height) || height < -CELL_BELOW || height > CELL_ABOVE)
35
+ || (grid.undergrowth !== null && !Number.isFinite(grid.undergrowth.checksum.sum))) throw new Error('Invalid native terrain lattice');
36
+ return { grid, ...bakedSamplers(grid) };
37
+ }
38
+
39
+ /** Owned native f32 field and the original clamped bilinear query over that same storage. */
40
+ export interface NativeScalarField {
41
+ readonly resolution: number;
42
+ readonly size: number;
43
+ readonly values: Float32Array;
44
+ readonly sample: (x: number, z: number) => number;
45
+ }
46
+
47
+ /** Admit an existing bounded scalar lattice and its declared compressed blocks for native authors.
48
+ * Decode once with the defining scalar intake; preserve every f32 bit and the original sampling law.
49
+ * Separate calls own their storage, never select a page or install terrain, and retain no input block. */
50
+ export function readNativeScalarField(input: unknown, blocks: ReadonlyMap<string, Uint8Array>): NativeScalarField {
51
+ const row = v.parse(ScalarLatticeSchema, input);
52
+ if (typeof row.values.data === 'string') throw new Error('Native scalar field requires a declared block');
53
+ const block = blocks.get(row.values.data.file);
54
+ if (block === undefined) throw new Error('Missing scalar block');
55
+ const values = decodeScalarStorage(row.values, block, (bytes, out) => unzlibSync(bytes, { out }));
56
+ if (!(values instanceof Float32Array)) throw new Error('Native scalar fields require f32 storage');
57
+ const { heightAt } = bakedSamplers({ res: row.res, size: row.size, heights: values, seed: 0,
58
+ landscapeHash: 0, splat: new Uint8Array(0), undergrowth: null });
59
+ return { resolution: row.res, size: row.size, values, sample: heightAt };
60
+ }
61
+
62
+ /** An admitted, detached column-major lattice and its original clamped triangular query. */
63
+ export interface NativeTriangleField {
64
+ readonly resolution: number;
65
+ readonly x: number; readonly z: number; readonly size: number;
66
+ readonly heights: Float32Array;
67
+ readonly sample: (x: number, z: number) => number;
68
+ }
69
+
70
+ /** Admit original author collision samples without transposing or resampling them.
71
+ * The native column-major law keeps its per-cell diagonal and operation order.
72
+ * Each call owns its storage; no landscape, runtime binding or collider is installed. */
73
+ export function readNativeTriangleField(input: Pick<TerrainTileData, 'resolution' | 'x' | 'z' | 'size' | 'heights'>): NativeTriangleField {
74
+ if (!Number.isSafeInteger(input.resolution) || input.resolution < 2 || input.resolution > 257
75
+ || !Number.isFinite(input.size) || input.size <= 0 || input.size > 500
76
+ || !Number.isFinite(input.x) || !Number.isFinite(input.z)
77
+ || input.heights.length !== input.resolution ** 2
78
+ || input.heights.some(height => !Number.isFinite(height) || height < -CELL_BELOW || height > CELL_ABOVE)) {
79
+ throw new Error('Invalid native triangular field');
80
+ }
81
+ const data = { resolution: input.resolution, x: input.x, z: input.z, size: input.size, heights: Float32Array.from(input.heights) };
82
+ return { ...data, sample: (x, z) => terrainTileHeight(data, x, z, { layout: 'column-major', boundary: 'clamp' }) };
83
+ }
84
+
85
+ /** Original-lattice query metadata; no render or collision mesh is generated. */
86
+ export interface QueryTerrainBakeOptions { normalEpsilon?: number; datum?: number; family?: string }
87
+ /** One critical, charged WTT query root; its runtime owner keeps rendering and collision. */
88
+ export interface BakedQueryTerrain {
89
+ terrain: ShardTerrain; files: Shardfile['files']; critical: string[]; assets: Map<string, Uint8Array>;
90
+ }
91
+
92
+ /** Encode the original native lattice directly, without sampling, patches, colours or render tiles.
93
+ * The query-only form requires runtime.binds terrain. Its compatibility collider reference names
94
+ * this same query root and never installs collision. Native placement logs are not query data. */
95
+ export function bakeQueryTerrain(source: NativeTerrainSource, options: QueryTerrainBakeOptions = {}): BakedQueryTerrain {
96
+ const { grid } = source;
97
+ if ((grid.res !== 256 && grid.res !== 257) || grid.size !== 500) throw new Error('Native query terrain needs its original 500 m grid');
98
+ const data: TerrainTileData = { resolution: grid.res, x: -grid.size / 2, z: -grid.size / 2,
99
+ size: grid.size, heights: grid.heights, splat: grid.splat };
100
+ const bytes = encodeTerrainTile(data), hash = contentHash(bytes);
101
+ const terrain = v.parse(TerrainSchema, { version: 1, form: 'query', family: options.family ?? 'toon', tiles: [],
102
+ sampling: { law: 'bilinear', file: hash, normalEpsilon: options.normalEpsilon ?? 0.6, datum: options.datum ?? 0 } });
103
+ const result: BakedQueryTerrain = { terrain, files: [{ hash, kind: 'binary', compressed: bytes.length,
104
+ ...terrainTileCost(data), dependencies: [], critical: true }], critical: [hash], assets: new Map([[hash, bytes]]) };
105
+ bilinearTerrainSamplers(data, options.normalEpsilon ?? 0.6, options.datum ?? 0);
106
+ return result;
107
+ }
108
+
109
+ /** An ordered build-time patch, blended across a circular footprint; it changes rendering and collision together. */
110
+ export interface TerrainOverride { x: number; z: number; radius: number; height: number; mode: 'replace' | 'lower' | 'raise' }
111
+ /** Trusted generator inputs. These closures run only while baking and never enter shard.json or the client. */
112
+ export interface TerrainBakeSource {
113
+ heightAt: (x: number, z: number) => number;
114
+ colourAt: (x: number, z: number, height: number) => readonly [number, number, number];
115
+ overrides?: readonly TerrainOverride[]; family?: string;
116
+ /** Independent original native query lattice; does not replace or install the compiled collider. */
117
+ sampling?: { source: NativeTerrainSource; normalEpsilon?: number; datum?: number };
118
+ }
119
+ /** Immutable wire files plus the ordinary shardfile rows and a validated terrain section. */
120
+ export interface BakedTerrain {
121
+ terrain: ShardTerrain; tiles: Shardfile['tiles']; files: Shardfile['files']; edge: Shardfile['edge'];
122
+ critical: string[]; assets: Map<string, Uint8Array>;
123
+ }
124
+
125
+ /** Bake a shared 257² lattice into 64 L0 and 16 L1 tiles, with an independent whole-sim collision file. */
126
+ export function bakeTerrain(source: TerrainBakeSource): BakedTerrain {
127
+ for (const patch of source.overrides ?? []) if (![patch.x, patch.z, patch.radius, patch.height].every(Number.isFinite) || patch.radius <= 0 || patch.x < -250 || patch.x > 250 || patch.z < -250 || patch.z > 250 || patch.height < -CELL_BELOW || patch.height > CELL_ABOVE || !['replace', 'lower', 'raise'].includes(patch.mode)) throw new Error('Invalid terrain override');
128
+ const heights = new Float32Array(257 ** 2), colours = new Float32Array(257 ** 2 * 3);
129
+ for (let z = 0; z < 257; z++) for (let x = 0; x < 257; x++) {
130
+ const px = -250 + x * 500 / 256, pz = -250 + z * 500 / 256;
131
+ let h = source.heightAt(px, pz);
132
+ if (!Number.isFinite(h) || h < -CELL_BELOW || h > CELL_ABOVE) throw new Error('Invalid terrain generator height');
133
+ for (const patch of source.overrides ?? []) {
134
+ const t = Math.max(0, 1 - Math.hypot(px - patch.x, pz - patch.z) / patch.radius), weight = t * t * (3 - 2 * t);
135
+ const target = patch.mode === 'lower' ? Math.min(h, patch.height) : patch.mode === 'raise' ? Math.max(h, patch.height) : patch.height;
136
+ h += (target - h) * weight;
137
+ }
138
+ const i = z * 257 + x; heights[i] = h;
139
+ const rgb = [...source.colourAt(px, pz, heights[i] ?? 0)];
140
+ if (rgb.length !== 3 || rgb.some((c) => !Number.isFinite(c) || c < 0 || c > 1)) throw new Error('Invalid terrain generator colour');
141
+ colours.set(rgb, i * 3);
142
+ }
143
+ const grid: TerrainTileData = { resolution: 257, x: -250, z: -250, size: 500, heights };
144
+ const assets = new Map<string, Uint8Array>(), files: Shardfile['files'] = [];
145
+ const store = (data: TerrainTileData, critical: boolean): string => {
146
+ const bytes = encodeTerrainTile(data), hash = contentHash(bytes);
147
+ if (!assets.has(hash)) { assets.set(hash, bytes); files.push({ hash, kind: 'binary', compressed: bytes.length, ...terrainTileCost(data), dependencies: [], critical }); }
148
+ return hash;
149
+ };
150
+ const collider = store(grid, true), tiles: Shardfile['tiles'] = [], entries: ShardTerrain['tiles'] = [];
151
+ for (const lod of [0, 1] as const) {
152
+ const size = lod === 0 ? 62.5 : 125, resolution = lod === 0 ? 33 : 17, count = 500 / size, stride = lod === 0 ? 1 : 4;
153
+ for (let tz = 0; tz < count; tz++) for (let tx = 0; tx < count; tx++) {
154
+ const tileHeights = new Float32Array(resolution ** 2), tileColours = new Float32Array(resolution ** 2 * 3);
155
+ for (let z = 0; z < resolution; z++) for (let x = 0; x < resolution; x++) {
156
+ const gx = tx * size / (500 / 256) + x * stride, gz = tz * size / (500 / 256) + z * stride, i = z * resolution + x, g = gz * 257 + gx;
157
+ tileHeights[i] = heights[g] ?? 0; tileColours.set(colours.subarray(g * 3, g * 3 + 3), i * 3);
158
+ }
159
+ const tile: TerrainTileData = { resolution, x: -250 + tx * size, z: -250 + tz * size, size, heights: tileHeights, colours: tileColours };
160
+ let geometricError = 0;
161
+ for (let z = 0; z <= size / (500 / 256); z++) for (let x = 0; x <= size / (500 / 256); x++) {
162
+ const px = tile.x + x * 500 / 256, pz = tile.z + z * 500 / 256;
163
+ geometricError = Math.max(geometricError, Math.abs(terrainTileHeight(tile, px, pz) - terrainTileHeight(grid, px, pz)));
164
+ }
165
+ const file = store(tile, false), cost = terrainTileCost(tile), cap = lod === 0 ? CONTENT_CAPS.l0 : CONTENT_CAPS.l1;
166
+ const min = Math.min(...tileHeights), max = Math.max(...tileHeights), compressed = assets.get(file)?.length ?? 0;
167
+ if (cost.decoded + cost.gpu > cap.resident || compressed > cap.compressed || cost.triangles > cap.triangles || cost.draws > cap.draws) throw new Error('Terrain tile exceeds content caps');
168
+ tiles.push({ lod, x: tx, z: tz, bounds: { min: [tile.x, min - (lod === 0 ? size / 16 : 0), tile.z], max: [tile.x + size, max, tile.z + size] }, geometricError, files: [file], compressed, ...cost });
169
+ entries.push({ lod, x: tx, z: tz, file });
170
+ }
171
+ }
172
+ const edgeAt = (side: 'north' | 'east' | 'south' | 'west'): Shardfile['edge']['north'] => {
173
+ const samples: number[] = [], rgb: [number, number, number][] = [];
174
+ for (let i = 0; i < 257; i++) {
175
+ const x = side === 'east' ? 256 : side === 'west' ? 0 : i, z = side === 'north' ? 256 : side === 'south' ? 0 : i, at = z * 257 + x;
176
+ samples.push(heights[at] ?? 0); rgb.push([colours[at * 3] ?? 0, colours[at * 3 + 1] ?? 0, colours[at * 3 + 2] ?? 0]);
177
+ }
178
+ return { heights: samples, colours: rgb, roadHeight: 0 };
179
+ };
180
+ const critical = [collider];
181
+ const sampling = source.sampling === undefined ? undefined : (() => {
182
+ const { grid: native } = source.sampling.source;
183
+ const file = store({ resolution: native.res, x: -250, z: -250, size: native.size,
184
+ heights: native.heights, splat: native.splat }, true);
185
+ critical.push(file);
186
+ return { law: 'bilinear' as const, file, normalEpsilon: source.sampling.normalEpsilon ?? 0.6, datum: source.sampling.datum ?? 0 };
187
+ })();
188
+ const terrain = v.parse(TerrainSchema, { version: 1, family: source.family ?? 'toon', collider, tiles: entries,
189
+ ...(sampling === undefined ? {} : { sampling }) });
190
+ const result: BakedTerrain = { terrain, tiles, files, critical, assets, edge: { north: edgeAt('north'), east: edgeAt('east'), south: edgeAt('south'), west: edgeAt('west') } };
191
+ validateTerrainAssets(terrain, assets, result); return result;
192
+ }
193
+
194
+ /** Defining per-vertex terrain masks, track vectors and zone channel layout. */
195
+ export function paintedTerrainAttributes(): typeof PAINTED_TERRAIN_ATTRIBUTES { return PAINTED_TERRAIN_ATTRIBUTES; }
@@ -0,0 +1,33 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Trusted author tools run the local, pinned texture encoder at build time.
2
+ import { execFileSync } from 'node:child_process';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Encoder throwaways belong to one temporary directory and are always removed.
4
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- Portable temporary directory for the author CLI.
6
+ import { tmpdir } from 'node:os';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- Resolve only filenames inside the encoder's owned temporary directory.
8
+ import { join } from 'node:path';
9
+ import { parseKtx2 } from '../assets';
10
+ import { readImagePixels } from './image';
11
+ import { bakeRawColourPixels } from './rawTexture';
12
+
13
+ /** Bake PNG colour pixels to mipmapped sRGB UASTC KTX2; the engine's existing loader transcodes these blocks to ASTC. */
14
+ export function bakeColourTexture(png: Uint8Array, encoder = 'basisu', options: { flipY?: boolean } = {}): Uint8Array {
15
+ if (png.length < 24 || png.length > 25_000_000 || png[0] !== 137 || png[1] !== 80 || png[2] !== 78 || png[3] !== 71) throw new Error('Texture source must be a bounded PNG');
16
+ const header = new DataView(png.buffer, png.byteOffset, png.byteLength), width = header.getUint32(16), height = header.getUint32(20);
17
+ if (width === 0 || height === 0 || width > 4096 || height > 4096) throw new Error('Texture dimensions exceed cap');
18
+ const directory = mkdtempSync(join(tmpdir(), 'wildshard-texture-'));
19
+ try {
20
+ const input = join(directory, 'colour.png'), output = join(directory, 'colour.ktx2'); writeFileSync(input, png);
21
+ execFileSync(encoder, ['-ktx2', '-uastc', '-uastc_level', '2', '-srgb', '-mipmap', '-mip_filter', 'box', '-max_threads', '4', '-ktx2_zstandard_level', '20', ...(options.flipY === true ? ['-y_flip'] : []), input, '-output_file', output], { stdio: 'pipe', timeout: 120000 });
22
+ const bytes = Uint8Array.from(readFileSync(output)); parseKtx2(bytes); return bytes;
23
+ } finally { rmSync(directory, { recursive: true }); }
24
+ }
25
+
26
+ /** Store bounded PNG/JPEG/WebP pixels byte-exact in a single-level Zstd RGBA8 KTX2.
27
+ * No lossy encoder or colour transform runs. flipY explicitly selects source row orientation;
28
+ * colourSpace:'linear' retains numerical texture values (default: sRGB).
29
+ * look.samplers mips:'gpu' uses the runtime's existing mip law, as for a painted bitmap. */
30
+ export async function bakeRawColourTexture(image: Uint8Array, options: { flipY?: boolean; colourSpace?: 'srgb' | 'linear' } = {}): Promise<Uint8Array> {
31
+ if (options.colourSpace !== undefined && !['srgb', 'linear'].includes(options.colourSpace)) throw new Error('Invalid texture colour space');
32
+ return bakeRawColourPixels(await readImagePixels(image, options), options);
33
+ }
@@ -0,0 +1,81 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Trusted author tooling resolves only its pinned dependency artifacts.
2
+ import { createRequire } from 'node:module';
3
+ // oxlint-disable-next-line import/no-nodejs-modules -- Temporary CommonJS glue is a verified third-party module, removed after loading.
4
+ import { mkdtempSync, readFileSync, writeFileSync, rmSync } from 'node:fs';
5
+ // oxlint-disable-next-line import/no-nodejs-modules -- The encoder owns this unique portable temporary directory.
6
+ import { tmpdir } from 'node:os';
7
+ // oxlint-disable-next-line import/no-nodejs-modules -- Local dependency artifacts, never an author-supplied path or URL.
8
+ import { dirname, join } from 'node:path';
9
+ // oxlint-disable-next-line import/no-nodejs-modules -- The trusted build runner opts into its private transform cache.
10
+ import process from 'node:process';
11
+ import { readImagePixels } from './image';
12
+ import { worldImageInfo } from './worldImage';
13
+ import { hashImmutableBytes } from '../immutable';
14
+ import { parseKtx2 } from '../assets';
15
+ import { cachedWorldTexture } from './worldTextureMemo';
16
+
17
+ /** Exact packaged encoder artifacts; lockfile integrity pins the containing dependency as well. */
18
+ export const WORLD_TEXTURE_TOOL: Readonly<{ package: "@loaders.gl/textures"; version: "4.5.3"; decoder: "sharp@0.34.5"; glue: "d204cc62dfdf910f92bce616872a6d6057b6d2b45bbaffbc0ef047375351e4a6"; wasm: "62ce0364ea8f4969e1e4277ce275213dcce5b234c8c96586da06e3879010341c"; }> = Object.freeze({
19
+ package: '@loaders.gl/textures', version: '4.5.3', decoder: 'sharp@0.34.5',
20
+ glue: 'd204cc62dfdf910f92bce616872a6d6057b6d2b45bbaffbc0ef047375351e4a6',
21
+ wasm: '62ce0364ea8f4969e1e4277ce275213dcce5b234c8c96586da06e3879010341c',
22
+ });
23
+ const settings = Object.freeze({ktx2:true,supercompression:true,quality:128,uastc:true,mips:true,sourceIsPng:false});
24
+ interface Encoder {
25
+ setCreateKTX2File: (value: boolean) => void; setKTX2UASTCSupercompression: (value: boolean) => void;
26
+ setKTX2SRGBTransferFunc: (value: boolean) => void; setSliceSourceImage: (slice: number, data: Uint8Array, width: number, height: number, png: boolean) => void;
27
+ setPerceptual: (value: boolean) => void; setMipSRGB: (value: boolean) => void; setQualityLevel: (value: number) => void;
28
+ setUASTC: (value: boolean) => void; setMipGen: (value: boolean) => void; encode: (output: Uint8Array) => number; delete: () => void;
29
+ }
30
+ interface BasisModule { initializeBasis: () => void; BasisEncoder: new () => unknown }
31
+ type BasisFactory = (options: { wasmBinary: Uint8Array; print: (text: string) => void; printErr: (text: string) => void }) => Promise<unknown>;
32
+ const methods = ['setCreateKTX2File', 'setKTX2UASTCSupercompression', 'setKTX2SRGBTransferFunc', 'setSliceSourceImage', 'setPerceptual', 'setMipSRGB', 'setQualityLevel', 'setUASTC', 'setMipGen', 'encode', 'delete'] as const;
33
+ function factory(value: unknown): value is BasisFactory { return typeof value === 'function'; }
34
+ function moduleApi(value: unknown): value is BasisModule { return typeof value === 'object' && value !== null && typeof Reflect.get(value, 'initializeBasis') === 'function' && typeof Reflect.get(value, 'BasisEncoder') === 'function'; }
35
+ function encoderApi(value: unknown): value is Encoder { return typeof value === 'object' && value !== null && methods.every(key => typeof Reflect.get(value, key) === 'function'); }
36
+ let basis: Promise<BasisModule> | undefined;
37
+ async function loadBasis(): Promise<BasisModule> {
38
+ const require = createRequire(join(import.meta.dirname, 'encoder.cjs')), directory = dirname(require.resolve(WORLD_TEXTURE_TOOL.package));
39
+ const glue = Uint8Array.from(readFileSync(join(directory, 'libs/basis_encoder.js'))), wasm = Uint8Array.from(readFileSync(join(directory, 'libs/basis_encoder.wasm')));
40
+ if (hashImmutableBytes(glue) !== WORLD_TEXTURE_TOOL.glue || hashImmutableBytes(wasm) !== WORLD_TEXTURE_TOOL.wasm) throw new Error('Pinned world texture encoder artifact mismatch');
41
+ // The package publishes its CommonJS Emscripten glue beneath type:module. Give those exact verified bytes
42
+ // a .cjs suffix; normal Node module loading executes them, with the WASM already supplied and no network.
43
+ const temporary = mkdtempSync(join(tmpdir(), 'wildshard-basis-'));
44
+ try {
45
+ const path = join(temporary, 'encoder.cjs'); writeFileSync(path, glue);
46
+ // oxlint-disable-next-line import/no-dynamic-require -- Only the SHA-verified pinned dependency bytes above are loaded here.
47
+ const entry: unknown = require(path); if (!factory(entry)) throw new Error('Invalid pinned encoder factory');
48
+ const loaded = await entry({ wasmBinary: wasm, print: () => undefined, printErr: () => undefined });
49
+ if (!moduleApi(loaded)) throw new Error('Invalid pinned encoder API');
50
+ loaded.initializeBasis(); return loaded;
51
+ } finally { rmSync(temporary, { recursive: true }); }
52
+ }
53
+ /** Encode embedded PNG/JPEG/WebP to deterministic single-threaded UASTC KTX2 with a complete mip chain.
54
+ * Colour/emissive uses sRGB; normal/ORM uses linear transfer. Source flipY is baked into raster rows for the glTF/KTX2 convention; atlas UVs stay unchanged. No system binary, CDN or author code is executed. */
55
+ export async function bakeWorldTexture(image: Uint8Array, colourSpace: 'srgb' | 'linear', options: { flipY?: boolean } = {}): Promise<Uint8Array> {
56
+ if (!['srgb', 'linear'].includes(colourSpace)) throw new Error('World texture transfer must be srgb or linear');
57
+ const info = await worldImageInfo(image), size: [number, number] = [info.width, info.height];
58
+ const decoded = await readImagePixels(image, options);
59
+ // Even a memo hit loads and verifies the exact pinned encoder artifacts.
60
+ basis ??= loadBasis(); const module = await basis;
61
+ const pixels = new Uint8Array(decoded.pixels.buffer, decoded.pixels.byteOffset, decoded.pixels.byteLength);
62
+ const key = hashImmutableBytes(new TextEncoder().encode(JSON.stringify({schema:1,tool:WORLD_TEXTURE_TOOL,settings,colourSpace,size,pixels:hashImmutableBytes(pixels)})));
63
+ return cachedWorldTexture(process.env['WILDSHARD_WORLD_TEXTURE_CACHE'],key,()=>{
64
+ const raw = new module.BasisEncoder();
65
+ if (!encoderApi(raw)) throw new Error('Invalid pinned encoder methods');
66
+ try {
67
+ const srgb = colourSpace === 'srgb';
68
+ raw.setCreateKTX2File(settings.ktx2); raw.setKTX2UASTCSupercompression(settings.supercompression); raw.setKTX2SRGBTransferFunc(srgb);
69
+ raw.setSliceSourceImage(0, pixels, size[0], size[1], settings.sourceIsPng); raw.setPerceptual(srgb); raw.setMipSRGB(srgb);
70
+ raw.setQualityLevel(settings.quality); raw.setUASTC(settings.uastc); raw.setMipGen(settings.mips);
71
+ const output = new Uint8Array(size[0] * size[1] * 4 + 1_048_576), length = raw.encode(output);
72
+ if (!Number.isSafeInteger(length) || length < 1 || length > output.length || length > 25_000_000) throw new Error('World texture encoding failed or exceeded wire cap');
73
+ return output.slice(0, length);
74
+ } finally { raw.delete(); }
75
+ },bytes=>{
76
+ parseKtx2(bytes);
77
+ const header = new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength),dfd = header.getUint32(48,true);
78
+ if(header.getUint32(20,true)!==size[0]||header.getUint32(24,true)!==size[1]
79
+ ||header.getUint32(40,true)!==1+Math.floor(Math.log2(Math.max(...size)))||bytes[dfd+14]!== (colourSpace==='srgb'?2:1)) throw new Error('World texture memo dimensions, mips or transfer differ');
80
+ });
81
+ }
@@ -0,0 +1,11 @@
1
+ // oxlint-disable-next-line import/no-nodejs-modules -- Build-only delivery selection uses the same gzip-9 as named blob intake.
2
+ import { gzipSync } from 'node:zlib';
3
+ import { compressGlb } from './glbCompression';
4
+
5
+ /** Lossless named-tile candidate: preserve every buffer-view word and scene field.
6
+ * Keep the original unless gzip-9 strictly improves; no quantization or reordering.
7
+ * The tile compiler derives identity and conservative costs from these final bytes. */
8
+ export function meshoptTileBytes(input: Uint8Array): Uint8Array {
9
+ const original = Uint8Array.from(input), packed = compressGlb(original);
10
+ return gzipSync(packed, { level: 9 }).length < gzipSync(original, { level: 9 }).length ? packed : original;
11
+ }
@@ -0,0 +1,62 @@
1
+ import * as v from 'valibot';
2
+ import { CHUNK_HALF, CHUNK_SIZE, CONTENT_CAPS } from '@wildshard/format/contentBounds';
3
+ import { TilesSchema } from '@wildshard/format/shardSections';
4
+ import type { Shardfile } from '@wildshard/format/shardSchema';
5
+
6
+ /** Native local-cell footprint in [minX, maxX, minZ, maxZ] order, owned by each author call. */
7
+ export function authorCellBounds(): readonly [number, number, number, number] {
8
+ return [-CHUNK_HALF, CHUNK_HALF, -CHUNK_HALF, CHUNK_HALF];
9
+ }
10
+
11
+ function checkedTiles(input: readonly Shardfile['tiles'][number][]): Shardfile['tiles'] {
12
+ const tiles = v.parse(TilesSchema, input), seen = new Set<string>();
13
+ for (const tile of tiles) {
14
+ const size = tile.lod === 0 ? CONTENT_CAPS.l0.size : CONTENT_CAPS.l1.size, count = CHUNK_SIZE / size;
15
+ const key = `${tile.lod}/${tile.x}/${tile.z}`;
16
+ if (seen.has(key) || tile.x >= count || tile.z >= count
17
+ || tile.bounds.min[0] !== -CHUNK_HALF + tile.x * size || tile.bounds.max[0] !== -CHUNK_HALF + (tile.x + 1) * size
18
+ || tile.bounds.min[2] !== -CHUNK_HALF + tile.z * size || tile.bounds.max[2] !== -CHUNK_HALF + (tile.z + 1) * size)
19
+ throw new Error(`Invalid tile grid address or bounds: ${key}`);
20
+ seen.add(key);
21
+ }
22
+ return tiles;
23
+ }
24
+
25
+ /** A full-world emitter declares vacant L0 squares explicitly, without fake
26
+ * assets or model rows. Existing tiles retain their order and exact metadata;
27
+ * sparse library/partial packers do not call this completion step. */
28
+ export function completeL0Tiles(input: readonly Shardfile['tiles'][number][]): Shardfile['tiles'] {
29
+ const tiles = checkedTiles(input), seen = new Set(tiles.map(tile => `${tile.lod}/${tile.x}/${tile.z}`));
30
+ const size = CONTENT_CAPS.l0.size, count = CHUNK_SIZE / size;
31
+ for (let z = 0; z < count; z++) for (let x = 0; x < count; x++) {
32
+ if (seen.has(`0/${x}/${z}`)) continue;
33
+ tiles.push({ lod: 0, x, z, bounds: { min: [-CHUNK_HALF + x * size, 0, -CHUNK_HALF + z * size],
34
+ max: [-CHUNK_HALF + (x + 1) * size, 0, -CHUNK_HALF + (z + 1) * size] },
35
+ geometricError: 0, files: [], compressed: 0, decoded: 0, gpu: 0, triangles: 0, draws: 0 });
36
+ }
37
+ return tiles;
38
+ }
39
+
40
+ /** Declare only L1 parents whose four explicit L0 children are empty. A
41
+ * partial/unknown inventory cannot establish absence. Occupied parents need
42
+ * real coarse geometry; this never creates a proxy or replaces an L1 row. */
43
+ export function completeEmptyL1Tiles(input: readonly Shardfile['tiles'][number][]): Shardfile['tiles'] {
44
+ const tiles = checkedTiles(input), children = new Map<string, boolean>();
45
+ const fineCount = CHUNK_SIZE / CONTENT_CAPS.l0.size;
46
+ for (const tile of tiles) if (tile.lod === 0) {
47
+ const zero = tile.compressed === 0 && tile.decoded === 0 && tile.gpu === 0 && tile.triangles === 0 && tile.draws === 0;
48
+ if (tile.files.length === 0 && (!zero || tile.geometricError !== 0)) throw new Error('Unknown L0 payload cannot prove an empty parent');
49
+ children.set(`${tile.x}/${tile.z}`, tile.files.length === 0);
50
+ }
51
+ if (children.size !== fineCount ** 2) throw new Error('Empty L1 completion requires every explicit L0 child');
52
+ const existing = new Set(tiles.filter(tile => tile.lod === 1).map(tile => `${tile.x}/${tile.z}`));
53
+ const size = CONTENT_CAPS.l1.size, count = CHUNK_SIZE / size;
54
+ for (let z = 0; z < count; z++) for (let x = 0; x < count; x++) {
55
+ if (existing.has(`${x}/${z}`) || ![children.get(`${2 * x}/${2 * z}`), children.get(`${2 * x + 1}/${2 * z}`),
56
+ children.get(`${2 * x}/${2 * z + 1}`), children.get(`${2 * x + 1}/${2 * z + 1}`)].every(value => value === true)) continue;
57
+ tiles.push({ lod: 1, x, z, bounds: { min: [-CHUNK_HALF + x * size, 0, -CHUNK_HALF + z * size],
58
+ max: [-CHUNK_HALF + (x + 1) * size, 0, -CHUNK_HALF + (z + 1) * size] },
59
+ geometricError: 0, files: [], compressed: 0, decoded: 0, gpu: 0, triangles: 0, draws: 0 });
60
+ }
61
+ return tiles;
62
+ }