ugly-game 0.15.42 → 0.15.44

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.
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export declare const CROWD_MATERIAL_COUNT = 5;
2
3
  export declare const CROWD_RECORD_FLOATS = 24;
3
4
  export declare const CROWD_REC_LAYER = 20;
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // ─────────────────────────────────────────────────────────────────────────────
2
3
  // GPU CROWD — thousands of individually-shaped, individually-animated characters.
3
4
  //
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export declare const MAX_CASCADES = 4;
2
3
  /**
3
4
  * Per-world surface + motion parameters.
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // ─────────────────────────────────────────────────────────────────────────────
2
3
  // GPU PROPS — instanced static-mesh renderer for scattered nature props (PLATFORM). Draws each cooked
3
4
  // model (tree/rock/bush/…) many times at per-instance world transforms, lit + fogged to match the
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export interface SkinCreature {
2
3
  rest: Float32Array;
3
4
  normals: Float32Array;
@@ -1,9 +1,4 @@
1
- // ─────────────────────────────────────────────────────────────────────────────
2
- // GPU SKIN — a reusable WebGPU renderer for skinned creatures (PLATFORM). A compute pass deforms the
3
- // rest mesh (AND its normals) by each creature's bone palette; the render pass draws them with the SAME
4
- // lighting model as the terrain/prop renderers — sun lambert on smooth per-vertex normals + ambient +
5
- // distance fog — so creatures sit in the scene consistently instead of looking flat/mismatched.
6
- // ─────────────────────────────────────────────────────────────────────────────
1
+ /// <reference types="@webgpu/types" preserve="true" />
7
2
  export const MAX_CASCADES = 4; // must match gpuShadow's
8
3
  const SKIN = /* wgsl */ `
9
4
  @group(0) @binding(0) var<storage,read> rest: array<vec4f>;
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export interface TranscodedTexture {
2
3
  texture: GPUTexture;
3
4
  format: GPUTextureFormat;
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // Runtime Basis Universal transcoder → GPU-compressed WebGPU texture. The runtime half of
2
3
  // design/asset-streaming.md §3/§4: a cooked .ugm carries textures as ETC1S KTX2 (see
3
4
  // demo/cli/assets/texture.ts cookTextureBasis), and at load we transcode them to whatever compressed
@@ -68,8 +68,52 @@ export interface GpuCharactersBatch {
68
68
  }
69
69
  export interface GpuCharactersBackend {
70
70
  submit(batch: GpuCharactersBatch): void;
71
+ /** Present when the backend applies an explicit per-frame render budget. */
72
+ characterBudgetReport?(): GpuCharacterBudgetReport;
71
73
  dispose?(): void;
72
74
  }
75
+ export type GpuCharacterBudgetReason = 'actor-capacity' | 'part-capacity' | 'part-cost-capacity';
76
+ export interface GpuCharacterBudgetLimits {
77
+ /** Maximum visible actors retained in one frame. Omitted means unbounded. */
78
+ maxActors?: number;
79
+ /** Maximum composed body/face/hair/garment/attachment rows. Omitted means unbounded. */
80
+ maxParts?: number;
81
+ /**
82
+ * Weighted part budget. Tier 0 costs eight units and tier 7 costs one, per part. The policy
83
+ * deterministically raises quality tiers before it drops an optional part or whole actor.
84
+ */
85
+ maxPartCost?: number;
86
+ }
87
+ export interface GpuCharacterBudgetRequest {
88
+ requestedActors: number;
89
+ requestedParts: number;
90
+ requestedPartCost: number;
91
+ }
92
+ export type GpuCharacterBudgetPolicy = GpuCharacterBudgetLimits | ((request: Readonly<GpuCharacterBudgetRequest>) => GpuCharacterBudgetLimits);
93
+ export interface GpuCharacterBudgetFinding {
94
+ code: 'gpu-characters-tier-demoted' | 'gpu-characters-part-dropped' | 'gpu-characters-actor-dropped';
95
+ reason: GpuCharacterBudgetReason;
96
+ actorSlot: number;
97
+ tier?: keyof Omit<GpuCharacterTiers, 'visible'>;
98
+ fromTier?: number;
99
+ toTier?: number;
100
+ partKind?: GpuCharacterPartKind;
101
+ asset?: number;
102
+ }
103
+ export interface GpuCharacterBudgetReport extends GpuCharacterBudgetRequest {
104
+ limits: {
105
+ maxActors: number | null;
106
+ maxParts: number | null;
107
+ maxPartCost: number | null;
108
+ };
109
+ renderedActors: number;
110
+ renderedParts: number;
111
+ renderedPartCost: number;
112
+ tierDemotions: number;
113
+ droppedActors: number;
114
+ droppedParts: number;
115
+ findings: readonly GpuCharacterBudgetFinding[];
116
+ }
73
117
  /**
74
118
  * The crowd renderer allocates vertex-pool offsets, while {@link GpuCharacters} allocates stable
75
119
  * actor ordinals. A binding is the explicit bridge between those two address spaces.
@@ -236,6 +280,8 @@ export interface GpuCrowdCharactersBackendOptions {
236
280
  socketCount?: number;
237
281
  /** Explicit handoff to caller-owned hair, garment and attachment render passes. */
238
282
  composition?: GpuCrowdCharacterCompositionBackend;
283
+ /** Optional deterministic pressure policy. No budget means every requested visible part renders. */
284
+ budget?: GpuCharacterBudgetPolicy;
239
285
  }
240
286
  export interface GpuCrowdCharactersPreparedFrame {
241
287
  renderedCount: number;
@@ -245,6 +291,7 @@ export interface GpuCrowdCharactersPreparedFrame {
245
291
  palettes: Float32Array;
246
292
  buckets: readonly CrowdBucket[];
247
293
  composition: GpuCrowdCharacterCompositionFrame;
294
+ budget: GpuCharacterBudgetReport;
248
295
  }
249
296
  export interface GpuCharactersReport {
250
297
  capacity: number;
@@ -256,6 +303,8 @@ export interface GpuCharactersReport {
256
303
  removals: number;
257
304
  /** Counts by tier for visible actors in the most recently submitted hot frame. */
258
305
  lastTierCounts: Record<'body' | 'face' | 'animation' | 'hair' | 'cloth', number[]>;
306
+ /** Backend render pressure for the last successful frame; null for backends without this seam. */
307
+ budget: GpuCharacterBudgetReport | null;
259
308
  }
260
309
  /** Validate a hot frame without allocating or converting it. */
261
310
  export declare function validateGpuCharacterFrame(frame: GpuCharacterFrame, options: Omit<Required<GpuCharactersOptions>, 'socketCount'> & Pick<GpuCharactersOptions, 'socketCount'>): void;
@@ -296,6 +345,7 @@ export declare class GpuCrowdCharactersBackend implements GpuCharactersBackend {
296
345
  private readonly faceChannels;
297
346
  private readonly socketCount;
298
347
  private readonly maxRiggedFaceTier;
348
+ private readonly budgetPolicy;
299
349
  private readonly compositionBackend;
300
350
  private readonly resolveBinding;
301
351
  private readonly releaseBinding;
@@ -304,6 +354,7 @@ export declare class GpuCrowdCharactersBackend implements GpuCharactersBackend {
304
354
  constructor(options: GpuCrowdCharactersBackendOptions);
305
355
  submit(batch: GpuCharactersBatch): void;
306
356
  lastPreparedFrame(): GpuCrowdCharactersPreparedFrame;
357
+ characterBudgetReport(): GpuCharacterBudgetReport;
307
358
  dispose(): void;
308
359
  private applyRemovals;
309
360
  private applyIdentityUpdates;
package/dist/character.js CHANGED
@@ -455,6 +455,7 @@ export class GpuCharacters {
455
455
  coldUpdates: this.coldUpdates,
456
456
  removals: this.removals,
457
457
  lastTierCounts: cloneTierCounts(this.lastTierCounts),
458
+ budget: this.backend?.characterBudgetReport?.() ?? null,
458
459
  };
459
460
  }
460
461
  dispose() {
@@ -539,6 +540,229 @@ function emptyComposition() {
539
540
  bounds: new Float32Array(0),
540
541
  };
541
542
  }
543
+ function budgetParts(entry) {
544
+ const { identity } = entry.state;
545
+ const parts = [
546
+ {
547
+ key: `${entry.actorSlot}:body`,
548
+ kind: GPU_CHARACTER_PART_KIND.body,
549
+ asset: identity.bodyAsset ?? -1,
550
+ tier: 'body',
551
+ },
552
+ {
553
+ key: `${entry.actorSlot}:face`,
554
+ kind: GPU_CHARACTER_PART_KIND.face,
555
+ asset: identity.faceAsset ?? identity.bodyAsset ?? -1,
556
+ tier: 'face',
557
+ },
558
+ ];
559
+ if (identity.hairAsset >= 0)
560
+ parts.push({
561
+ key: `${entry.actorSlot}:hair`,
562
+ kind: GPU_CHARACTER_PART_KIND.hair,
563
+ asset: identity.hairAsset,
564
+ tier: 'hair',
565
+ });
566
+ identity.garmentAssets.forEach((asset, index) => {
567
+ if (asset >= 0)
568
+ parts.push({
569
+ key: `${entry.actorSlot}:garment:${index}`,
570
+ kind: GPU_CHARACTER_PART_KIND.garment,
571
+ asset,
572
+ tier: 'cloth',
573
+ });
574
+ });
575
+ (identity.socketAttachments ?? []).forEach((attachment, index) => {
576
+ if (attachment.asset >= 0)
577
+ parts.push({
578
+ key: `${entry.actorSlot}:attachment:${index}`,
579
+ kind: GPU_CHARACTER_PART_KIND.socketAttachment,
580
+ asset: attachment.asset,
581
+ tier: 'body',
582
+ });
583
+ });
584
+ return parts;
585
+ }
586
+ function partCost(entry, part) {
587
+ return TIER_MASK + 1 - entry.tiers[part.tier];
588
+ }
589
+ function maxBudgetTier(entry, tier, maxRiggedFaceTier) {
590
+ const contiguousMax = (slots, from) => {
591
+ let maximum = from;
592
+ for (let candidate = from + 1; candidate < slots.length; candidate++) {
593
+ const slot = slots[candidate];
594
+ if (!Number.isInteger(slot) || (slot ?? -1) < 0)
595
+ break;
596
+ maximum = candidate;
597
+ }
598
+ return maximum;
599
+ };
600
+ if (tier === 'body') {
601
+ const attachmentLimits = (entry.state.binding.socketAttachments ?? [])
602
+ .filter((binding) => binding !== null)
603
+ .map((binding) => contiguousMax(binding.lodSlots, entry.tiers.body));
604
+ const faceLimit = entry.tiers.face <= maxRiggedFaceTier && entry.state.binding.facePoolSlots
605
+ ? contiguousMax(entry.state.binding.facePoolSlots, entry.tiers.body)
606
+ : TIER_MASK;
607
+ return Math.min(TIER_MASK, entry.state.binding.poolSlots.length - 1, faceLimit, ...attachmentLimits);
608
+ }
609
+ if (tier === 'hair')
610
+ return Math.min(TIER_MASK, entry.state.binding.hair
611
+ ? contiguousMax(entry.state.binding.hair.lodSlots, entry.tiers.hair)
612
+ : entry.tiers.hair);
613
+ if (tier === 'cloth') {
614
+ const garmentLimits = (entry.state.binding.garments ?? [])
615
+ .filter((binding) => binding !== null)
616
+ .map((binding) => contiguousMax(binding.lodSlots, entry.tiers.cloth));
617
+ return garmentLimits.length === 0
618
+ ? entry.tiers.cloth
619
+ : Math.min(TIER_MASK, ...garmentLimits);
620
+ }
621
+ return TIER_MASK;
622
+ }
623
+ function cloneBudgetReport(report) {
624
+ return {
625
+ ...report,
626
+ limits: { ...report.limits },
627
+ findings: report.findings.map((finding) => ({ ...finding })),
628
+ };
629
+ }
630
+ function planCharacterBudget(sourceEntries, policy, maxRiggedFaceTier = 1) {
631
+ const entries = sourceEntries.map((entry) => ({
632
+ ...entry,
633
+ tiers: { ...entry.tiers },
634
+ }));
635
+ const budgetOrder = [...entries].sort((a, b) => a.actorSlot - b.actorSlot);
636
+ const requestedParts = entries.reduce((count, entry) => count + budgetParts(entry).length, 0);
637
+ const requestedPartCost = entries.reduce((cost, entry) => cost +
638
+ budgetParts(entry).reduce((actorCost, part) => actorCost + partCost(entry, part), 0), 0);
639
+ const request = {
640
+ requestedActors: entries.length,
641
+ requestedParts,
642
+ requestedPartCost,
643
+ };
644
+ const requestedLimits = typeof policy === 'function' ? policy(request) : policy;
645
+ const maxActors = requestedLimits?.maxActors === undefined
646
+ ? Number.POSITIVE_INFINITY
647
+ : nonNegativeInt(requestedLimits.maxActors, 'budget.maxActors');
648
+ const maxParts = requestedLimits?.maxParts === undefined
649
+ ? Number.POSITIVE_INFINITY
650
+ : nonNegativeInt(requestedLimits.maxParts, 'budget.maxParts');
651
+ const maxPartCost = requestedLimits?.maxPartCost === undefined
652
+ ? Number.POSITIVE_INFINITY
653
+ : nonNegativeInt(requestedLimits.maxPartCost, 'budget.maxPartCost');
654
+ const findings = [];
655
+ const droppedPartKeys = new Set();
656
+ const droppedActorSlots = new Set();
657
+ const activeParts = () => entries.flatMap((entry) => droppedActorSlots.has(entry.actorSlot)
658
+ ? []
659
+ : budgetParts(entry)
660
+ .filter((part) => !droppedPartKeys.has(part.key))
661
+ .map((part) => ({ entry, part })));
662
+ const currentCost = () => activeParts().reduce((cost, { entry, part }) => cost + partCost(entry, part), 0);
663
+ // Preserve lower stable actor slots and their quality. Under pressure, higher slots walk the
664
+ // deterministic hair → cloth → face → body ladder first; only then may anything disappear.
665
+ const needsPartRelief = () => activeParts().length > maxParts || currentCost() > maxPartCost;
666
+ while (needsPartRelief()) {
667
+ let changed = false;
668
+ for (const entry of [...budgetOrder].reverse()) {
669
+ for (const tier of ['hair', 'cloth', 'face', 'body']) {
670
+ const affected = budgetParts(entry).filter((part) => part.tier === tier);
671
+ const maximum = maxBudgetTier(entry, tier, maxRiggedFaceTier);
672
+ if (affected.length === 0 || entry.tiers[tier] >= maximum)
673
+ continue;
674
+ const reason = currentCost() > maxPartCost ? 'part-cost-capacity' : 'part-capacity';
675
+ const fromTier = entry.tiers[tier];
676
+ entry.tiers[tier]++;
677
+ if (tier === 'body')
678
+ entry.lod = entry.tiers.body;
679
+ findings.push({
680
+ code: 'gpu-characters-tier-demoted',
681
+ reason,
682
+ actorSlot: entry.actorSlot,
683
+ tier,
684
+ fromTier,
685
+ toTier: entry.tiers[tier],
686
+ });
687
+ changed = true;
688
+ if (!needsPartRelief())
689
+ break;
690
+ }
691
+ if (!needsPartRelief())
692
+ break;
693
+ }
694
+ if (!changed)
695
+ break;
696
+ }
697
+ while (entries.length - droppedActorSlots.size > maxActors) {
698
+ const entry = [...budgetOrder]
699
+ .reverse()
700
+ .find((candidate) => !droppedActorSlots.has(candidate.actorSlot));
701
+ if (!entry)
702
+ break;
703
+ droppedActorSlots.add(entry.actorSlot);
704
+ findings.push({
705
+ code: 'gpu-characters-actor-dropped',
706
+ reason: 'actor-capacity',
707
+ actorSlot: entry.actorSlot,
708
+ });
709
+ }
710
+ const optionalParts = activeParts()
711
+ .filter(({ part }) => part.kind !== GPU_CHARACTER_PART_KIND.body &&
712
+ part.kind !== GPU_CHARACTER_PART_KIND.face)
713
+ .sort((a, b) => b.entry.actorSlot - a.entry.actorSlot ||
714
+ b.part.kind - a.part.kind ||
715
+ b.part.key.localeCompare(a.part.key));
716
+ for (const { entry, part } of optionalParts) {
717
+ if (!needsPartRelief())
718
+ break;
719
+ const reason = currentCost() > maxPartCost ? 'part-cost-capacity' : 'part-capacity';
720
+ droppedPartKeys.add(part.key);
721
+ findings.push({
722
+ code: 'gpu-characters-part-dropped',
723
+ reason,
724
+ actorSlot: entry.actorSlot,
725
+ partKind: part.kind,
726
+ asset: part.asset,
727
+ });
728
+ }
729
+ while (needsPartRelief()) {
730
+ const entry = [...budgetOrder]
731
+ .reverse()
732
+ .find((candidate) => !droppedActorSlots.has(candidate.actorSlot));
733
+ if (!entry)
734
+ break;
735
+ const reason = currentCost() > maxPartCost ? 'part-cost-capacity' : 'part-capacity';
736
+ droppedActorSlots.add(entry.actorSlot);
737
+ findings.push({
738
+ code: 'gpu-characters-actor-dropped',
739
+ reason,
740
+ actorSlot: entry.actorSlot,
741
+ });
742
+ }
743
+ const renderedEntries = entries.filter((entry) => !droppedActorSlots.has(entry.actorSlot));
744
+ const renderedParts = activeParts().length;
745
+ const renderedPartCost = currentCost();
746
+ return {
747
+ entries: renderedEntries,
748
+ droppedPartKeys,
749
+ report: {
750
+ ...request,
751
+ limits: {
752
+ maxActors: Number.isFinite(maxActors) ? maxActors : null,
753
+ maxParts: Number.isFinite(maxParts) ? maxParts : null,
754
+ maxPartCost: Number.isFinite(maxPartCost) ? maxPartCost : null,
755
+ },
756
+ renderedActors: renderedEntries.length,
757
+ renderedParts,
758
+ renderedPartCost,
759
+ tierDemotions: findings.filter((finding) => finding.code === 'gpu-characters-tier-demoted').length,
760
+ droppedActors: request.requestedActors - renderedEntries.length,
761
+ droppedParts: request.requestedParts - renderedParts,
762
+ findings,
763
+ },
764
+ };
765
+ }
542
766
  function validatePartBinding(binding, asset, label) {
543
767
  if (asset < 0) {
544
768
  if (binding)
@@ -566,6 +790,7 @@ export class GpuCrowdCharactersBackend {
566
790
  faceChannels;
567
791
  socketCount;
568
792
  maxRiggedFaceTier;
793
+ budgetPolicy;
569
794
  compositionBackend;
570
795
  resolveBinding;
571
796
  releaseBinding;
@@ -577,6 +802,7 @@ export class GpuCrowdCharactersBackend {
577
802
  palettes: new Float32Array(0),
578
803
  buckets: [],
579
804
  composition: emptyComposition(),
805
+ budget: planCharacterBudget([], undefined).report,
580
806
  };
581
807
  constructor(options) {
582
808
  this.renderer = options.renderer;
@@ -585,6 +811,7 @@ export class GpuCrowdCharactersBackend {
585
811
  if (this.faceChannels !== GPU_CHARACTER_FACE_CHANNELS)
586
812
  throw new Error(`GpuCrowdRenderer requires ${GPU_CHARACTER_FACE_CHANNELS} face channels`);
587
813
  this.socketCount = nonNegativeInt(options.socketCount ?? 0, 'socketCount');
814
+ this.budgetPolicy = options.budget;
588
815
  this.compositionBackend = options.composition;
589
816
  this.resolveBinding = options.resolveBinding;
590
817
  this.releaseBinding = options.releaseBinding;
@@ -600,7 +827,7 @@ export class GpuCrowdCharactersBackend {
600
827
  throw new Error(`socketTransforms length ${socketValues} does not match backend requirement ${expectedSocketValues}`);
601
828
  this.applyRemovals(batch.removedSlots);
602
829
  this.applyIdentityUpdates(batch.identityUpdates);
603
- const entries = [];
830
+ const requestedEntries = [];
604
831
  for (let i = 0; i < batch.frame.count; i++) {
605
832
  const tiers = unpackGpuCharacterFlags(batch.frame.flags[i]);
606
833
  if (!tiers.visible)
@@ -611,7 +838,7 @@ export class GpuCrowdCharactersBackend {
611
838
  throw new Error(`crowd backend has no identity for actor slot ${actorSlot}`);
612
839
  // Stable sorting below preserves actor order within a LOD, including blend ordering chosen
613
840
  // by the caller. That makes buckets contiguous without changing same-rung draw semantics.
614
- entries.push({
841
+ requestedEntries.push({
615
842
  actorSlot,
616
843
  sourceIndex: i,
617
844
  lod: tiers.body,
@@ -619,20 +846,16 @@ export class GpuCrowdCharactersBackend {
619
846
  state,
620
847
  });
621
848
  }
849
+ const budget = planCharacterBudget(requestedEntries, this.budgetPolicy, this.maxRiggedFaceTier);
850
+ const entries = budget.entries;
622
851
  entries.sort((a, b) => a.lod - b.lod);
623
852
  const records = new Float32Array(entries.length * CROWD_RECORD_FLOATS);
624
853
  const palettes = new Float32Array(entries.length * this.boneCount * 16);
625
854
  const actorSlots = new Uint32Array(entries.length);
626
855
  const buckets = [];
627
856
  const paletteStride = this.boneCount * 16;
628
- const compositionCount = entries.reduce((count, entry) => {
629
- const identity = entry.state.identity;
630
- return (count +
631
- 2 +
632
- (identity.hairAsset < 0 ? 0 : 1) +
633
- identity.garmentAssets.filter((asset) => asset >= 0).length +
634
- (identity.socketAttachments ?? []).filter((attachment) => attachment.asset >= 0).length);
635
- }, 0);
857
+ const compositionCount = entries.reduce((count, entry) => count +
858
+ budgetParts(entry).filter((part) => !budget.droppedPartKeys.has(part.key)).length, 0);
636
859
  const composition = {
637
860
  count: compositionCount,
638
861
  actorSlots: new Uint32Array(compositionCount),
@@ -656,9 +879,8 @@ export class GpuCrowdCharactersBackend {
656
879
  state.morphedLod = lod;
657
880
  }
658
881
  const wantsFace = tiers.face <= this.maxRiggedFaceTier;
659
- const facePoolSlot = wantsFace
660
- ? bindingFaceSlot(state.binding, lod)
661
- : null;
882
+ const composedFacePoolSlot = bindingFaceSlot(state.binding, lod);
883
+ const facePoolSlot = wantsFace ? composedFacePoolSlot : null;
662
884
  if (wantsFace && facePoolSlot === null)
663
885
  throw new Error(`character binding has no face pool slot for rigged actor ${actorSlot} at LOD ${lod}`);
664
886
  if (state.rigSource !== null && state.rigSource !== sourcePoolSlot) {
@@ -698,21 +920,24 @@ export class GpuCrowdCharactersBackend {
698
920
  const bodyAsset = state.identity.bodyAsset ?? -1;
699
921
  const faceAsset = state.identity.faceAsset ?? bodyAsset;
700
922
  writePart(GPU_CHARACTER_PART_KIND.body, bodyAsset, sourcePoolSlot, lod, tiers.body, transform);
701
- writePart(GPU_CHARACTER_PART_KIND.face, faceAsset, facePoolSlot ?? sourcePoolSlot, lod, tiers.face, transform);
702
- if (state.identity.hairAsset >= 0) {
923
+ writePart(GPU_CHARACTER_PART_KIND.face, faceAsset, composedFacePoolSlot ?? sourcePoolSlot, lod, tiers.face, transform);
924
+ if (state.identity.hairAsset >= 0 &&
925
+ !budget.droppedPartKeys.has(`${actorSlot}:hair`)) {
703
926
  const binding = state.binding.hair;
704
927
  if (!binding)
705
928
  throw new Error('hair binding is unavailable');
706
929
  writePart(GPU_CHARACTER_PART_KIND.hair, state.identity.hairAsset, partBindingSlot(binding, tiers.hair, 'hair'), tiers.hair, tiers.hair, transform);
707
930
  }
708
931
  for (const [garmentIndex, asset,] of state.identity.garmentAssets.entries()) {
709
- if (asset < 0)
932
+ if (asset < 0 ||
933
+ budget.droppedPartKeys.has(`${actorSlot}:garment:${garmentIndex}`))
710
934
  continue;
711
935
  const binding = indexedPartBinding(state.binding.garments, garmentIndex, `garment ${garmentIndex}`);
712
936
  writePart(GPU_CHARACTER_PART_KIND.garment, asset, partBindingSlot(binding, tiers.cloth, `garment ${garmentIndex}`), tiers.cloth, tiers.cloth, transform);
713
937
  }
714
938
  for (const [attachmentIndex, attachment] of (state.identity.socketAttachments ?? []).entries()) {
715
- if (attachment.asset < 0)
939
+ if (attachment.asset < 0 ||
940
+ budget.droppedPartKeys.has(`${actorSlot}:attachment:${attachmentIndex}`))
716
941
  continue;
717
942
  const socketTransforms = batch.frame.socketTransforms;
718
943
  if (!socketTransforms)
@@ -740,6 +965,7 @@ export class GpuCrowdCharactersBackend {
740
965
  palettes,
741
966
  buckets: buckets.map((bucket) => ({ ...bucket })),
742
967
  composition,
968
+ budget: cloneBudgetReport(budget.report),
743
969
  };
744
970
  this.compositionBackend?.submitComposition(composition, {
745
971
  palettes,
@@ -749,6 +975,9 @@ export class GpuCrowdCharactersBackend {
749
975
  lastPreparedFrame() {
750
976
  return this.prepared;
751
977
  }
978
+ characterBudgetReport() {
979
+ return cloneBudgetReport(this.prepared.budget);
980
+ }
752
981
  dispose() {
753
982
  for (const state of this.states.values())
754
983
  this.releaseState(state);
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export interface FrameStats {
2
3
  meanLum: number;
3
4
  minLum: number;
@@ -1,9 +1,4 @@
1
- // FULL-FRAME visual-regression harness: render a pinned deterministic scene to an offscreen
2
- // target, READ THE WHOLE FRAMEBUFFER BACK, and reduce it to (a) sanity stats and (b) a small
3
- // perceptual SIGNATURE that can be compared to a committed golden. This is how the eyeballed
4
- // render demos become actual regression tests — a broken render (all-black, blown-out, changed)
5
- // fails automatically instead of needing a human to notice. Pairs with shaderProbe.ts (which
6
- // checks material values); this checks a whole rendered frame.
1
+ /// <reference types="@webgpu/types" preserve="true" />
7
2
  const SIZE = 256, GRID = 8; // 256×256 render (bytesPerRow = 1024, 256-aligned); 8×8 signature
8
3
  export class FrameProbe {
9
4
  device;
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export interface Instance {
2
3
  x: number;
3
4
  y: number;
package/dist/gpuDriven.js CHANGED
@@ -1,14 +1,4 @@
1
- // ─────────────────────────────────────────────────────────────────────────────
2
- // GPU-DRIVEN render backend (WebGPU) — executes the render IR's DrawPlan on the GPU.
3
- // The whole scene lives in a storage buffer; a COMPUTE shader frustum-culls every
4
- // instance and writes, per pipeline (material), an atomic instanceCount + a compacted
5
- // list of visible instance indices; then ONE indirect draw per pipeline renders all
6
- // its visible instances. CPU draw calls = O(pipelines), independent of instance count.
7
- //
8
- // This is the real backend for the render IR (shared/renderIR.ts is the CPU reference
9
- // oracle it's validated against). Instances are billboarded quads for now — the shape
10
- // is not the point; the draw-call model is. See design/moonshot-open-world.md §5.
11
- // ─────────────────────────────────────────────────────────────────────────────
1
+ /// <reference types="@webgpu/types" preserve="true" />
12
2
  const INSTANCE_F32 = 8; // pos.xyz, scale | material, bounds, pad, pad
13
3
  const ARG_U32 = 4; // drawIndirect: vertexCount, instanceCount, firstVertex, firstInstance
14
4
  const WGSL = /* wgsl */ `
package/dist/gpuGI.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export interface GIBox {
2
3
  x: number;
3
4
  y: number;
package/dist/gpuGI.js CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // Render increment 8 — BAKED GLOBAL ILLUMINATION via an irradiance probe grid (DDGI-style).
2
3
  // The last of GAME.md §3.6's named look gaps. Real-time path tracing is out; the tractable form
3
4
  // is to PRECOMPUTE indirect light into a 3D grid of probes, then sample it per-pixel. Each probe
@@ -1,4 +1,5 @@
1
- import { type Graph } from './shaderGraph';
1
+ /// <reference types="@webgpu/types" preserve="true" />
2
+ import { type Graph } from './shaderGraph.js';
2
3
  export interface GraphInstance {
3
4
  x: number;
4
5
  y: number;
package/dist/gpuGraph.js CHANGED
@@ -1,9 +1,10 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // Renders each shader GRAPH as its own pipeline: compileGraph() emits a `material()` WGSL fn that
2
3
  // is spliced into a shared scene template (cube instances + Cook-Torrance PBR lighting). So the
3
4
  // LIGHTING is engine-owned and identical; only the artist-authored material() differs per graph —
4
5
  // exactly how a production shader-graph pipeline works. No hand-written per-material WGSL.
5
- import { CUBE } from './cube';
6
- import { compileGraph } from './shaderGraph';
6
+ import { CUBE } from './cube.js';
7
+ import { compileGraph } from './shaderGraph.js';
7
8
  function sceneWGSL(materialFn) {
8
9
  return /* wgsl */ `
9
10
  struct Inst { pos: vec4<f32>, scl: vec4<f32> };
package/dist/gpuLit.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export interface Instance {
2
3
  x: number;
3
4
  y: number;
package/dist/gpuLit.js CHANGED
@@ -1,12 +1,4 @@
1
- // ─────────────────────────────────────────────────────────────────────────────
2
- // GPU-driven LIT renderer — the shading program begins here (GAME.md §3.6). Builds
3
- // on the proven cull backend (compute frustum-cull → per-pipeline indirect draw) and
4
- // adds real lighting: instances render as lit impostor SPHERES (a billboard quad whose
5
- // fragment reconstructs a sphere normal), shaded by a directional sun + a buffer of
6
- // MANY dynamic POINT LIGHTS. This is the many-dynamic-lights look the open-world axis
7
- // needs; a later increment adds tiled/clustered light culling to scale the light count.
8
- // See design/moonshot-open-world.md §5 (phase 4), design/engine-build-plan.md.
9
- // ─────────────────────────────────────────────────────────────────────────────
1
+ /// <reference types="@webgpu/types" preserve="true" />
10
2
  const INSTANCE_F32 = 8, ARG_U32 = 4, LIGHT_F32 = 8, CAM_F32 = 64;
11
3
  const WGSL = /* wgsl */ `
12
4
  struct Inst { pos: vec4<f32>, attr: vec4<f32> };
package/dist/gpuPost.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export declare class PostChain {
2
3
  private device;
3
4
  private w;
package/dist/gpuPost.js CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // Stage 2 — a MULTI-STEP GPU POST-PROCESSING CHAIN over the HDR scene, the thing the earlier
2
3
  // "few draw calls, analytic shading" demos conspicuously lacked. Five fullscreen passes:
3
4
  // 1. BRIGHT extract (threshold the HDR → the bloom/flare source, at half res)
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export declare const SHADOW_SIZE = 2048;
2
3
  export declare const SHADOW_WGSL = "\nfn shadowFactor(lightVP: mat4x4<f32>, world: vec3<f32>, ndl: f32, texel: f32,\n shadowMap: texture_depth_2d, shadowSamp: sampler_comparison) -> f32 {\n let lp = lightVP * vec4(world, 1.0);\n let proj = lp.xyz / lp.w;\n let uv = proj.xy * vec2(0.5, -0.5) + vec2(0.5, 0.5);\n if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0 || proj.z > 1.0 || proj.z < 0.0) { return 1.0; }\n let bias = max(0.0025 * (1.0 - ndl), 0.0012);\n var s = 0.0;\n for (var dy = -1; dy <= 1; dy = dy + 1) {\n for (var dx = -1; dx <= 1; dx = dx + 1) {\n s = s + textureSampleCompareLevel(shadowMap, shadowSamp, uv + vec2(f32(dx), f32(dy)) * texel, proj.z - bias);\n }\n }\n return s / 9.0;\n}";
3
4
  export declare class GpuShadowMap {
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // ─────────────────────────────────────────────────────────────────────────────
2
3
  // GPU SHADOW MAP (PLATFORM) — a shared directional-sun depth map + PCF sampling helper, so the outdoor
3
4
  // scene casts real shadows (the single biggest look upgrade after lighting; it also makes the sun's
package/dist/gpuSpot.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import type { CubeInstance } from './cube';
2
- export type { CubeInstance } from './cube';
1
+ /// <reference types="@webgpu/types" preserve="true" />
2
+ import type { CubeInstance } from './cube.js';
3
+ export type { CubeInstance } from './cube.js';
3
4
  export interface Spot {
4
5
  px: number;
5
6
  py: number;
package/dist/gpuSpot.js CHANGED
@@ -1,10 +1,11 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // Render IR increment 6 — POINT-LIGHT (spotlight) SHADOWS. Pairs increment 4 (many lights)
2
3
  // with increment 5 (shadows): now the positional lights themselves cast real shadows. Full
3
4
  // omnidirectional cube shadows for 1,600 lights is infeasible (6 faces each), so this is the
4
5
  // tractable, honest form — a handful of shadow-casting SPOTLIGHTS, each with its own 2D shadow
5
6
  // map (a perspective light view) packed into a depth-2d-ARRAY. Same PCF-comparison machinery
6
7
  // as the sun, extended to a positional light with a cone + distance falloff, times L lights.
7
- import { CUBE } from './cube';
8
+ import { CUBE } from './cube.js';
8
9
  export const NUM_SPOTS = 6;
9
10
  const SHADOW_SIZE = 1536;
10
11
  const COMMON = /* wgsl */ `
package/dist/gpuSsao.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export declare class GpuSSAO {
2
3
  private device;
3
4
  private pipe;
package/dist/gpuSsao.js CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // SCREEN-SPACE CONTACT AO — the missing cue that makes voxel terrain read as 3D. Fixed directional fill shades a
2
3
  // face by its ORIENTATION, but a large flat ground plane has one normal everywhere, so it still looks flat. What
3
4
  // the eye actually uses to read shape is the DARK where surfaces meet: the base of a step, the inside corner of a
package/dist/gpuTaa.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import type { CubeInstance } from './cube';
2
- export type { CubeInstance } from './cube';
1
+ /// <reference types="@webgpu/types" preserve="true" />
2
+ import type { CubeInstance } from './cube.js';
3
+ export type { CubeInstance } from './cube.js';
3
4
  export declare class GpuTaaRenderer {
4
5
  private device;
5
6
  private w;
package/dist/gpuTaa.js CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // Render IR increment 7 — TEMPORAL ANTI-ALIASING (TAA). The last of GAME.md §3.6's named
2
3
  // "biggest look gaps", and the proper fix for the residual shadow/edge shimmer of a moving
3
4
  // camera. The engine complexity here is the temporal pipeline, not the shading:
@@ -10,7 +11,7 @@
10
11
  // Reuses the cube geometry from gpuShadow. Sun-lit (no shadow map here) to keep the module
11
12
  // focused on the temporal machinery. `?taa=0` on the page disables jitter + accumulation so the
12
13
  // raw aliased image is visible for comparison.
13
- import { CUBE } from './cube';
14
+ import { CUBE } from './cube.js';
14
15
  const COLOR_FMT = 'rgba16float';
15
16
  const MOTION_FMT = 'rg16float';
16
17
  const SCENE_WGSL = /* wgsl */ `
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  /** Halton(2,3) sub-pixel jitter for frame `i`, in CLIP space. Multiply into the projection. */
2
3
  export declare function haltonJitter(i: number, w: number, h: number, samples?: number): [number, number];
3
4
  export declare class GpuTaaResolve {
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // PLATFORM PASS. Temporal anti-aliasing as a POST PASS over an existing colour+depth pair, so any
2
3
  // renderer in this package can get TAA without becoming a TAA renderer.
3
4
  //
@@ -1,4 +1,5 @@
1
- import { type GpuShadowMap } from './gpuShadowMap';
1
+ /// <reference types="@webgpu/types" preserve="true" />
2
+ import { type GpuShadowMap } from './gpuShadowMap.js';
2
3
  export declare class GpuTerrainRenderer {
3
4
  private device;
4
5
  private terrainPipe;
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // ─────────────────────────────────────────────────────────────────────────────
2
3
  // GPU TERRAIN — a smooth lit triangle-mesh renderer for the world surface (PLATFORM), replacing the
3
4
  // boxy instanced-cube look. Draws an indexed mesh (per-vertex position / normal / colour) with a sun
@@ -5,7 +6,7 @@
5
6
  // its depth into the shared sun shadow map) and RECEIVES sun shadows (PCF sample in the fragment), so
6
7
  // hills and props darken the ground they occlude — which also makes the sun's direction legible.
7
8
  // ─────────────────────────────────────────────────────────────────────────────
8
- import { SHADOW_WGSL } from './gpuShadowMap';
9
+ import { SHADOW_WGSL } from './gpuShadowMap.js';
9
10
  const TERRAIN =
10
11
  /* wgsl */ `
11
12
  struct U { mvp: mat4x4<f32>, sun: vec4<f32>, sunCol: vec4<f32>, amb: vec4<f32>, cam: vec4<f32>, fog: vec4<f32>, lightVP: mat4x4<f32>, shadowP: vec4<f32> };
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  export interface Instance {
2
3
  x: number;
3
4
  y: number;
package/dist/gpuTiled.js CHANGED
@@ -1,11 +1,4 @@
1
- // ─────────────────────────────────────────────────────────────────────────────
2
- // Tiled (forward+) light culling — scales the many-dynamic-lights renderer from
3
- // hundreds to THOUSANDS of lights. A COMPUTE pass bins each light into the screen
4
- // tiles its projected sphere overlaps; the fragment shader then shades only its
5
- // tile's lights → O(lights-per-tile) instead of O(all-lights). Same story as the
6
- // instance brute→grid cull, applied to lights. Builds on the GPU-driven lit backend
7
- // (shared/gpuLit). See design/moonshot-open-world.md §5 (phase 4), GAME.md §3.6.
8
- // ─────────────────────────────────────────────────────────────────────────────
1
+ /// <reference types="@webgpu/types" preserve="true" />
9
2
  const INSTANCE_F32 = 8, ARG_U32 = 4, LIGHT_F32 = 8, CAM_F32 = 72;
10
3
  export const TILE = 24, MAX_PER_TILE = 256;
11
4
  const WGSL = /* wgsl */ `
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  /** Milliseconds per labelled span, plus the whole bracketed region as `total`. */
2
3
  export type GpuSpans = Record<string, number>;
3
4
  export declare class GpuTimer {
package/dist/gpuTimer.js CHANGED
@@ -1,32 +1,4 @@
1
- // PLATFORM PASS-TIMER. Real GPU time per render pass, via `timestamp-query`.
2
- //
3
- // Why marks between passes rather than `timestampWrites` on the pass descriptor: every renderer in
4
- // this package (GpuShadowRenderer, GpuSSAO, GpuPropsRenderer, …) opens its own `beginRenderPass`
5
- // inside `frame()`. Timing via the pass descriptor would mean threading a query set through every
6
- // one of those private call sites. `encoder.writeTimestamp` brackets spans on the ENCODER instead,
7
- // so a caller can time existing renderers without any of them changing:
8
- //
9
- // timer.begin(enc);
10
- // skyR.frame(enc, …); timer.mark(enc, 'sky');
11
- // renderer.frame(enc, …); timer.mark(enc, 'cubes');
12
- // ssaoR.frame(enc, …); timer.mark(enc, 'ssao');
13
- // timer.end(enc);
14
- // device.queue.submit([enc.finish()]);
15
- // timer.poll(); // non-blocking; results land a few frames later
16
- //
17
- // MEASURED on the Electron WebGPU host, timing two 512² passes whose fragment loops differ 5000×:
18
- // `timestampWrites` reported 0.072 / 79.19 ms and `encoder.writeTimestamp` 0.137 / 70.32 ms. Both
19
- // attribute correctly, so the encoder path was chosen purely because it needs no renderer changes.
20
- //
21
- // THE TRAP, worth knowing before trusting any number this produces: a render pass whose result is
22
- // never consumed can be dropped by the driver, and then its time lands in a NEIGHBOURING span. An
23
- // early version of the oracle drew two passes into one texture with `loadOp: 'clear'` and never
24
- // read it; the first pass was dead work, got elided, and the timer duly reported the heavy pass at
25
- // 0.01 ms. The timer was right and the scene was a lie. If a span looks impossibly cheap, check
26
- // that something downstream actually reads what the pass wrote.
27
- //
28
- // Unsupported devices degrade quietly: `supported` is false, marks are no-ops, and `spans()` stays
29
- // empty so callers fall back to wall-clock frame time.
1
+ /// <reference types="@webgpu/types" preserve="true" />
30
2
  const MAX_MARKS = 32; // query-set slots: 1 begin + up to 31 marks
31
3
  const RING = 3; // readback buffers in flight — enough to never stall a 60fps loop
32
4
  export class GpuTimer {
@@ -1,4 +1,5 @@
1
- import type { CubeInstance } from './cube';
1
+ /// <reference types="@webgpu/types" preserve="true" />
2
+ import type { CubeInstance } from './cube.js';
2
3
  /** A dynamic instance that also knows where it was last frame (for its motion vector). */
3
4
  export interface WorldInstance extends CubeInstance {
4
5
  px: number;
package/dist/gpuWorld.js CHANGED
@@ -1,3 +1,4 @@
1
+ /// <reference types="@webgpu/types" preserve="true" />
1
2
  // The integrated scene renderer: sun SHADOW MAPPING + TAA in one pipeline, driven by the
2
3
  // deterministic ECS sim. The new hard part vs. the isolated /gputaa demo is PER-OBJECT MOTION
3
4
  // VECTORS: the sim moves crates/character/projectiles every frame, so camera-only reprojection
@@ -5,7 +6,7 @@
5
6
  // pass emits a true motion vector (camera motion + object motion), and TAA reprojects history
6
7
  // through it. Passes: (1) shadow depth from the sun, (2) shadow-lit scene → MRT color+motion
7
8
  // (jittered), (3) TAA resolve → screen + ping-ponged history.
8
- import { CUBE } from './cube';
9
+ import { CUBE } from './cube.js';
9
10
  const COLOR_FMT = 'rgba16float';
10
11
  const MOTION_FMT = 'rg16float';
11
12
  const SHADOW_SIZE = 2048;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.42",
3
+ "version": "0.15.44",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -25,10 +25,12 @@
25
25
  "test:flight-browser": "playwright test -c playwright.flight.config.ts",
26
26
  "test:flight-perf": "playwright test -c playwright.flight.config.ts --grep 'CPU and retained-memory'",
27
27
  "test:types": "tsc -p tsconfig.test.json",
28
+ "test:package-types": "node tools/packageTypesSmoke.mjs",
28
29
  "pretty": "prettier --write .",
29
30
  "prepublishOnly": "pnpm run pretty && ugly-app lint && tsc -p tsconfig.json && mkdir -p dist/assets/basis && cp src/assets/basis/basis_transcoder.js src/assets/basis/basis_transcoder.bin dist/assets/basis/"
30
31
  },
31
32
  "dependencies": {
33
+ "@webgpu/types": "^0.1.40",
32
34
  "meshoptimizer": "^1.2.0"
33
35
  },
34
36
  "peerDependencies": {
@@ -38,7 +40,6 @@
38
40
  "@playwright/test": "^1.62.1",
39
41
  "@types/node": "^22.20.1",
40
42
  "@types/react": "^19.0.0",
41
- "@webgpu/types": "^0.1.40",
42
43
  "prettier": "^3.9.5",
43
44
  "typescript": "^5.6.0",
44
45
  "ugly-app": "^0.1.841",