@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.
- package/GUIDE.md +790 -0
- package/README.md +13 -5
- package/bin/wildshard.mjs +38 -0
- package/lint/declaration-config.d.mts +2 -0
- package/lint/declaration-config.mjs +19 -0
- package/lint/engine-plugin.d.mts +2 -0
- package/lint/engine-plugin.mjs +40 -0
- package/lint/host-callbacks.d.mts +6 -0
- package/lint/host-callbacks.mjs +123 -0
- package/lint/host-files.d.mts +1 -0
- package/lint/host-files.mjs +7 -0
- package/lint/layer-exports.d.mts +2 -0
- package/lint/layer-exports.mjs +21 -0
- package/lint/legacy-line-basis.json +995 -0
- package/lint/nine-tiling-baseline.json +35 -0
- package/lint/ratchet.json +11 -0
- package/lint/runtime-files.d.mts +12 -0
- package/lint/runtime-files.json +16 -0
- package/lint/runtime-files.mjs +69 -0
- package/lint/runtime-performance.d.mts +6 -0
- package/lint/runtime-performance.mjs +184 -0
- package/lint/sdk-plugin.d.mts +4 -0
- package/lint/sdk-plugin.mjs +134 -0
- package/lint/shardfile-boundaries.d.mts +10 -0
- package/lint/shardfile-boundaries.mjs +122 -0
- package/lint/tile-bake-debt.json +556 -0
- package/package.json +365 -3
- package/scripts/agent-parity.mjs +1524 -0
- package/scripts/agent-sync.mjs +518 -0
- package/scripts/apfs-clone.mjs +67 -0
- package/scripts/assert-store-layout.mjs +23 -0
- package/scripts/astc6-phone-cap.d.mts +3 -0
- package/scripts/astc6-phone-cap.mjs +137 -0
- package/scripts/audit-assets.d.mts +10 -0
- package/scripts/audit-assets.mjs +151 -0
- package/scripts/bake/coatFiles.d.mts +6 -0
- package/scripts/bake/coatFiles.mjs +37 -0
- package/scripts/bake/environment.d.mts +2 -0
- package/scripts/bake/environment.mjs +58 -0
- package/scripts/bake/far-proxies.mjs +45 -0
- package/scripts/bake/keyed-sky.d.mts +4 -0
- package/scripts/bake/keyed-sky.mjs +34 -0
- package/scripts/bake/movers.mjs +56 -0
- package/scripts/bake/nativeWorld.d.mts +6 -0
- package/scripts/bake/nativeWorld.mjs +43 -0
- package/scripts/bake/navmeshGround.ts +22 -0
- package/scripts/bake/near-placeholder.mjs +331 -0
- package/scripts/bake/placeholderShards.mjs +41 -0
- package/scripts/bake/skins.mjs +15 -0
- package/scripts/bake/template-skins.mjs +33 -0
- package/scripts/bake/viewmodelBytes.ts +26 -0
- package/scripts/bake/viewmodelPage.ts +11 -0
- package/scripts/bake/worldHost.d.mts +35 -0
- package/scripts/bake/worldHost.mjs +110 -0
- package/scripts/bake-astc6.cache.json +80 -0
- package/scripts/bake-astc6.far-reach.cache.json +23 -0
- package/scripts/bake-astc6.list.json +111 -0
- package/scripts/bake-astc6.mjs +279 -0
- package/scripts/bake-astc6.nalati-grasslands.cache.json +42 -0
- package/scripts/bake-catalogue.mjs +44 -0
- package/scripts/bake-check.mjs +54 -0
- package/scripts/bake-chunk.mjs +124 -0
- package/scripts/bake-cloud-field.mjs +24 -0
- package/scripts/bake-coats.mjs +110 -0
- package/scripts/bake-data-maps.d.mts +24 -0
- package/scripts/bake-data-maps.mjs +72 -0
- package/scripts/bake-entry-programs.mjs +117 -0
- package/scripts/bake-geometry.mjs +106 -0
- package/scripts/bake-hybrid-tiles.mjs +28 -0
- package/scripts/bake-ktx2.cache.json +276 -0
- package/scripts/bake-ktx2.list.json +365 -0
- package/scripts/bake-ktx2.mjs +477 -0
- package/scripts/bake-map-glb.mjs +127 -0
- package/scripts/bake-map-rest.d.mts +7 -0
- package/scripts/bake-map-rest.mjs +50 -0
- package/scripts/bake-maps.mjs +200 -0
- package/scripts/bake-navmesh.mjs +259 -0
- package/scripts/bake-packs.mjs +129 -0
- package/scripts/bake-pickups.mjs +102 -0
- package/scripts/bake-query-terrain.mjs +64 -0
- package/scripts/bake-recurve-pool.mjs +16 -0
- package/scripts/bake-section-schemas.d.mts +3 -0
- package/scripts/bake-template-shardfile.mjs +32 -0
- package/scripts/bake-textures.mjs +80 -0
- package/scripts/bake-viewmodel-sets.json +45 -0
- package/scripts/bake-viewmodel-sets.mjs +137 -0
- package/scripts/bake-voxel-ao.mjs +119 -0
- package/scripts/bake-water-ripples.mjs +25 -0
- package/scripts/blender/README.md +129 -0
- package/scripts/blender/build.sh +166 -0
- package/scripts/blender/lib/export-scene.mjs +129 -0
- package/scripts/blender/lib/glb-digest.mjs +188 -0
- package/scripts/blender/lib/glb.py +68 -0
- package/scripts/blender/lib/save_blend.py +17 -0
- package/scripts/blender/lib/world_fixture.py +55 -0
- package/scripts/blender/targets.json +591 -0
- package/scripts/build-sdk.mjs +95 -0
- package/scripts/build-shardfiles.d.mts +7 -0
- package/scripts/build-shardfiles.mjs +206 -0
- package/scripts/capture-hero.mjs +137 -0
- package/scripts/check-lift-review.mjs +23 -0
- package/scripts/chromium-keychain-check.mjs +139 -0
- package/scripts/chromium-keychain.d.mts +1 -0
- package/scripts/chromium-keychain.mjs +5 -0
- package/scripts/compile-script.d.mts +3 -0
- package/scripts/compile-script.mjs +8 -0
- package/scripts/creature-color.mjs +255 -0
- package/scripts/decide/calibrate.py +127 -0
- package/scripts/decide/calibration/2026-10-03/labels-s1.tsv +281 -0
- package/scripts/decide/calibration/2026-10-03/labels-s2.tsv +97 -0
- package/scripts/decide/calibration/2026-10-03/labels-s3.tsv +48 -0
- package/scripts/decide/calibration/2026-10-03/labels-s3b.tsv +26 -0
- package/scripts/decide/calibration/2026-10-03/res-capture-status-v1.jsonl +376 -0
- package/scripts/decide/calibration/2026-10-03/res-text-garbled-strings.jsonl +48 -0
- package/scripts/decide/calibration/2026-10-03/res-text-garbled-v1.jsonl +73 -0
- package/scripts/decide/decide.py +262 -0
- package/scripts/decide/decide.sh +50 -0
- package/scripts/decide/layer-purity-pilot.mjs +41 -0
- package/scripts/decide/sets/capture-status.json +46 -0
- package/scripts/decide/sets/layer-purity.json +28 -0
- package/scripts/decide/sets/text-garbled.json +17 -0
- package/scripts/decide/test_decide.py +37 -0
- package/scripts/docs.mjs +15 -0
- package/scripts/entry-reads/crawl.ts +152 -0
- package/scripts/entry-reads/tsconfig.json +25 -0
- package/scripts/gen-format-schema.d.mts +2 -0
- package/scripts/gen-format-schema.mjs +21 -0
- package/scripts/gen-host-catalogue.d.mts +14 -0
- package/scripts/gen-host-catalogue.mjs +108 -0
- package/scripts/gen-shard-layout-doc.d.mts +4 -0
- package/scripts/gen-shard-layout-doc.mjs +55 -0
- package/scripts/gen-shards.d.mts +17 -0
- package/scripts/gen-shards.mjs +311 -0
- package/scripts/goldens/capture-inputs.d.mts +4 -0
- package/scripts/goldens/capture-inputs.mjs +34 -0
- package/scripts/goldens/colour_shift.py +27 -0
- package/scripts/goldens/native-residency.d.mts +10 -0
- package/scripts/goldens/native-residency.mjs +104 -0
- package/scripts/goldens/plot-inputs.d.mts +12 -0
- package/scripts/goldens/plot-inputs.mjs +46 -0
- package/scripts/gpu-texmem.mjs +98 -0
- package/scripts/horizon-matte/config.py +24 -0
- package/scripts/horizon-matte/encode.py +91 -0
- package/scripts/horizon-matte/key.py +141 -0
- package/scripts/horizon-matte/mkjobs.py +33 -0
- package/scripts/horizon-matte/mkjobs_day2.py +11 -0
- package/scripts/horizon-matte/overlap.py +80 -0
- package/scripts/horizon-matte/run_codex.py +57 -0
- package/scripts/horizon-matte/stitch.py +133 -0
- package/scripts/img2mesh/CC0.md +105 -0
- package/scripts/img2mesh/README.md +209 -0
- package/scripts/img2mesh/ab_board.py +102 -0
- package/scripts/img2mesh/birds/birds.json +255 -0
- package/scripts/img2mesh/birds/birds_atlas.py +150 -0
- package/scripts/img2mesh/birds/birds_fix_preview.mjs +103 -0
- package/scripts/img2mesh/birds/birds_fix_render.py +75 -0
- package/scripts/img2mesh/birds/birds_pack.py +110 -0
- package/scripts/img2mesh/birds/birds_phone_b.py +112 -0
- package/scripts/img2mesh/birds/birds_post.py +550 -0
- package/scripts/img2mesh/birds/birds_render.py +125 -0
- package/scripts/img2mesh/birds/birds_sheet.py +33 -0
- package/scripts/img2mesh/birds/birds_view.py +60 -0
- package/scripts/img2mesh/board.py +100 -0
- package/scripts/img2mesh/build_cc0.sh +52 -0
- package/scripts/img2mesh/build_driftwood.sh +12 -0
- package/scripts/img2mesh/build_faces.sh +53 -0
- package/scripts/img2mesh/build_props.py +81 -0
- package/scripts/img2mesh/cc0_export.py +186 -0
- package/scripts/img2mesh/driftwood_post.py +571 -0
- package/scripts/img2mesh/e304_faces.sh +67 -0
- package/scripts/img2mesh/face_remaster.py +911 -0
- package/scripts/img2mesh/face_views.py +95 -0
- package/scripts/img2mesh/faces-e304.json +9 -0
- package/scripts/img2mesh/faces.json +30 -0
- package/scripts/img2mesh/head_cut.py +100 -0
- package/scripts/img2mesh/hi3d_paint.py +94 -0
- package/scripts/img2mesh/hi3d_refine.py +161 -0
- package/scripts/img2mesh/hunyuan_cpu_rasterizer.sh +42 -0
- package/scripts/img2mesh/pine_hollow_phone.sh +13 -0
- package/scripts/img2mesh/props/coral-arch.json +32 -0
- package/scripts/img2mesh/props/ember-furnace.json +30 -0
- package/scripts/img2mesh/props/night-market-gate.json +10 -0
- package/scripts/img2mesh/render_still.py +86 -0
- package/scripts/img2mesh/rig_strip.mjs +46 -0
- package/scripts/img2mesh/rig_transfer.mjs +104 -0
- package/scripts/img2mesh/split_sheet.py +48 -0
- package/scripts/img2mesh/trellis_batch.py +110 -0
- package/scripts/img2mesh/versus_board.py +114 -0
- package/scripts/import-bundle.d.mts +2 -0
- package/scripts/import-bundle.mjs +20 -0
- package/scripts/ktx2-ab-board.py +133 -0
- package/scripts/ktx2-ab.mjs +111 -0
- package/scripts/ktx2-settings.mjs +18 -0
- package/scripts/land.d.mts +14 -0
- package/scripts/land.mjs +809 -0
- package/scripts/lint-dispatch.mjs +14 -0
- package/scripts/map-bake-frames.d.mts +4 -0
- package/scripts/map-bake-frames.mjs +23 -0
- package/scripts/map-geometry.d.mts +9 -0
- package/scripts/map-geometry.mjs +29 -0
- package/scripts/map-world.mjs +162 -0
- package/scripts/mockup-local.sh +46 -0
- package/scripts/music/export-midi.mjs +68 -0
- package/scripts/music/gen/analyze.py +308 -0
- package/scripts/music/gen/audio_jobs.py +46 -0
- package/scripts/music/gen/briefs.json +51 -0
- package/scripts/music/gen/build_page.py +334 -0
- package/scripts/music/gen/folk.json +3187 -0
- package/scripts/music/gen/gen_ace_step.py +156 -0
- package/scripts/music/gen/gen_heartmula.py +187 -0
- package/scripts/music/gen/gen_minimax.py +143 -0
- package/scripts/music/gen/gen_sao.py +122 -0
- package/scripts/music/gen/gen_sao_small.py +104 -0
- package/scripts/music/gen/gen_sfx.py +98 -0
- package/scripts/music/gen/gen_sfx_ezaudio.py +112 -0
- package/scripts/music/gen/gen_sfx_moss.py +112 -0
- package/scripts/music/gen/models.json +61 -0
- package/scripts/music/gen/nalati-jobs.json +104 -0
- package/scripts/music/gen/nalati-score-build.json +119 -0
- package/scripts/music/gen/nalati-score.json +3448 -0
- package/scripts/music/gen/ob7-fit-decisions.json +38 -0
- package/scripts/music/gen/ob7-score-jobs.json +152 -0
- package/scripts/music/gen/ob7-sfx-jobs.json +897 -0
- package/scripts/music/gen/ob7_build.py +469 -0
- package/scripts/music/gen/ob7_generate.py +67 -0
- package/scripts/music/gen/ob7_run.sh +42 -0
- package/scripts/music/gen/orchestral.json +3187 -0
- package/scripts/music/gen/own_score.py +486 -0
- package/scripts/music/gen/ph-jobs.json +27 -0
- package/scripts/music/gen/ph_page.py +222 -0
- package/scripts/music/gen/piano.json +3175 -0
- package/scripts/music/gen/rank_v3.py +248 -0
- package/scripts/music/gen/sfx-best.json +2486 -0
- package/scripts/music/gen/sfx-ezaudio.json +4082 -0
- package/scripts/music/gen/sfx-jobs.json +57 -0
- package/scripts/music/gen/sfx-minimax-jobs.json +16 -0
- package/scripts/music/gen/sfx-minimax.json +289 -0
- package/scripts/music/gen/sfx-moss.json +4082 -0
- package/scripts/music/gen/sfx-nalati-b3-jobs.json +17 -0
- package/scripts/music/gen/sfx-nalati-jobs.json +338 -0
- package/scripts/music/gen/sfx-nalati.json +11202 -0
- package/scripts/music/gen/sfx-nd-jobs.json +57 -0
- package/scripts/music/gen/sfx-nd-moss.json +2097 -0
- package/scripts/music/gen/sfx-nd-sa3-medium.json +2097 -0
- package/scripts/music/gen/sfx-nd-summary.json +38 -0
- package/scripts/music/gen/sfx-peaks.json +7 -0
- package/scripts/music/gen/sfx-ph-jobs.json +169 -0
- package/scripts/music/gen/sfx-ph-moss.json +6564 -0
- package/scripts/music/gen/sfx-ph-sa3-medium.json +7239 -0
- package/scripts/music/gen/sfx-ph-summary.json +63 -0
- package/scripts/music/gen/sfx-sa3-medium.json +4082 -0
- package/scripts/music/gen/sfx-sa3.json +4082 -0
- package/scripts/music/gen/sfx-summary.json +107 -0
- package/scripts/music/gen/sfx_build.py +332 -0
- package/scripts/music/gen/sfx_merge.py +255 -0
- package/scripts/music/gen/sfx_minimax.py +61 -0
- package/scripts/music/gen/sfx_nalati.py +331 -0
- package/scripts/music/gen/sfx_sprite.py +424 -0
- package/scripts/music/gen/stems.py +539 -0
- package/scripts/music/gen/test_loop_meter.py +29 -0
- package/scripts/music/gen/test_ob7_provenance.py +77 -0
- package/scripts/music/gen/v3-folk-build.json +148 -0
- package/scripts/music/gen/v3-folk.json +1818 -0
- package/scripts/music/gen/v3-jobs.json +145 -0
- package/scripts/music/gen/v3-orchestral-build.json +148 -0
- package/scripts/music/gen/v3-orchestral.json +1813 -0
- package/scripts/music/gen/v3-ph-folk-build.json +94 -0
- package/scripts/music/gen/v3-ph-folk.json +1806 -0
- package/scripts/music/gen/v3-ph-orchestral-build.json +94 -0
- package/scripts/music/gen/v3-ph-orchestral.json +1824 -0
- package/scripts/music/gen/v3-ph-piano-build.json +94 -0
- package/scripts/music/gen/v3-ph-piano.json +1818 -0
- package/scripts/music/gen/v3-piano-build.json +148 -0
- package/scripts/music/gen/v3-piano.json +1813 -0
- package/scripts/music/wildshard-theme.mid +0 -0
- package/scripts/music/wildshard-trailer30.mid +0 -0
- package/scripts/named-blob-output.d.mts +8 -0
- package/scripts/named-blob-output.mjs +48 -0
- package/scripts/pack-all.mjs +15 -0
- package/scripts/pid-lock.d.mts +1 -0
- package/scripts/pid-lock.mjs +63 -0
- package/scripts/practice/bake_dummy.py +53 -0
- package/scripts/practice/build_dummies.sh +43 -0
- package/scripts/practice/dummy_parts.py +568 -0
- package/scripts/practice/dummy_rig_gate.py +139 -0
- package/scripts/practice/gate_sheet.py +36 -0
- package/scripts/practice/generate_dummy_unimate.py +132 -0
- package/scripts/practice/pack_dummy.mjs +59 -0
- package/scripts/practice/repair_dummy_weights.mjs +68 -0
- package/scripts/practice/rig_dummy.py +828 -0
- package/scripts/practice/verify_unimate_skin.mjs +356 -0
- package/scripts/preparation-seed.mjs +15 -0
- package/scripts/prepare-basis-tool.mjs +6 -0
- package/scripts/prepare-product.d.mts +14 -0
- package/scripts/prepare-product.mjs +101 -0
- package/scripts/product-build-tools.d.mts +3 -0
- package/scripts/product-build-tools.json +3 -0
- package/scripts/product-build-tools.mjs +31 -0
- package/scripts/publish-public.mjs +7 -0
- package/scripts/push-tables.d.mts +1 -0
- package/scripts/push-tables.mjs +28 -0
- package/scripts/record-shard-mounts.mjs +133 -0
- package/scripts/sdk-externals.d.mts +2 -0
- package/scripts/sdk-externals.mjs +2 -0
- package/scripts/section-inventory.ts +209 -0
- package/scripts/select-candidate.mjs +15 -0
- package/scripts/shard-build-pool.d.mts +4 -0
- package/scripts/shard-build-pool.mjs +53 -0
- package/scripts/shard-line-baseline.json +17 -0
- package/scripts/shard-milestones.d.mts +15 -0
- package/scripts/shard-milestones.mjs +105 -0
- package/scripts/shard-output-report.d.mts +9 -0
- package/scripts/shard-output-report.mjs +85 -0
- package/scripts/shard-platform-cli.mjs +93 -0
- package/scripts/shard-progress.mjs +212 -0
- package/scripts/shard-timelapse.py +102 -0
- package/scripts/shardfile-cold-boot.mjs +79 -0
- package/scripts/shardfile-vite.d.mts +4 -0
- package/scripts/shardfile-vite.mjs +20 -0
- package/scripts/simplify-models.mjs +24 -0
- package/scripts/site-facts.mjs +88 -0
- package/scripts/test-template-gate.mjs +44 -0
- package/scripts/test_golden_compare.py +68 -0
- package/scripts/tex-tiers.cache.json +181 -0
- package/scripts/tex-tiers.mjs +240 -0
- package/scripts/texmem-probe.mjs +184 -0
- package/scripts/unused-assets.mjs +173 -0
- package/scripts/vite-tmp.d.mts +23 -0
- package/scripts/vite-tmp.mjs +157 -0
- package/scripts/wave-line-baselines.json +32 -0
- package/scripts/wildshard.d.mts +4 -0
- package/scripts/wildshard.mjs +105 -0
- package/scripts/witness-checkpoints.d.mts +10 -0
- package/scripts/witness-checkpoints.mjs +84 -0
- package/scripts/witness-generation.d.mts +10 -0
- package/scripts/witness-generation.mjs +45 -0
- package/scripts/witness-manifests.d.mts +8 -0
- package/scripts/witness-manifests.mjs +157 -0
- package/scripts/worktree-ignore.d.mts +4 -0
- package/scripts/worktree-ignore.mjs +36 -0
- package/scripts/worktree-reap.mjs +214 -0
- package/scripts/worktree.mjs +396 -0
- package/scripts/worldclaw/capture-front.sh +28 -0
- package/scripts/worldclaw/design-template.md +62 -0
- package/scripts/worldclaw/spec-map.py +92 -0
- package/scripts/worldclaw/spec.ts +96 -0
- package/skills/wildshard/SKILL.md +50 -0
- package/skills/wildshard-goldens/SKILL.md +54 -0
- package/skills/wildshard-mockup-to-model/SKILL.md +56 -0
- package/skills/wildshard-upgrade/SKILL.md +46 -0
- package/src/.oxfmtrc.json +50 -0
- package/src/.oxlintrc.json +173 -0
- package/src/cli/account/account.ts +199 -0
- package/src/cli/account/command.ts +193 -0
- package/src/cli/account/key.ts +154 -0
- package/src/cli/args.ts +97 -0
- package/src/cli/audio/audio.ts +24 -0
- package/src/cli/bin.mjs +8 -0
- package/src/cli/delete/delete.ts +258 -0
- package/src/cli/help.ts +196 -0
- package/src/cli/hero/adopt.ts +103 -0
- package/src/cli/hero/hero.ts +112 -0
- package/src/cli/hero/stamp.ts +298 -0
- package/src/cli/main.ts +292 -0
- package/src/cli/report.ts +16 -0
- package/src/cli/shardfile/command.ts +50 -0
- package/src/cli/shardfile/shardfile.ts +192 -0
- package/src/cli/upload/api.ts +246 -0
- package/src/cli/upload/compress.ts +55 -0
- package/src/cli/upload/hero.ts +62 -0
- package/src/cli/upload/placement.ts +115 -0
- package/src/cli/upload/provenance.ts +192 -0
- package/src/cli/upload/signature.ts +30 -0
- package/src/cli/upload/upload.ts +269 -0
- package/src/cli/upload/validate.ts +74 -0
- package/src/cli/upload/wire.ts +147 -0
- package/src/cli/version.ts +63 -0
- package/src/commons/bake/portableMath.ts +187 -0
- package/src/commons/catalogue.ts +10 -0
- package/src/commons/courseProgram.ts +32 -0
- package/src/commons/practiceCourse.ts +16 -0
- package/src/commons/scripts/abi.as +14 -0
- package/src/commons/scripts/bridge.as +14 -0
- package/src/commons/scripts/course.as +63 -0
- package/src/scripts/ask-new.sh +29 -0
- package/src/scripts/asks.mjs +141 -0
- package/src/scripts/herdr-prompt.sh +34 -0
- package/src/scripts/herdr-question-open.sh +67 -0
- package/src/scripts/md-wrap.mjs +229 -0
- package/src/server/app.ts +19 -0
- package/src/server/serve.ts +49 -0
- package/src/sharddev/admission.ts +7 -0
- package/src/sharddev/arenaView.ts +15 -0
- package/src/sharddev/as/groupBankV2.ts +36 -0
- package/src/sharddev/as/groupStepV2.ts +13 -0
- package/src/sharddev/as/ws.ts +30 -0
- package/src/sharddev/as/wsV2.ts +180 -0
- package/src/sharddev/assemblyscriptCompiler.d.mts +5 -0
- package/src/sharddev/assemblyscriptCompiler.mjs +14 -0
- package/src/sharddev/assetHandle.ts +84 -0
- package/src/sharddev/assetOwner.ts +70 -0
- package/src/sharddev/assetScope.ts +30 -0
- package/src/sharddev/assets.ts +21 -0
- package/src/sharddev/audio.ts +9 -0
- package/src/sharddev/audioEncode.ts +211 -0
- package/src/sharddev/author.ts +3 -0
- package/src/sharddev/authorError.ts +28 -0
- package/src/sharddev/authorManifest.ts +39 -0
- package/src/sharddev/bake/annulus.ts +19 -0
- package/src/sharddev/bake/assemblyscriptMemo.ts +76 -0
- package/src/sharddev/bake/assemblyscriptMemoPort.ts +4 -0
- package/src/sharddev/bake/authoredWorld.ts +201 -0
- package/src/sharddev/bake/basisEncoder.ts +95 -0
- package/src/sharddev/bake/basisGlb.ts +85 -0
- package/src/sharddev/bake/basisTool.ts +74 -0
- package/src/sharddev/bake/basisToolInputs.ts +476 -0
- package/src/sharddev/bake/byteCodec.ts +33 -0
- package/src/sharddev/bake/canvasAtlas.ts +406 -0
- package/src/sharddev/bake/coarseCopy.ts +59 -0
- package/src/sharddev/bake/colliders.ts +87 -0
- package/src/sharddev/bake/compactGlb.ts +224 -0
- package/src/sharddev/bake/compileScript.ts +119 -0
- package/src/sharddev/bake/compileScriptV2.ts +75 -0
- package/src/sharddev/bake/contactRows.ts +84 -0
- package/src/sharddev/bake/creaturePlacement.ts +117 -0
- package/src/sharddev/bake/export.ts +67 -0
- package/src/sharddev/bake/facetedGeometry.ts +379 -0
- package/src/sharddev/bake/farImpostor.ts +120 -0
- package/src/sharddev/bake/forest.ts +100 -0
- package/src/sharddev/bake/format-hook.mjs +2 -0
- package/src/sharddev/bake/generatorGlb.ts +23 -0
- package/src/sharddev/bake/geometryBounds.ts +77 -0
- package/src/sharddev/bake/geometryError.ts +48 -0
- package/src/sharddev/bake/glb.ts +355 -0
- package/src/sharddev/bake/glbCompression.ts +143 -0
- package/src/sharddev/bake/gltfSource.ts +59 -0
- package/src/sharddev/bake/groundMap.ts +142 -0
- package/src/sharddev/bake/image.ts +20 -0
- package/src/sharddev/bake/isleMap.ts +64 -0
- package/src/sharddev/bake/json.mjs +84 -0
- package/src/sharddev/bake/keyedSky.ts +47 -0
- package/src/sharddev/bake/keyedSkyMemo.ts +39 -0
- package/src/sharddev/bake/kinds.ts +137 -0
- package/src/sharddev/bake/lightSources.ts +31 -0
- package/src/sharddev/bake/mapAssembly.ts +84 -0
- package/src/sharddev/bake/mapRaster.ts +173 -0
- package/src/sharddev/bake/mapRest.ts +57 -0
- package/src/sharddev/bake/mapScenes.ts +234 -0
- package/src/sharddev/bake/materialGraph.ts +32 -0
- package/src/sharddev/bake/meadow.ts +27 -0
- package/src/sharddev/bake/meshoptChoiceMemo.ts +34 -0
- package/src/sharddev/bake/nativeInteractionFacts.ts +5 -0
- package/src/sharddev/bake/nativeLattice.ts +178 -0
- package/src/sharddev/bake/nativeRaster.ts +106 -0
- package/src/sharddev/bake/nativeTerrainField.ts +11 -0
- package/src/sharddev/bake/navigation-json.mjs +38 -0
- package/src/sharddev/bake/navigation.ts +113 -0
- package/src/sharddev/bake/navigationAsset.ts +18 -0
- package/src/sharddev/bake/nearPlaceholder.ts +206 -0
- package/src/sharddev/bake/normalizeRig.ts +80 -0
- package/src/sharddev/bake/phoneAstc.ts +93 -0
- package/src/sharddev/bake/placeholders.ts +581 -0
- package/src/sharddev/bake/placement.ts +80 -0
- package/src/sharddev/bake/portableBytes.ts +18 -0
- package/src/sharddev/bake/portableBytesMemo.ts +50 -0
- package/src/sharddev/bake/practiceCourse.ts +49 -0
- package/src/sharddev/bake/primitives.ts +96 -0
- package/src/sharddev/bake/props.ts +443 -0
- package/src/sharddev/bake/questPlacement.ts +98 -0
- package/src/sharddev/bake/rawTexture.ts +26 -0
- package/src/sharddev/bake/riderArms.ts +97 -0
- package/src/sharddev/bake/rig.ts +95 -0
- package/src/sharddev/bake/riggedHullRecipes.ts +40 -0
- package/src/sharddev/bake/signPlacements.ts +25 -0
- package/src/sharddev/bake/simplifier.ts +52 -0
- package/src/sharddev/bake/skinned.ts +312 -0
- package/src/sharddev/bake/slabChunks.ts +149 -0
- package/src/sharddev/bake/slabs.ts +263 -0
- package/src/sharddev/bake/source-loader.mjs +55 -0
- package/src/sharddev/bake/sourceMetadata.ts +54 -0
- package/src/sharddev/bake/species.ts +368 -0
- package/src/sharddev/bake/specimenCatalogue.ts +47 -0
- package/src/sharddev/bake/splatGround.ts +141 -0
- package/src/sharddev/bake/staticMaterials.ts +171 -0
- package/src/sharddev/bake/terrain.ts +195 -0
- package/src/sharddev/bake/texture.ts +33 -0
- package/src/sharddev/bake/textureWasm.ts +81 -0
- package/src/sharddev/bake/tileEncoder.ts +11 -0
- package/src/sharddev/bake/tileGrid.ts +62 -0
- package/src/sharddev/bake/v2Finite.ts +160 -0
- package/src/sharddev/bake/v2Fuel.ts +71 -0
- package/src/sharddev/bake/wholePartition.ts +74 -0
- package/src/sharddev/bake/wholePieceJoin.ts +147 -0
- package/src/sharddev/bake/world.ts +173 -0
- package/src/sharddev/bake/worldCollision.ts +128 -0
- package/src/sharddev/bake/worldGeometry.ts +237 -0
- package/src/sharddev/bake/worldGlb.ts +123 -0
- package/src/sharddev/bake/worldImage.ts +12 -0
- package/src/sharddev/bake/worldLod.ts +128 -0
- package/src/sharddev/bake/worldRows.ts +102 -0
- package/src/sharddev/bake/worldTextureMemo.ts +63 -0
- package/src/sharddev/bake/zstdBytesMemo.ts +52 -0
- package/src/sharddev/bake.ts +193 -0
- package/src/sharddev/bakePublication.ts +31 -0
- package/src/sharddev/behaviourSource.ts +94 -0
- package/src/sharddev/bin/wildshard.mjs +7 -0
- package/src/sharddev/blobBytes.ts +65 -0
- package/src/sharddev/blobs.ts +138 -0
- package/src/sharddev/bootInventory.ts +129 -0
- package/src/sharddev/bossProfiles.ts +18 -0
- package/src/sharddev/buildBehaviour.ts +77 -0
- package/src/sharddev/buildCacheMetrics.ts +17 -0
- package/src/sharddev/buildDecisionScripts.ts +122 -0
- package/src/sharddev/check.ts +117 -0
- package/src/sharddev/checkProject.ts +126 -0
- package/src/sharddev/cli.ts +191 -0
- package/src/sharddev/clientChannels.ts +169 -0
- package/src/sharddev/clientScripts.ts +10 -0
- package/src/sharddev/commons.ts +77 -0
- package/src/sharddev/commonsCosts.ts +11 -0
- package/src/sharddev/compileMovers.ts +11 -0
- package/src/sharddev/configBoundary.ts +6 -0
- package/src/sharddev/cookInput.ts +40 -0
- package/src/sharddev/crowds.ts +6 -0
- package/src/sharddev/decisionBindingMap.ts +11 -0
- package/src/sharddev/decisionScriptBindings.ts +117 -0
- package/src/sharddev/decisionScripts.ts +28 -0
- package/src/sharddev/decisionSource.ts +51 -0
- package/src/sharddev/dev.ts +113 -0
- package/src/sharddev/director.ts +26 -0
- package/src/sharddev/directorAbi.ts +77 -0
- package/src/sharddev/discoveryDocument.ts +97 -0
- package/src/sharddev/draft.ts +11 -0
- package/src/sharddev/eliteEntryRows.ts +29 -0
- package/src/sharddev/entries.ts +76 -0
- package/src/sharddev/entryReads.ts +73 -0
- package/src/sharddev/executeBundle.ts +55 -0
- package/src/sharddev/finds.ts +5 -0
- package/src/sharddev/formatJsonSchema.ts +3 -0
- package/src/sharddev/generationCache.ts +257 -0
- package/src/sharddev/generationRecipe.ts +94 -0
- package/src/sharddev/handwritten.ts +110 -0
- package/src/sharddev/immutable.ts +14 -0
- package/src/sharddev/interactions.ts +38 -0
- package/src/sharddev/kit/bakedGeometry.ts +16 -0
- package/src/sharddev/kit/geometryPack.ts +110 -0
- package/src/sharddev/ledger.ts +13 -0
- package/src/sharddev/looks/tileField.ts +67 -0
- package/src/sharddev/materialGraphFiles.ts +57 -0
- package/src/sharddev/materials.ts +574 -0
- package/src/sharddev/measure.ts +18 -0
- package/src/sharddev/modes.ts +115 -0
- package/src/sharddev/moverPrograms.ts +213 -0
- package/src/sharddev/movers.ts +75 -0
- package/src/sharddev/nativePopulationRows.ts +46 -0
- package/src/sharddev/newProject.ts +247 -0
- package/src/sharddev/noise.ts +54 -0
- package/src/sharddev/outputProduct.ts +188 -0
- package/src/sharddev/outputRuntime.ts +66 -0
- package/src/sharddev/performancePolicy.ts +18 -0
- package/src/sharddev/phasedBoss.ts +34 -0
- package/src/sharddev/physics.ts +194 -0
- package/src/sharddev/platformSections.ts +42 -0
- package/src/sharddev/plumbing.ts +8 -0
- package/src/sharddev/productOutput.ts +128 -0
- package/src/sharddev/project.ts +337 -0
- package/src/sharddev/projectCompilerIdentity.ts +94 -0
- package/src/sharddev/projectDecisions.ts +66 -0
- package/src/sharddev/projectEntryProof.ts +32 -0
- package/src/sharddev/projectGeneration.ts +219 -0
- package/src/sharddev/projectInputFiles.ts +47 -0
- package/src/sharddev/projectManifest.ts +108 -0
- package/src/sharddev/projectMap.ts +35 -0
- package/src/sharddev/projectOutput.ts +242 -0
- package/src/sharddev/projectPolicy.ts +17 -0
- package/src/sharddev/projectSections.ts +27 -0
- package/src/sharddev/questGraph.ts +25 -0
- package/src/sharddev/quests.ts +65 -0
- package/src/sharddev/random.ts +61 -0
- package/src/sharddev/refusals.ts +234 -0
- package/src/sharddev/reportCard.ts +13 -0
- package/src/sharddev/returnProjectionV2.ts +81 -0
- package/src/sharddev/rows.ts +192 -0
- package/src/sharddev/runtimeImports.ts +38 -0
- package/src/sharddev/runtimeMirrors.ts +39 -0
- package/src/sharddev/runtimePerformance.ts +38 -0
- package/src/sharddev/scene.ts +321 -0
- package/src/sharddev/sceneAnimation.ts +54 -0
- package/src/sharddev/sceneAudio.ts +64 -0
- package/src/sharddev/sceneDeclarations.ts +100 -0
- package/src/sharddev/sceneGraph.ts +139 -0
- package/src/sharddev/sceneTransform.ts +12 -0
- package/src/sharddev/schemaValidation.ts +61 -0
- package/src/sharddev/sections.ts +47 -0
- package/src/sharddev/shardSource.ts +59 -0
- package/src/sharddev/sourceReader.ts +26 -0
- package/src/sharddev/spawns.ts +38 -0
- package/src/sharddev/species/clips.ts +24 -0
- package/src/sharddev/species.ts +29 -0
- package/src/sharddev/speciesBrains.ts +19 -0
- package/src/sharddev/synth.ts +66 -0
- package/src/sharddev/test/compileDualScriptV2.ts +71 -0
- package/src/sharddev/test/compileSimV2.ts +21 -0
- package/src/sharddev/test/diskScriptScenario.ts +86 -0
- package/src/sharddev/test/scriptScenario.ts +249 -0
- package/src/sharddev/test/scriptSource.ts +12 -0
- package/src/sharddev/version.ts +4 -0
- package/src/sharddev/weapons/bowProfile.ts +20 -0
- package/src/sharddev/weapons/firearmRows.ts +11 -0
- package/src/sharddev/weapons/meleeProfile.ts +71 -0
- package/src/sharddev/weapons/thrownProfile.ts +10 -0
- package/src/sharddev/worldScenes.ts +308 -0
- package/src/sharddev/worldSource.ts +82 -0
- package/src/shards/_template/README.md +78 -0
- package/src/shards/_template/assets/2bf489fdb15f1734ddb4c4f32d500ec6da85c765ec7a4eb28dc6781160e7ec8c +0 -0
- package/src/shards/_template/assets/97ec4d8f75f5fa6239ee919444d6dc19fd35896bb305930c1f050ac6e0e0e6a6 +1 -0
- package/src/shards/_template/assets/a6a587a31327f936b1b04c05ade818c73fc8964260918662db43539465e27586 +0 -0
- package/src/shards/_template/assets/b4fbde0422e125b498c3dc8b9a5cc2516c8598f09e9d0e5f6b639b32f98179e6 +0 -0
- package/src/shards/_template/assets/bfa4dfc9c18979f904557ee8deab0058b8a399be10266f5fb1578b403f482fd4 +1 -0
- package/src/shards/_template/assets/ef3b7ff4fd22715771cb7d68a3977a903c5e7c3dc293542687d04b3ef3ace2cb +0 -0
- package/src/shards/_template/assets/f2db05998615ce1cb79ea96be32c168842eb6a2b34ec01feb86d36404603ee54 +0 -0
- package/src/shards/_template/assets/fef98ebb7fce6f66b26e78ac699e5c90f9bdcfaf8cabeb2b58125347eea8b4ab +0 -0
- package/src/shards/_template/behaviour/boss.as +39 -0
- package/src/shards/_template/behaviour/door.as +32 -0
- package/src/shards/_template/behaviour/hooks.json +129 -0
- package/src/shards/_template/behaviour/idle.as +75 -0
- package/src/shards/_template/behaviour/items.as +22 -0
- package/src/shards/_template/card/landscape.jpg +0 -0
- package/src/shards/_template/card/portrait.jpg +0 -0
- package/src/shards/_template/card/thumb.jpg +0 -0
- package/src/shards/_template/data/audio.json +45 -0
- package/src/shards/_template/data/bossDecision.json +83 -0
- package/src/shards/_template/data/budgets.json +70 -0
- package/src/shards/_template/data/card.json +281 -0
- package/src/shards/_template/data/clientScripts.json +987 -0
- package/src/shards/_template/data/creatures.json +65 -0
- package/src/shards/_template/data/director.json +39 -0
- package/src/shards/_template/data/encounters.json +96 -0
- package/src/shards/_template/data/items.json +172 -0
- package/src/shards/_template/data/layout.json +66 -0
- package/src/shards/_template/data/ledger.json +32 -0
- package/src/shards/_template/data/look.json +521 -0
- package/src/shards/_template/data/map.json +64 -0
- package/src/shards/_template/data/moves.json +16 -0
- package/src/shards/_template/data/placeholder.json +8 -0
- package/src/shards/_template/data/plumbing.json +32 -0
- package/src/shards/_template/data/quests.json +223 -0
- package/src/shards/_template/data/rows.json +423 -0
- package/src/shards/_template/data/skins.json +66 -0
- package/src/shards/_template/data/spawn.json +6 -0
- package/src/shards/_template/data/targets.json +150 -0
- package/src/shards/_template/data/text.json +12 -0
- package/src/shards/_template/data/ui.json +33 -0
- package/src/shards/_template/data/water.json +13 -0
- package/src/shards/_template/generators/behaviour.ts +34 -0
- package/src/shards/_template/generators/boss.ts +29 -0
- package/src/shards/_template/generators/buildOptions.ts +2 -0
- package/src/shards/_template/generators/cell.ts +224 -0
- package/src/shards/_template/generators/districts.ts +215 -0
- package/src/shards/_template/generators/farLook.ts +15 -0
- package/src/shards/_template/generators/generate.ts +27 -0
- package/src/shards/_template/generators/ground.ts +15 -0
- package/src/shards/_template/generators/kit.ts +69 -0
- package/src/shards/_template/generators/landscape.ts +59 -0
- package/src/shards/_template/generators/landscapeNoise.ts +62 -0
- package/src/shards/_template/generators/mapInputs.ts +10 -0
- package/src/shards/_template/generators/product.ts +100 -0
- package/src/shards/_template/generators/productOutput.ts +18 -0
- package/src/shards/_template/generators/props.ts +9 -0
- package/src/shards/_template/generators/templatePropsSource.ts +58 -0
- package/src/shards/_template/generators/terrain.ts +17 -0
- package/src/shards/_template/generators/world.ts +630 -0
- package/src/shards/_template/hero.json +10 -0
- package/src/shards/_template/look/entry-reads.json +20 -0
- package/src/shards/_template/manifest.json +281 -0
- package/src/shards/_template/shard.config.ts +10 -0
- package/src/shared/health.ts +10 -0
- package/src/tools/build-web.ts +59 -0
- package/src/tsconfig.json +30 -0
- package/src/web/app.tsx +53 -0
- package/src/web/index.html +12 -0
- package/src/web/main.tsx +10 -0
- package/src/web/tsconfig.json +13 -0
- package/tsconfig.author.json +23 -0
- package/tsconfig.commons.json +21 -0
- package/tsconfig.json +47 -0
- package/tsconfig.sharddev.json +20 -0
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import * as schema from 'valibot';
|
|
2
|
+
import { BufferAttribute, Float16BufferAttribute, Matrix4, type Color, type InterleavedBufferAttribute, MeshBasicMaterial, MeshStandardMaterial, Quaternion, Vector3, Group, Mesh, type Material, type Object3D, BufferGeometry, Euler } from 'three';
|
|
3
|
+
import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
|
|
4
|
+
import { parseGlb } from '../assets';
|
|
5
|
+
import { parsePrivateScene, compileTubeCurve, type TubeCurveProfile, type TubeCurveFrame, type PrivateScene } from '@wildshard/format/clientChannels';
|
|
6
|
+
|
|
7
|
+
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
|
|
8
|
+
|
|
9
|
+
/** Geometry GLB and the existing private-scene rows; actual materials remain owned client ports. */
|
|
10
|
+
export interface ClientSceneBake { readonly glb: Uint8Array; readonly scene: PrivateScene }
|
|
11
|
+
|
|
12
|
+
/** A bounded authored strand, optionally placed within its named scene mesh. */
|
|
13
|
+
export interface ClientSceneCurve {
|
|
14
|
+
readonly profile: TubeCurveProfile; readonly frame: TubeCurveFrame; readonly time?: number;
|
|
15
|
+
readonly position?: readonly [number, number, number]; readonly rotation?: readonly [number, number, number];
|
|
16
|
+
}
|
|
17
|
+
/** Named curve meshes share the runtime tube sampler; absent preserves ordinary geometry. */
|
|
18
|
+
export interface ClientSceneOptions { readonly curves?: ReadonlyMap<string, readonly ClientSceneCurve[]> }
|
|
19
|
+
function curveGeometry(rows: readonly ClientSceneCurve[]): BufferGeometry {
|
|
20
|
+
if (rows.length === 0 || rows.length > 32) throw new Error('Authored curves exceed their bounded roster');
|
|
21
|
+
const parts: BufferGeometry[] = []; let vertices = 0;
|
|
22
|
+
try {
|
|
23
|
+
for (const row of rows) {
|
|
24
|
+
const tube = compileTubeCurve(row.profile); vertices += tube.vertices;
|
|
25
|
+
if (vertices > 65536) throw new Error('Authored curve mesh exceeds its vertex budget');
|
|
26
|
+
const positions = new Float32Array(tube.vertices * 3); tube.write(positions, row.frame, row.time ?? 0);
|
|
27
|
+
const { segments, radial, caps } = row.profile, indices: number[] = [];
|
|
28
|
+
for (let s = 0; s < segments; s++) for (let r = 0; r < radial; r++) {
|
|
29
|
+
const a = s * radial + r, b = s * radial + (r + 1) % radial, c = a + radial, d = b + radial;
|
|
30
|
+
indices.push(a, b, c, b, d, c);
|
|
31
|
+
}
|
|
32
|
+
if (caps === true) {
|
|
33
|
+
const bottom = (segments + 1) * radial, top = bottom + radial + 1;
|
|
34
|
+
for (let r = 0; r < radial; r++) {
|
|
35
|
+
const next = (r + 1) % radial;
|
|
36
|
+
indices.push(bottom, bottom + next + 1, bottom + r + 1, top, top + r + 1, top + next + 1);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const geometry = new BufferGeometry(); parts.push(geometry);
|
|
40
|
+
geometry.setAttribute('position', new BufferAttribute(positions, 3));
|
|
41
|
+
geometry.setIndex(new BufferAttribute(new Uint16Array(indices), 1)); geometry.computeVertexNormals();
|
|
42
|
+
const position = row.position ?? [0, 0, 0], rotation = row.rotation ?? [0, 0, 0];
|
|
43
|
+
if ([...position, ...rotation].some(value => !Number.isFinite(value) || Math.abs(value) > 1e5)) throw new Error('Invalid authored curve pose');
|
|
44
|
+
geometry.applyMatrix4(new Matrix4().compose(new Vector3(...position), new Quaternion().setFromEuler(new Euler(...rotation)), new Vector3(1, 1, 1)));
|
|
45
|
+
}
|
|
46
|
+
const result = mergeGeometries(parts);
|
|
47
|
+
result.computeBoundingBox(); result.computeBoundingSphere(); return result;
|
|
48
|
+
} finally { for (const geometry of parts) geometry.dispose(); }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function ordinaryMesh(value: Object3D): value is Mesh { return value instanceof Mesh && value.type === 'Mesh'; }
|
|
52
|
+
|
|
53
|
+
/** Bake named ordinary groups and meshes without fitting geometry or serializing shader/material owners. */
|
|
54
|
+
export function clientSceneGlb(root: Group, ports: ReadonlyMap<Material, string>, options: ClientSceneOptions = {}): ClientSceneBake {
|
|
55
|
+
const nodes: PrivateScene['nodes'] = [], materials: PrivateScene['materials'] = [], primitives: GlbPrimitive[] = [];
|
|
56
|
+
const identities = new Set<string>(), namedMaterials = new Map<string, Material>();
|
|
57
|
+
const geometryMaterial = new MeshStandardMaterial(), ownedCurves: BufferGeometry[] = [], usedCurves = new Set<string>();
|
|
58
|
+
if ((options.curves?.size ?? 0) > 128) throw new Error('Too many authored curve targets');
|
|
59
|
+
const visit = (object: Object3D): void => {
|
|
60
|
+
if (identities.size >= 128) throw new Error('Rest scene exceeds its bounded part roster');
|
|
61
|
+
if (!/^[a-z][a-zA-Z0-9-]{0,95}$/u.test(object.name) || identities.has(object.name)) throw new Error('Rest scene requires unique loader-safe part names');
|
|
62
|
+
if (object.layers.mask !== 1 || !object.matrixAutoUpdate || object.animations.length > 0) throw new Error('Rest scene requires ordinary transform owners');
|
|
63
|
+
identities.add(object.name);
|
|
64
|
+
const pose = { position: [object.position.x, object.position.y, object.position.z] as [number, number, number],
|
|
65
|
+
rotation: [object.rotation.x, object.rotation.y, object.rotation.z] as [number, number, number], order: object.rotation.order,
|
|
66
|
+
scale: [object.scale.x, object.scale.y, object.scale.z] as [number, number, number], children: object.children.map(child => child.name),
|
|
67
|
+
visible: object.visible, castShadow: object.castShadow, receiveShadow: object.receiveShadow, frustumCulled: object.frustumCulled, renderOrder: object.renderOrder };
|
|
68
|
+
if (ordinaryMesh(object)) {
|
|
69
|
+
if (Array.isArray(object.material) || Object.keys(object.geometry.morphAttributes).length > 0
|
|
70
|
+
|| object.geometry.drawRange.start !== 0 || object.geometry.drawRange.count !== Infinity) throw new Error('Rest scene requires one owned material and complete rigid geometry');
|
|
71
|
+
const material = ports.get(object.material);
|
|
72
|
+
if (material === undefined) throw new Error('Rest scene material has no declared client port');
|
|
73
|
+
const prior = namedMaterials.get(material);
|
|
74
|
+
if (prior !== undefined && prior !== object.material) throw new Error('Rest scene material port aliases distinct owners');
|
|
75
|
+
if (prior === undefined) {
|
|
76
|
+
if (namedMaterials.size >= 32) throw new Error('Rest scene exceeds its bounded material roster');
|
|
77
|
+
namedMaterials.set(material, object.material); materials.push({ kind: 'port', id: material, source: material });
|
|
78
|
+
}
|
|
79
|
+
const curves = options.curves?.get(object.name), geometry = curves === undefined ? object.geometry : curveGeometry(curves);
|
|
80
|
+
if (curves !== undefined) { ownedCurves.push(geometry); usedCurves.add(object.name); }
|
|
81
|
+
const sphere = geometry.boundingSphere, box = geometry.boundingBox;
|
|
82
|
+
for (const [channel, attribute] of Object.entries(geometry.attributes)) {
|
|
83
|
+
const width = ['uv','uv1'].includes(channel) ? 2 : channel === 'tangent' ? 4 : ['position', 'normal', 'color'].includes(channel) ? 3 : undefined;
|
|
84
|
+
if (width === undefined || !(attribute instanceof BufferAttribute) || !(attribute.array instanceof Float32Array)
|
|
85
|
+
|| attribute.normalized || attribute.itemSize !== width) throw new Error('Rest scene requires exact supported Float32 geometry channels');
|
|
86
|
+
}
|
|
87
|
+
const index = geometry.index;
|
|
88
|
+
if (index !== null && (!(index.array instanceof Uint16Array) && !(index.array instanceof Uint32Array)
|
|
89
|
+
|| index.normalized || index.itemSize !== 1)) throw new Error('Rest scene requires exact uint16/uint32 indices');
|
|
90
|
+
const extras = { restBox: box === null ? null : [box.min.x, box.min.y, box.min.z, box.max.x, box.max.y, box.max.z], restGroups: geometry.groups.map(group => [group.start, group.count, group.materialIndex ?? 0]),
|
|
91
|
+
restSphere: sphere === null ? null : [sphere.center.x, sphere.center.y, sphere.center.z, sphere.radius] };
|
|
92
|
+
primitives.push({ name: object.name, geometry, material: geometryMaterial, nativeAttributes: true, compactIndex: true, extras });
|
|
93
|
+
nodes.push({ kind: 'mesh', id: object.name, geometry: object.name, material, missing: 'empty', ...pose });
|
|
94
|
+
} else if (object instanceof Group && object.type === 'Group') nodes.push({ kind: 'group', id: object.name, ...pose });
|
|
95
|
+
else throw new Error('Rest scene supports ordinary Group and Mesh declarations only');
|
|
96
|
+
for (const child of object.children) visit(child);
|
|
97
|
+
};
|
|
98
|
+
try {
|
|
99
|
+
visit(root);
|
|
100
|
+
if (usedCurves.size !== (options.curves?.size ?? 0)) throw new Error('Authored curve target is not a declared mesh');
|
|
101
|
+
const scene = parsePrivateScene({ version: 1, root: root.name, nodes, materials });
|
|
102
|
+
return { scene, glb: staticGlb(primitives, root.name) };
|
|
103
|
+
} finally { geometryMaterial.dispose(); for (const geometry of ownedCurves) geometry.dispose(); }
|
|
104
|
+
}
|
|
105
|
+
/** A primitive's geometry, material and optional instanced local transforms; textures are separate declared assets. */
|
|
106
|
+
export interface GlbPrimitive {
|
|
107
|
+
geometry: BufferGeometry; material: MeshStandardMaterial | MeshBasicMaterial; instances?: readonly Matrix4[]; castShadow?: boolean;
|
|
108
|
+
/** Optional unique glTF node/mesh name (letters, digits, underscore or hyphen); absent preserves the old byte path. */
|
|
109
|
+
name?: string;
|
|
110
|
+
/** Write exact float32 column-major MAT4 instances instead of decomposing TRS. */
|
|
111
|
+
exactInstances?: true;
|
|
112
|
+
/** Optional linear RGB instance colours, 0 … 1; count must match instances. */
|
|
113
|
+
instanceColours?: readonly Color[];
|
|
114
|
+
/** Explicit glTF application semantic → geometry channel, e.g. `_SPLAT: 'splat'`; absent preserves old bytes. */
|
|
115
|
+
customAttributes?: Readonly<Record<string, string>>;
|
|
116
|
+
/** Optional node transform (a finite positive TRS; not with `instances`); absent preserves the old byte path. */
|
|
117
|
+
transform?: Matrix4;
|
|
118
|
+
/** I3: with `nativeAttributes`, each non-float32 channel is written once (an integer custom channel in its own type,
|
|
119
|
+
* a half-float one only as its raw bits) instead of also as float32; absent: the old (pinned) byte path. */
|
|
120
|
+
nativeOnce?: true;
|
|
121
|
+
/** I3: the exact source transform a native node records (`matrix64`) when its node `transform` also carries the grid
|
|
122
|
+
* that dequantizes its positions; absent: `transform` itself. */
|
|
123
|
+
pose?: Matrix4;
|
|
124
|
+
/** Keep original typed vertex channels as glTF application accessors with reconstruction metadata in node extras.
|
|
125
|
+
* Half floats use uint16 bits (glTF has no float16); ordinary semantics remain portable float32. Also retains
|
|
126
|
+
* double-precision source transforms in extras. Omitted: the existing byte path. */
|
|
127
|
+
nativeAttributes?: true;
|
|
128
|
+
/** Plain application rows, charged inside the GLB; reserved storage/transform extras remain baker-owned. */
|
|
129
|
+
extras?: Readonly<Record<string, Json>>;
|
|
130
|
+
/** `true` writes the index as built: none for a non-indexed geometry, 16-bit when it is 16-bit; absent always writes a 32-bit index (the old byte path). */
|
|
131
|
+
compactIndex?: true;
|
|
132
|
+
/** `true` writes a normalized Int8 normal and a normalized Uint8 / Uint16 colour as they are (KHR_mesh_quantization,
|
|
133
|
+
* tightly packed), which three's GLTFLoader reads back into the same typed attributes;
|
|
134
|
+
* positions stay float32. Other storage refuses. Absent: the old float32 byte path. */
|
|
135
|
+
quantizedChannels?: true;
|
|
136
|
+
/** With `quantizedChannels`: every quantized channel gets a 4-byte stride (meshopt's attribute codec needs one;
|
|
137
|
+
* GLTFLoader reads it back interleaved), and an unnormalized Int16 position is written on its node's grid, the
|
|
138
|
+
* node's `transform` (a scale and translation) dequantizing it (RM8.1, tiles). */
|
|
139
|
+
meshoptReady?: true;
|
|
140
|
+
}
|
|
141
|
+
/** A deterministic self-contained static GLB; names and vertex colours survive the ordinary engine GLTFLoader. */
|
|
142
|
+
export function staticGlb(primitives: readonly GlbPrimitive[], name = 'baked'): Uint8Array {
|
|
143
|
+
const names = primitives.map(primitive => primitive.name ?? name);
|
|
144
|
+
for (const primitive of primitives) {
|
|
145
|
+
if (primitive.name !== undefined && (!/^[A-Za-z_][A-Za-z0-9_-]{0,127}$/u.test(primitive.name)
|
|
146
|
+
|| names.filter(actual => actual === primitive.name).length !== 1)) throw new Error('GLB node names must be unique loader-safe identifiers');
|
|
147
|
+
}
|
|
148
|
+
const chunks: Uint8Array[] = [], views: Json[] = [], accessors: Json[] = [], meshes: Json[] = [], nodes: Json[] = [], materials: Json[] = [];
|
|
149
|
+
let offset = 0;
|
|
150
|
+
const accessor = (values: readonly number[] | BufferAttribute | InterleavedBufferAttribute, width: number, type: string, integer = false, bounds = false, short = false): number => {
|
|
151
|
+
// Read through Three's channel API, including normalized, half and interleaved
|
|
152
|
+
// attributes, without first allocating a boxed copy of every component.
|
|
153
|
+
const length = 'length' in values ? values.length : values.count * width;
|
|
154
|
+
// Three's Float16BufferAttribute inherits getComponent, which returns
|
|
155
|
+
// Uint16 storage bits. Its axis getters decode the numeric channel value.
|
|
156
|
+
const read = 'length' in values ? (i: number) => values[i]
|
|
157
|
+
: values instanceof Float16BufferAttribute ? (i: number) => {
|
|
158
|
+
const row = Math.floor(i / width), component = i % width;
|
|
159
|
+
return component === 0 ? values.getX(row) : component === 1 ? values.getY(row)
|
|
160
|
+
: component === 2 ? values.getZ(row) : values.getW(row);
|
|
161
|
+
} : (i: number) => values.getComponent(Math.floor(i / width), i % width);
|
|
162
|
+
if (length === 0 || length % width !== 0) throw new Error('Invalid GLB attribute');
|
|
163
|
+
// Validate, encode and collect component bounds in one ordered pass. Bounds
|
|
164
|
+
// retain the unrounded source values, while the wire keeps its old storage.
|
|
165
|
+
const minima: number[] = bounds ? Array.from({ length: width }, () => Infinity) : [];
|
|
166
|
+
const maxima: number[] = bounds ? Array.from({ length: width }, () => -Infinity) : [];
|
|
167
|
+
// a 16-bit index's view is padded to 4 bytes so every later view stays aligned
|
|
168
|
+
const size = short ? 2 : 4, bytes = new Uint8Array(Math.ceil(length * size / 4) * 4), v = new DataView(bytes.buffer);
|
|
169
|
+
for (let i = 0; i < length; i++) {
|
|
170
|
+
const n = read(i);
|
|
171
|
+
if (n === undefined || !Number.isFinite(n)) throw new Error('Invalid GLB attribute');
|
|
172
|
+
if (short) v.setUint16(i * 2, n, true);
|
|
173
|
+
else if (integer) v.setUint32(i * 4, n, true);
|
|
174
|
+
else v.setFloat32(i * 4, n, true);
|
|
175
|
+
if (bounds) {
|
|
176
|
+
const component = i % width;
|
|
177
|
+
minima[component] = Math.min(minima[component] ?? Infinity, n);
|
|
178
|
+
maxima[component] = Math.max(maxima[component] ?? -Infinity, n);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const view = views.length; views.push({ buffer: 0, byteOffset: offset, byteLength: length * size }); chunks.push(bytes); offset += bytes.length;
|
|
182
|
+
const a: Record<string, Json> = { bufferView: view, componentType: short ? 5123 : integer ? 5125 : 5126, count: length / width, type };
|
|
183
|
+
if (bounds) { a['min'] = minima; a['max'] = maxima; }
|
|
184
|
+
accessors.push(a); return accessors.length - 1;
|
|
185
|
+
};
|
|
186
|
+
const rawAccessor = (attribute: BufferAttribute): number => {
|
|
187
|
+
const array = attribute.array;
|
|
188
|
+
const componentType = array instanceof Float32Array ? 5126 : array instanceof Uint32Array ? 5125
|
|
189
|
+
: array instanceof Uint16Array ? 5123 : array instanceof Int16Array ? 5122
|
|
190
|
+
: array instanceof Uint8Array ? 5121 : array instanceof Int8Array ? 5120 : null;
|
|
191
|
+
if (componentType === null) throw new Error('Native GLB attributes require a glTF component type');
|
|
192
|
+
const length = attribute.count * attribute.itemSize * array.BYTES_PER_ELEMENT;
|
|
193
|
+
const bytes = new Uint8Array(Math.ceil(length / 4) * 4);
|
|
194
|
+
bytes.set(new Uint8Array(array.buffer, array.byteOffset, length));
|
|
195
|
+
const view = views.length; views.push({ buffer: 0, byteOffset: offset, byteLength: length }); chunks.push(bytes); offset += bytes.length;
|
|
196
|
+
accessors.push({ bufferView: view, componentType, count: attribute.count,
|
|
197
|
+
type: attribute.itemSize === 1 ? 'SCALAR' : `VEC${attribute.itemSize}`,
|
|
198
|
+
...(attribute.normalized ? { normalized: true } : {}) });
|
|
199
|
+
return accessors.length - 1;
|
|
200
|
+
};
|
|
201
|
+
// KHR_mesh_quantization: a normalized integer vertex channel, tightly packed (each view starts 4-byte aligned): WebGL
|
|
202
|
+
// needs only component alignment, and three's GLTFLoader reads a packed view back as a plain typed attribute (a padded
|
|
203
|
+
// stride would come back interleaved)
|
|
204
|
+
let quantized = false;
|
|
205
|
+
const packedAccessor = (attribute: BufferAttribute, aligned = false, position = false): number => {
|
|
206
|
+
const array = attribute.array;
|
|
207
|
+
const componentType = position ? (array instanceof Int16Array && !attribute.normalized ? 5122 : null)
|
|
208
|
+
: !attribute.normalized ? null : array instanceof Int8Array ? 5120 : array instanceof Uint8Array ? 5121 : array instanceof Uint16Array ? 5123 : null;
|
|
209
|
+
if (componentType === null) throw new Error('Quantized GLB channels must be normalized Int8, Uint8 or Uint16 (positions unnormalized Int16)');
|
|
210
|
+
const element = attribute.itemSize * array.BYTES_PER_ELEMENT, stride = aligned ? Math.ceil(element / 4) * 4 : element;
|
|
211
|
+
const length = attribute.count * stride, bytes = new Uint8Array(Math.ceil(length / 4) * 4), source = new Uint8Array(array.buffer, array.byteOffset, attribute.count * element);
|
|
212
|
+
if (stride === element) bytes.set(source);
|
|
213
|
+
// Copy raw components without allocating a typed view for every padded
|
|
214
|
+
// vertex. The fresh target retains the same zero stride/tail padding.
|
|
215
|
+
else for (let i = 0, from = 0, to = 0; i < attribute.count; i++, from += element, to += stride) {
|
|
216
|
+
for (let component = 0; component < element; component++) bytes[to + component] = source[from + component] ?? 0;
|
|
217
|
+
}
|
|
218
|
+
const view = views.length; views.push({ buffer: 0, byteOffset: offset, byteLength: length, ...(stride === element ? {} : { byteStride: stride }) }); chunks.push(bytes); offset += bytes.length;
|
|
219
|
+
const a: Record<string, Json> = { bufferView: view, componentType, ...(position ? {} : { normalized: true }), count: attribute.count, type: `VEC${attribute.itemSize}` };
|
|
220
|
+
if (position) {
|
|
221
|
+
const minima = [Infinity, Infinity, Infinity], maxima = [-Infinity, -Infinity, -Infinity];
|
|
222
|
+
for (let i = 0; i < attribute.count; i++) for (let c = 0; c < 3; c++) {
|
|
223
|
+
const n = attribute.getComponent(i, c); minima[c] = Math.min(minima[c] ?? Infinity, n); maxima[c] = Math.max(maxima[c] ?? -Infinity, n);
|
|
224
|
+
}
|
|
225
|
+
a['min'] = minima; a['max'] = maxima;
|
|
226
|
+
}
|
|
227
|
+
accessors.push(a);
|
|
228
|
+
quantized = true;
|
|
229
|
+
return accessors.length - 1;
|
|
230
|
+
};
|
|
231
|
+
const trs = (matrix: Matrix4): { position: Vector3; rotation: Quaternion; scale: Vector3 } => {
|
|
232
|
+
const position = new Vector3(), scale = new Vector3(), rotation = new Quaternion();
|
|
233
|
+
matrix.decompose(position, rotation, scale);
|
|
234
|
+
const composed = new Matrix4().compose(position, rotation, scale);
|
|
235
|
+
if (matrix.elements.some((n, i) => !Number.isFinite(n) || Math.abs(n - (composed.elements[i] ?? Infinity)) > 1e-5) || scale.x <= 0 || scale.y <= 0 || scale.z <= 0) throw new Error('Instance must be a finite positive TRS transform');
|
|
236
|
+
return { position, rotation, scale };
|
|
237
|
+
};
|
|
238
|
+
for (const { geometry, material, instances, exactInstances, instanceColours, castShadow = true, customAttributes = {}, name: nodeName = name, transform, compactIndex, nativeAttributes, nativeOnce, extras, pose, quantizedChannels, meshoptReady } of primitives) {
|
|
239
|
+
if (material.map !== null || material.alphaMap !== null || (!(material instanceof MeshBasicMaterial) && (material.normalMap !== null || material.roughnessMap !== null || material.metalnessMap !== null))) throw new Error('GLB textures must be external KTX2 declarations');
|
|
240
|
+
if (!geometry.hasAttribute('position')) throw new Error('Missing GLB positions');
|
|
241
|
+
const p = geometry.getAttribute('position'); if ( p.count > 400_000) throw new Error('Unsupported GLB geometry');
|
|
242
|
+
const attributes: Record<string, Json> = {};
|
|
243
|
+
for (const [key, semantic, width] of [['position', 'POSITION', 3], ['normal', 'NORMAL', 3], ['uv', 'TEXCOORD_0', 2], ['uv1', 'TEXCOORD_1', 2], ['color', 'COLOR_0', geometry.hasAttribute('color') ? geometry.getAttribute('color').itemSize : 3], ['tangent', 'TANGENT', 4]] as const) {
|
|
244
|
+
const a = geometry.getAttribute(key); if (!geometry.hasAttribute(key)) continue;
|
|
245
|
+
// A trusted whole shape may use the fourth normal component as a shader channel. glTF NORMAL is vec3:
|
|
246
|
+
// retain the original vec4 as an application accessor below, never misdeclare the portable semantic.
|
|
247
|
+
if (nativeAttributes === true && key === 'normal' && a.itemSize === 4 && a.count === p.count) continue;
|
|
248
|
+
if (a.itemSize !== width || a.count !== p.count || (key === 'color' && width !== 3 && width !== 4)) throw new Error('Mismatched GLB attributes');
|
|
249
|
+
// (a colour outside [0, 1] stays float32 beside quantized normals: compactWholeNormals)
|
|
250
|
+
if (quantizedChannels === true && (key === 'normal' || (key === 'color' && !(a.array instanceof Float32Array)))) {
|
|
251
|
+
if (!(a instanceof BufferAttribute) || (key === 'normal' && !(a.array instanceof Int8Array))) throw new Error('Quantized GLB normals must be normalized Int8');
|
|
252
|
+
attributes[semantic] = packedAccessor(a, meshoptReady === true); continue;
|
|
253
|
+
}
|
|
254
|
+
if (quantizedChannels === true && meshoptReady === true && key === 'position' && a instanceof BufferAttribute && a.array instanceof Int16Array) {
|
|
255
|
+
if (transform === undefined) throw new Error('A quantized GLB position needs its node transform');
|
|
256
|
+
attributes[semantic] = packedAccessor(a, true, true); continue;
|
|
257
|
+
}
|
|
258
|
+
attributes[semantic] = accessor(a, width, `VEC${width}`, false, key === 'position');
|
|
259
|
+
}
|
|
260
|
+
const custom = Object.entries(customAttributes).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
261
|
+
if (custom.length > 16) throw new Error('GLB custom attribute cap');
|
|
262
|
+
for (const [semantic, channel] of custom) {
|
|
263
|
+
if (!/^_[A-Z][A-Z0-9_]{0,63}$/.test(semantic) || !geometry.hasAttribute(channel)) throw new Error(`Invalid GLB custom attribute ${semantic}`);
|
|
264
|
+
const a = geometry.getAttribute(channel), width = a.itemSize;
|
|
265
|
+
if (!Number.isInteger(width) || width < 1 || width > 4 || a.count !== p.count) throw new Error(`Mismatched GLB custom attribute ${semantic}`);
|
|
266
|
+
// iPhone downloads I3 (with `nativeOnce`, so pinned byte paths stay): a native channel that is not float32 is read back only from its exact stored copy below (an
|
|
267
|
+
// integer channel is that copy, under its own semantic; a half-float one is its raw bits), so it is not also
|
|
268
|
+
// written as float32 (a half channel's float32 copy held its raw bits, never read; Nine's tiles carried ~50 MB of them)
|
|
269
|
+
if (nativeAttributes === true && nativeOnce === true && a instanceof BufferAttribute && !(a.array instanceof Float32Array)) continue;
|
|
270
|
+
attributes[semantic] = accessor(a, width, width === 1 ? 'SCALAR' : `VEC${width}`);
|
|
271
|
+
}
|
|
272
|
+
const native: Record<string, Json> = {};
|
|
273
|
+
if (nativeAttributes === true) {
|
|
274
|
+
const channels = new Map<string, string>([['position', 'POSITION'], ['normal', 'NORMAL'], ['uv', 'TEXCOORD_0'], ['uv1', 'TEXCOORD_1'], ['color', 'COLOR_0'], ['tangent', 'TANGENT'], ...custom.map(([semantic, channel]) => [channel, semantic] as [string, string])]);
|
|
275
|
+
for (const [channel, semantic] of channels) {
|
|
276
|
+
if (!geometry.hasAttribute(channel)) continue;
|
|
277
|
+
const a = geometry.getAttribute(channel);
|
|
278
|
+
if (!(a instanceof BufferAttribute)) throw new Error('Native GLB attributes must not be interleaved');
|
|
279
|
+
let stored = semantic;
|
|
280
|
+
// a quantized normal / colour is already its own typed portable accessor: the table names it, with no raw copy;
|
|
281
|
+
// so is an integer custom channel (glTF admits any component type for an application semantic), written once here
|
|
282
|
+
const portable = quantizedChannels === true && (channel === 'normal' || channel === 'color'
|
|
283
|
+
|| (channel === 'position' && meshoptReady === true && a.array instanceof Int16Array && !a.normalized));
|
|
284
|
+
const integerCustom = nativeOnce === true && semantic.startsWith('_') && !(a instanceof Float16BufferAttribute) && !(a.array instanceof Float32Array);
|
|
285
|
+
if (integerCustom) { attributes[semantic] = rawAccessor(a); native[channel] = { semantic, storage: a.array.constructor.name, normalized: a.normalized, itemSize: a.itemSize }; continue; }
|
|
286
|
+
if (!portable && (!(a.array instanceof Float32Array) || (semantic === 'NORMAL' && a.itemSize !== 3))) {
|
|
287
|
+
stored = `_WS_RAW_${semantic.replace(/^_/u, '')}`;
|
|
288
|
+
if (Object.hasOwn(attributes, stored)) throw new Error(`Native GLB semantic collision ${stored}`);
|
|
289
|
+
attributes[stored] = rawAccessor(a);
|
|
290
|
+
}
|
|
291
|
+
native[channel] = { semantic: stored, storage: a instanceof Float16BufferAttribute ? 'Float16Array' : a.array.constructor.name,
|
|
292
|
+
normalized: a.normalized, itemSize: a.itemSize };
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const index = geometry.getIndex(), indices = index === null ? Array.from({ length: p.count }, (_, i) => i) : Array.from(index.array);
|
|
296
|
+
if (indices.length % 3 !== 0 || indices.some((i) => !Number.isInteger(i) || i < 0 || i >= p.count)) throw new Error('Invalid triangle indices');
|
|
297
|
+
const materialIndex = materials.length;
|
|
298
|
+
materials.push({ name: material.name, pbrMetallicRoughness: { baseColorFactor: [...material.color, material.opacity], metallicFactor: material instanceof MeshBasicMaterial ? 0 : material.metalness, roughnessFactor: material instanceof MeshBasicMaterial ? 1 : material.roughness }, doubleSided: material.side === 2,
|
|
299
|
+
alphaMode: material.transparent ? 'BLEND' : material.alphaTest > 0 ? 'MASK' : 'OPAQUE',
|
|
300
|
+
...(material.alphaTest > 0 ? { alphaCutoff: material.alphaTest } : {}),
|
|
301
|
+
...(material instanceof MeshBasicMaterial ? { extensions: { KHR_materials_unlit: {} } } : material.emissive.r !== 0 || material.emissive.g !== 0 || material.emissive.b !== 0 ? { emissiveFactor: [...material.emissive].map(value => value * material.emissiveIntensity) } : {}),
|
|
302
|
+
});
|
|
303
|
+
const compact = compactIndex === true, short = compact && index !== null && index.array instanceof Uint16Array;
|
|
304
|
+
meshes.push({ name: nodeName, primitives: [{ attributes, ...(compact && index === null ? {} : { indices: accessor(indices, 1, 'SCALAR', true, false, short) }), material: materialIndex }] });
|
|
305
|
+
if (extras !== undefined && ['castShadow', 'nativeAttributes', 'matrix64', 'instances64'].some(key => Object.hasOwn(extras, key))) throw new Error('GLB application extras use a reserved key');
|
|
306
|
+
const node: Record<string, Json> = { name: nodeName, mesh: meshes.length - 1, extras: { ...extras, castShadow, ...(nativeAttributes === true ? { nativeAttributes: native,
|
|
307
|
+
...(transform === undefined ? {} : { matrix64: (pose ?? transform).elements }),
|
|
308
|
+
...(instances === undefined ? {} : { instances64: instances.map(matrix => matrix.elements) }) } : {}) } };
|
|
309
|
+
if (instances === undefined && (exactInstances !== undefined || instanceColours !== undefined)) throw new Error('Instance options need instances');
|
|
310
|
+
if (instances !== undefined) {
|
|
311
|
+
if (instances.length === 0 || instances.length > 10_000) throw new Error('Invalid instance count');
|
|
312
|
+
let instanceAttributes: Record<string, Json>;
|
|
313
|
+
if (exactInstances === true) instanceAttributes = { _MATRIX: accessor(instances.flatMap(matrix => matrix.elements), 16, 'MAT4') };
|
|
314
|
+
else {
|
|
315
|
+
const t: number[] = [], r: number[] = [], s: number[] = [];
|
|
316
|
+
for (const matrix of instances) { const { position, rotation, scale } = trs(matrix); t.push(...position); r.push(...rotation); s.push(...scale); }
|
|
317
|
+
instanceAttributes = { TRANSLATION: accessor(t, 3, 'VEC3'), ROTATION: accessor(r, 4, 'VEC4'), SCALE: accessor(s, 3, 'VEC3') };
|
|
318
|
+
}
|
|
319
|
+
if (instanceColours !== undefined) {
|
|
320
|
+
if (instanceColours.length !== instances.length) throw new Error('Instance colours must match instance count');
|
|
321
|
+
instanceAttributes['_COLOR_0'] = accessor(instanceColours.flatMap(colour => [colour.r, colour.g, colour.b]), 3, 'VEC3');
|
|
322
|
+
}
|
|
323
|
+
node['extensions'] = { EXT_mesh_gpu_instancing: { attributes: instanceAttributes } };
|
|
324
|
+
}
|
|
325
|
+
if (transform !== undefined) {
|
|
326
|
+
if (instances !== undefined) throw new Error('A GLB node takes a transform or instances, not both');
|
|
327
|
+
const { position, rotation, scale } = trs(transform);
|
|
328
|
+
// only what differs from the identity, so a translated node keeps its exact translation
|
|
329
|
+
if (position.x !== 0 || position.y !== 0 || position.z !== 0) node['translation'] = [position.x, position.y, position.z];
|
|
330
|
+
if (rotation.x !== 0 || rotation.y !== 0 || rotation.z !== 0 || rotation.w !== 1) node['rotation'] = [rotation.x, rotation.y, rotation.z, rotation.w];
|
|
331
|
+
if (scale.x !== 1 || scale.y !== 1 || scale.z !== 1) node['scale'] = [scale.x, scale.y, scale.z];
|
|
332
|
+
}
|
|
333
|
+
nodes.push(node);
|
|
334
|
+
}
|
|
335
|
+
const doc: Record<string, Json> = { asset: { version: '2.0', generator: 'wildshard-static-v1' }, scene: 0, scenes: [{ nodes: nodes.map((_, i) => i) }], nodes, meshes, materials, accessors, bufferViews: views, buffers: [{ byteLength: offset }] };
|
|
336
|
+
const extensions = [...(primitives.some(p => p.instances !== undefined) ? ['EXT_mesh_gpu_instancing'] : []), ...(primitives.some(p => p.material instanceof MeshBasicMaterial) ? ['KHR_materials_unlit'] : []), ...(quantized ? ['KHR_mesh_quantization'] : [])];
|
|
337
|
+
if (extensions.length > 0) { doc['extensionsUsed'] = extensions; doc['extensionsRequired'] = extensions; }
|
|
338
|
+
const raw = new TextEncoder().encode(JSON.stringify(doc)), length = Math.ceil(raw.length / 4) * 4, bytes = new Uint8Array(28 + length + offset), v = new DataView(bytes.buffer);
|
|
339
|
+
v.setUint32(0, 0x46546c67, true); v.setUint32(4, 2, true); v.setUint32(8, bytes.length, true); v.setUint32(12, length, true); v.setUint32(16, 0x4e4f534a, true); bytes.fill(32, 20, 20 + length); bytes.set(raw, 20);
|
|
340
|
+
v.setUint32(20 + length, offset, true); v.setUint32(24 + length, 0x004e4942, true);
|
|
341
|
+
let at = 28 + length; for (const chunk of chunks) { bytes.set(chunk, at); at += chunk.length; }
|
|
342
|
+
parseGlb(bytes); return bytes;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** Read ordered whole-partition identities from a bounded standard GLB JSON
|
|
346
|
+
* chunk. Unrelated glTF metadata strips; malformed optional structures refuse. */
|
|
347
|
+
export function glbWholePartitionIds(bytes: Uint8Array): string[] {
|
|
348
|
+
if (bytes.byteLength < 20) throw new Error('GLB partition is truncated');
|
|
349
|
+
const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength), length = header.getUint32(12, true);
|
|
350
|
+
if (header.getUint32(0, true) !== 0x46546c67 || header.getUint32(4, true) !== 2 || header.getUint32(8, true) !== bytes.byteLength
|
|
351
|
+
|| header.getUint32(16, true) !== 0x4e4f534a || length > bytes.byteLength - 20) throw new Error('GLB partition header differs');
|
|
352
|
+
const json: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(20, 20 + length)));
|
|
353
|
+
const value = schema.parse(schema.object({ nodes: schema.optional(schema.array(schema.object({ extras: schema.optional(schema.object({ wholePartition: schema.optional(schema.object({ id: schema.string() })) })) })), []) }), json);
|
|
354
|
+
return value.nodes.flatMap(node => node.extras?.wholePartition === undefined ? [] : [node.extras.wholePartition.id]);
|
|
355
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { VertexLayout, WebIO, type Accessor } from '@gltf-transform/core';
|
|
2
|
+
import { EXTMeshoptCompression, KHRMeshQuantization } from '@gltf-transform/extensions';
|
|
3
|
+
import { dedup } from '@gltf-transform/functions';
|
|
4
|
+
import { MeshoptDecoder } from 'meshoptimizer';
|
|
5
|
+
import { MeshoptEncoder } from 'meshoptimizer/encoder';
|
|
6
|
+
import { parseGlb, prepareAssetDecoders } from '@wildshard/format/product';
|
|
7
|
+
|
|
8
|
+
await MeshoptEncoder.ready;
|
|
9
|
+
await prepareAssetDecoders();
|
|
10
|
+
const EXT = 'EXT_meshopt_compression';
|
|
11
|
+
const object = (value: unknown): Record<string, unknown> => {
|
|
12
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('GLB compression object required');
|
|
13
|
+
return value as Record<string, unknown>;
|
|
14
|
+
};
|
|
15
|
+
const rows = (value: unknown): Record<string, unknown>[] => {
|
|
16
|
+
if (!Array.isArray(value)) throw new Error('GLB compression array required');
|
|
17
|
+
return value.map(object);
|
|
18
|
+
};
|
|
19
|
+
const integer = (value: unknown): number => {
|
|
20
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) throw new Error('GLB compression count required');
|
|
21
|
+
return value;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Lossless buffer-view encoding, without quantization, welding, index reordering or scene/material edits.
|
|
25
|
+
* The ordinary meshopt-capable runtime decodes the exact original channels, including application accessors. */
|
|
26
|
+
export function compressGlb(input: Uint8Array): Uint8Array {
|
|
27
|
+
parseGlb(input);
|
|
28
|
+
const header = new DataView(input.buffer, input.byteOffset, input.byteLength), jsonLength = header.getUint32(12, true);
|
|
29
|
+
const doc = object(JSON.parse(new TextDecoder().decode(input.subarray(20, 20 + jsonLength))));
|
|
30
|
+
if (Array.isArray(doc['extensionsUsed']) && doc['extensionsUsed'].includes(EXT)) return Uint8Array.from(input);
|
|
31
|
+
const source = input.subarray(28 + jsonLength), views = rows(doc['bufferViews'] ?? []), accessors = rows(doc['accessors'] ?? []);
|
|
32
|
+
const chunks: Uint8Array[] = [];
|
|
33
|
+
let physical = 0, fallback = 0;
|
|
34
|
+
const append = (bytes: Uint8Array): number => {
|
|
35
|
+
const offset = physical, padded = new Uint8Array(Math.ceil(bytes.length / 4) * 4);
|
|
36
|
+
padded.set(bytes); chunks.push(padded); physical += padded.length; return offset;
|
|
37
|
+
};
|
|
38
|
+
const packedViews = views.map((view, index) => {
|
|
39
|
+
const output = view;
|
|
40
|
+
const length = integer(view['byteLength']), offset = integer(view['byteOffset'] ?? 0), bytes = source.subarray(offset, offset + length);
|
|
41
|
+
const accessor = accessors.find(row => row['bufferView'] === index && (row['byteOffset'] ?? 0) === 0);
|
|
42
|
+
const count = accessor === undefined ? 0 : integer(accessor['count']);
|
|
43
|
+
const indices = accessor?.['type'] === 'SCALAR' && (accessor['componentType'] === 5123 || accessor['componentType'] === 5125);
|
|
44
|
+
const inferred = count === 0 ? 0 : length / count;
|
|
45
|
+
const size = view['byteStride'] === undefined ? inferred : integer(view['byteStride']);
|
|
46
|
+
const mode = indices ? 'INDICES' : 'ATTRIBUTES';
|
|
47
|
+
if (size === 0 || !Number.isInteger(size) || length % size !== 0 || size > 256
|
|
48
|
+
|| (indices ? size !== 2 && size !== 4 : size % 4 !== 0)) { output['byteOffset'] = append(bytes); return output; }
|
|
49
|
+
const packed = MeshoptEncoder.encodeGltfBuffer(bytes, length / size, size, mode), target = fallback;
|
|
50
|
+
fallback += Math.ceil(length / 4) * 4;
|
|
51
|
+
output['buffer'] = 1; output['byteOffset'] = target;
|
|
52
|
+
output['extensions'] = { ...(view['extensions'] === undefined ? {} : object(view['extensions'])),
|
|
53
|
+
[EXT]: { buffer: 0, byteOffset: append(packed), byteLength: packed.length, byteStride: size, count: length / size, mode } };
|
|
54
|
+
return output;
|
|
55
|
+
});
|
|
56
|
+
if (fallback === 0) return Uint8Array.from(input);
|
|
57
|
+
doc['bufferViews'] = packedViews;
|
|
58
|
+
doc['buffers'] = [{ byteLength: physical }, { byteLength: fallback, extensions: { [EXT]: { fallback: true } } }];
|
|
59
|
+
for (const key of ['extensionsUsed', 'extensionsRequired']) {
|
|
60
|
+
const existing = doc[key];
|
|
61
|
+
const entries: unknown[] = existing === undefined ? [] : Array.isArray(existing) ? existing : (() => { throw new Error('GLB extension list required'); })();
|
|
62
|
+
doc[key] = [...entries, EXT];
|
|
63
|
+
}
|
|
64
|
+
const json = new TextEncoder().encode(JSON.stringify(doc)), paddedJson = Math.ceil(json.length / 4) * 4;
|
|
65
|
+
const output = new Uint8Array(28 + paddedJson + physical), result = new DataView(output.buffer);
|
|
66
|
+
result.setUint32(0, 0x46546c67, true); result.setUint32(4, 2, true); result.setUint32(8, output.length, true);
|
|
67
|
+
result.setUint32(12, paddedJson, true); result.setUint32(16, 0x4e4f534a, true);
|
|
68
|
+
output.fill(32, 20, 20 + paddedJson); output.set(json, 20);
|
|
69
|
+
result.setUint32(20 + paddedJson, physical, true); result.setUint32(24 + paddedJson, 0x004e4942, true);
|
|
70
|
+
let offset = 28 + paddedJson;
|
|
71
|
+
for (const chunk of chunks) { output.set(chunk, offset); offset += chunk.length; }
|
|
72
|
+
parseGlb(output);
|
|
73
|
+
return output;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Re-encode authored channels with the native separate-layout meshopt writer.
|
|
77
|
+
* No reorder, quantization transform or filter is applied. Deduplication is explicit. */
|
|
78
|
+
export async function meshoptGlb(input: Uint8Array, options: { readonly deduplicate?: boolean } = {}): Promise<Uint8Array> {
|
|
79
|
+
const bytes = Uint8Array.from(input), deduplicate = options.deduplicate === true;
|
|
80
|
+
await Promise.all([MeshoptEncoder.ready, MeshoptDecoder.ready]);
|
|
81
|
+
const io = new WebIO().setVertexLayout(VertexLayout.SEPARATE).registerExtensions([EXTMeshoptCompression])
|
|
82
|
+
.registerDependencies({ 'meshopt.encoder': MeshoptEncoder, 'meshopt.decoder': MeshoptDecoder });
|
|
83
|
+
const document = await io.readBinary(bytes);
|
|
84
|
+
if (deduplicate) await document.transform(dedup());
|
|
85
|
+
document.createExtension(EXTMeshoptCompression).setRequired(true).setEncoderOptions({ method: EXTMeshoptCompression.EncoderMethod.QUANTIZE });
|
|
86
|
+
return io.writeBinary(document);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function sameNumbers(a: ArrayLike<number> | null, b: ArrayLike<number> | null): boolean {
|
|
90
|
+
if (a === null || b === null || a.length !== b.length) return false;
|
|
91
|
+
for (let index = 0; index < a.length; index++) if (!Object.is(a[index], b[index])) return false;
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
const sameAccessor = (a: Accessor | null, b: Accessor | null): boolean => a !== null && b !== null
|
|
95
|
+
&& a.getType() === b.getType() && a.getNormalized() === b.getNormalized() && a.getComponentType() === b.getComponentType()
|
|
96
|
+
&& sameNumbers(a.getArray(), b.getArray());
|
|
97
|
+
|
|
98
|
+
/** Pack alternate vertex channels beside an identical static mesh, without
|
|
99
|
+
* requantizing its frame, positions, indices or existing channels. Both inputs
|
|
100
|
+
* require one unskinned mesh in the same frame and material; only explicitly
|
|
101
|
+
* selected channels may differ. New application accessors keep the source's
|
|
102
|
+
* exact component storage and normalization. Inputs remain independently owned.
|
|
103
|
+
*/
|
|
104
|
+
export async function pairedChannelGlb(primary: Uint8Array, alternate: Uint8Array, name: string,
|
|
105
|
+
channels: readonly { readonly from: string; readonly to: string }[]): Promise<Uint8Array> {
|
|
106
|
+
if (!/^[A-Za-z_][A-Za-z0-9_-]{0,127}$/u.test(name) || channels.length === 0 || channels.length > 8
|
|
107
|
+
|| new Set(channels.map(row => row.from)).size !== channels.length || new Set(channels.map(row => row.to)).size !== channels.length
|
|
108
|
+
|| channels.some(row => !/^[A-Z_][A-Z0-9_]*$/u.test(row.from) || !/^_[A-Z0-9_]+$/u.test(row.to) || row.from === 'POSITION')) throw new Error('Invalid paired GLB channels');
|
|
109
|
+
parseGlb(primary); parseGlb(alternate); await MeshoptDecoder.ready;
|
|
110
|
+
const io = new WebIO().setVertexLayout(VertexLayout.SEPARATE).registerExtensions([EXTMeshoptCompression, KHRMeshQuantization])
|
|
111
|
+
.registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
|
|
112
|
+
const left = await io.readBinary(Uint8Array.from(primary)), right = await io.readBinary(Uint8Array.from(alternate));
|
|
113
|
+
const a = left.getRoot(), b = right.getRoot(), node = a.listNodes()[0], otherNode = b.listNodes()[0], mesh = a.listMeshes()[0], otherMesh = b.listMeshes()[0];
|
|
114
|
+
if (node === undefined || otherNode === undefined || mesh === undefined || otherMesh === undefined
|
|
115
|
+
|| a.listNodes().length !== 1 || b.listNodes().length !== 1 || a.listMeshes().length !== 1 || b.listMeshes().length !== 1
|
|
116
|
+
|| a.listAnimations().length > 0 || b.listAnimations().length > 0 || a.listSkins().length > 0 || b.listSkins().length > 0
|
|
117
|
+
|| a.listTextures().length > 0 || b.listTextures().length > 0 || node.getMesh() !== mesh || otherNode.getMesh() !== otherMesh
|
|
118
|
+
|| !sameNumbers(node.getMatrix(), otherNode.getMatrix())) throw new Error('Paired GLB requires identical static frames');
|
|
119
|
+
const part = mesh.listPrimitives()[0], other = otherMesh.listPrimitives()[0];
|
|
120
|
+
const semantics = part?.listSemantics().sort(), otherSemantics = other?.listSemantics().sort();
|
|
121
|
+
if (part === undefined || other === undefined || mesh.listPrimitives().length !== 1 || otherMesh.listPrimitives().length !== 1
|
|
122
|
+
|| part.listTargets().length > 0 || other.listTargets().length > 0 || part.getMode() !== other.getMode()
|
|
123
|
+
|| semantics === undefined || otherSemantics === undefined || semantics.length !== otherSemantics.length
|
|
124
|
+
|| semantics.some((semantic, index) => semantic !== otherSemantics[index])
|
|
125
|
+
|| !sameAccessor(part.getAttribute('POSITION'), other.getAttribute('POSITION'))
|
|
126
|
+
|| (part.getIndices() !== null || other.getIndices() !== null) && !sameAccessor(part.getIndices(), other.getIndices())) throw new Error('Paired GLB topology differs');
|
|
127
|
+
const material = part.getMaterial(), otherMaterial = other.getMaterial();
|
|
128
|
+
if (material === null ? otherMaterial !== null : otherMaterial === null || !material.equals(otherMaterial)) throw new Error('Paired GLB material differs');
|
|
129
|
+
const selected = new Set(channels.map(row => row.from));
|
|
130
|
+
for (const semantic of part.listSemantics()) if (!selected.has(semantic) && !sameAccessor(part.getAttribute(semantic), other.getAttribute(semantic))) throw new Error(`Paired GLB channel differs: ${semantic}`);
|
|
131
|
+
const buffer = part.getAttribute('POSITION')?.getBuffer();
|
|
132
|
+
if (buffer === undefined || buffer === null) throw new Error('Missing paired GLB buffer');
|
|
133
|
+
for (const { from, to } of channels) {
|
|
134
|
+
const source = other.getAttribute(from), values = source?.getArray();
|
|
135
|
+
if (source === null || source === undefined || values === null || values === undefined || part.getAttribute(to) !== null) throw new Error('Missing or duplicate paired GLB channel');
|
|
136
|
+
part.setAttribute(to, left.createAccessor(to).setType(source.getType()).setNormalized(source.getNormalized()).setArray(values.slice()).setBuffer(buffer));
|
|
137
|
+
}
|
|
138
|
+
node.setName(name); mesh.setName(name);
|
|
139
|
+
// Decode the old transport once, then use the existing lossless view codec.
|
|
140
|
+
// No second grid quantization or meshopt attribute filter enters the table.
|
|
141
|
+
for (const extension of a.listExtensionsUsed()) if (extension.extensionName === EXT) extension.dispose();
|
|
142
|
+
return compressGlb(await io.writeBinary(left));
|
|
143
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { NodeIO } from '@gltf-transform/core';
|
|
2
|
+
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
|
|
3
|
+
import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
|
|
4
|
+
import * as v from 'valibot';
|
|
5
|
+
import { isJsonData } from '@wildshard/format/json';
|
|
6
|
+
import { parseGlb } from '@wildshard/format/product';
|
|
7
|
+
|
|
8
|
+
const MAX_BYTES = 25_000_000;
|
|
9
|
+
const count = v.pipe(v.number(), v.integer(), v.minValue(0));
|
|
10
|
+
const sourceSchema = v.looseObject({ asset: v.looseObject({ version: v.literal('2.0') }),
|
|
11
|
+
buffers: v.exactOptional(v.array(v.looseObject({ byteLength: count, uri: v.exactOptional(v.string()) }))),
|
|
12
|
+
images: v.exactOptional(v.array(v.looseObject({ uri: v.exactOptional(v.string()), mimeType: v.exactOptional(v.string()), bufferView: v.exactOptional(count) }))),
|
|
13
|
+
extensionsUsed: v.exactOptional(v.array(v.string())), extensionsRequired: v.exactOptional(v.array(v.string())) });
|
|
14
|
+
|
|
15
|
+
/** Compile textual glTF and its bounded resources to one self-contained GLB. The injected reader owns path admission;
|
|
16
|
+
* NodeIO never reads a URL or filesystem path. Meshes, skin, animation and original image bytes use the existing
|
|
17
|
+
* SDK bake dependencies; unsupported extensions refuse instead of disappearing during conversion. */
|
|
18
|
+
export async function compileGltfSource(bytes: Uint8Array, read: (uri: string) => Uint8Array): Promise<Uint8Array> {
|
|
19
|
+
if (bytes.length === 0 || bytes.length > MAX_BYTES) throw new Error('glTF source exceeds its byte cap');
|
|
20
|
+
const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
21
|
+
if (!isJsonData(value)) throw new Error('glTF source must be plain JSON');
|
|
22
|
+
const source = v.parse(sourceSchema, value), supported = new Set(ALL_EXTENSIONS.map(extension => extension.EXTENSION_NAME));
|
|
23
|
+
const checkExtensions = (input: unknown): void => {
|
|
24
|
+
if (typeof input !== 'object' || input === null) return;
|
|
25
|
+
for (const [key, member] of Object.entries(input)) {
|
|
26
|
+
const child: unknown = member;
|
|
27
|
+
if (key === 'extensions' && typeof child === 'object' && child !== null && Object.keys(child).some(name => !supported.has(name))) throw new Error('glTF source requires an unsupported extension');
|
|
28
|
+
checkExtensions(child);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
if ([...source.extensionsUsed ?? [], ...source.extensionsRequired ?? []].some(name => !supported.has(name))) throw new Error('glTF source requires an unsupported extension');
|
|
32
|
+
checkExtensions(source);
|
|
33
|
+
const resources = new Map<string, Uint8Array<ArrayBuffer>>(), sizes = new Map<string, number>();
|
|
34
|
+
let total = bytes.length;
|
|
35
|
+
for (const row of [...source.buffers ?? [], ...source.images ?? []]) {
|
|
36
|
+
if (row.uri === undefined || sizes.has(row.uri)) continue;
|
|
37
|
+
if (row.uri.startsWith('data:')) {
|
|
38
|
+
if (!/^data:(?:application\/(?:octet-stream|gltf-buffer)|image\/(?:png|jpeg|webp|ktx2));base64,[A-Za-z0-9+/]*={0,2}$/u.test(row.uri)) throw new Error('glTF embedded resource must be bounded base64');
|
|
39
|
+
const data = row.uri.slice(row.uri.indexOf(',') + 1);
|
|
40
|
+
if (data.length % 4 !== 0) throw new Error('glTF embedded resource has incomplete base64');
|
|
41
|
+
const size = data.length * 3 / 4 - (data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0);
|
|
42
|
+
total += size; sizes.set(row.uri, size);
|
|
43
|
+
} else {
|
|
44
|
+
const resource = Uint8Array.from(read(row.uri));
|
|
45
|
+
total += resource.length; resources.set(row.uri, resource); sizes.set(row.uri, resource.length);
|
|
46
|
+
}
|
|
47
|
+
if (total > MAX_BYTES * 2) throw new Error('glTF resources exceed their combined byte cap');
|
|
48
|
+
}
|
|
49
|
+
if (source.buffers?.some(buffer => buffer.uri === undefined || sizes.get(buffer.uri) !== buffer.byteLength) === true) throw new Error('glTF buffer differs from its declared byte length');
|
|
50
|
+
await Promise.all([MeshoptDecoder.ready, MeshoptEncoder.ready]);
|
|
51
|
+
const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.decoder': MeshoptDecoder, 'meshopt.encoder': MeshoptEncoder });
|
|
52
|
+
const document = await io.readJSON({ json: source, resources: Object.fromEntries(resources) }), root = document.getRoot();
|
|
53
|
+
const buffer = root.listBuffers()[0] ?? document.createBuffer();
|
|
54
|
+
for (const accessor of root.listAccessors()) accessor.setBuffer(buffer);
|
|
55
|
+
for (const other of root.listBuffers()) if (other !== buffer) other.dispose();
|
|
56
|
+
const result = await io.writeBinary(document);
|
|
57
|
+
parseGlb(result);
|
|
58
|
+
return result;
|
|
59
|
+
}
|