ugly-game 0.15.41 → 0.15.43

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,4 +1,5 @@
1
1
  import type { CrowdBucket, GpuCrowdRenderer } from './assets/gpuCrowd.js';
2
+ import type { GpuSkinRenderer, SkinCreature } from './assets/gpuSkin.js';
2
3
  export declare const GPU_CHARACTER_FACE_CHANNELS = 47;
3
4
  export declare const GPU_CHARACTER_VISIBLE = 1;
4
5
  export interface GpuCharacterTiers {
@@ -67,8 +68,52 @@ export interface GpuCharactersBatch {
67
68
  }
68
69
  export interface GpuCharactersBackend {
69
70
  submit(batch: GpuCharactersBatch): void;
71
+ /** Present when the backend applies an explicit per-frame render budget. */
72
+ characterBudgetReport?(): GpuCharacterBudgetReport;
70
73
  dispose?(): void;
71
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
+ }
72
117
  /**
73
118
  * The crowd renderer allocates vertex-pool offsets, while {@link GpuCharacters} allocates stable
74
119
  * actor ordinals. A binding is the explicit bridge between those two address spaces.
@@ -125,8 +170,101 @@ export interface GpuCrowdCharacterCompositionFrame {
125
170
  bounds: Float32Array;
126
171
  }
127
172
  export interface GpuCrowdCharacterCompositionBackend {
128
- submitComposition(frame: GpuCrowdCharacterCompositionFrame): void;
173
+ submitComposition(frame: GpuCrowdCharacterCompositionFrame, resources: GpuCrowdCharacterCompositionResources): void;
174
+ }
175
+ /** Shared skin data referenced by `paletteRows`; passed by reference, never copied. */
176
+ export interface GpuCrowdCharacterCompositionResources {
177
+ palettes: Float32Array;
178
+ boneCount: number;
179
+ }
180
+ /**
181
+ * One directly drawable instanced part batch. Rows are grouped by kind, authored asset and LOD;
182
+ * models and palettes are packed instance-major for `GpuSkin` or an equivalent caller renderer.
183
+ * `bindingSlots` remain available to a pooled renderer and are deliberately opaque here.
184
+ */
185
+ export interface GpuCrowdCharacterPartDrawBatch {
186
+ kind: GpuCharacterPartKind;
187
+ asset: number;
188
+ lod: number;
189
+ count: number;
190
+ actorSlots: Uint32Array;
191
+ bindingSlots: Uint32Array;
192
+ socketIndices: Int32Array;
193
+ models: Float32Array;
194
+ palettes: Float32Array;
195
+ bounds: Float32Array;
196
+ }
197
+ /** The game owns the actual render pass; this receives executable, asset-grouped draw inputs. */
198
+ export interface GpuCrowdCharacterPartDrawBackend {
199
+ submitPartDraws(batches: readonly GpuCrowdCharacterPartDrawBatch[]): void;
129
200
  }
201
+ export interface GpuCrowdCharacterPartDispatcherOptions {
202
+ backend: GpuCrowdCharacterPartDrawBackend;
203
+ /** Body and face already use `GpuCrowdRenderer`; include them only for a replacement renderer. */
204
+ includeBodyAndFace?: boolean;
205
+ }
206
+ /**
207
+ * Converts the unified composition table into concrete instanced draw submissions. This is the
208
+ * generic boundary the engine can provide without inventing a mesh format: the caller maps each
209
+ * authored `asset` to its own GPU renderer and encodes those prepared batches in its scene pass.
210
+ */
211
+ export declare class GpuCrowdCharacterPartDispatcher implements GpuCrowdCharacterCompositionBackend {
212
+ private readonly backend;
213
+ private readonly includeBodyAndFace;
214
+ constructor(options: GpuCrowdCharacterPartDispatcherOptions);
215
+ submitComposition(frame: GpuCrowdCharacterCompositionFrame, resources: GpuCrowdCharacterCompositionResources): void;
216
+ }
217
+ export declare function createGpuCrowdCharacterPartDispatcher(options: GpuCrowdCharacterPartDispatcherOptions): GpuCrowdCharacterPartDispatcher;
218
+ /** Immutable mesh/material fields for one authored part; pose and placement come from the batch. */
219
+ export type GpuSkinCharacterPartAsset = Omit<SkinCreature, 'palette' | 'model' | 'instances'>;
220
+ export interface GpuSkinCharacterPartDrawBackendOptions {
221
+ renderer: Pick<GpuSkinRenderer, 'setCreatures'>;
222
+ resolveAsset: (kind: GpuCharacterPartKind, asset: number, lod: number) => GpuSkinCharacterPartAsset | null;
223
+ }
224
+ /**
225
+ * Executable adapter for the engine's existing skinned-mesh renderer. After submission, the game's
226
+ * normal `GpuSkinRenderer.frame(...)` call deforms and draws every grouped part. Asset GPU resources
227
+ * remain caller-owned; a body-conformed garment must resolve to its conformed mesh (or use a pooled
228
+ * backend) because this adapter intentionally shares one immutable mesh per asset/LOD batch.
229
+ */
230
+ export declare class GpuSkinCharacterPartDrawBackend implements GpuCrowdCharacterPartDrawBackend {
231
+ private readonly renderer;
232
+ private readonly resolveAsset;
233
+ constructor(options: GpuSkinCharacterPartDrawBackendOptions);
234
+ submitPartDraws(batches: readonly GpuCrowdCharacterPartDrawBatch[]): void;
235
+ }
236
+ export declare function createGpuSkinCharacterPartDrawBackend(options: GpuSkinCharacterPartDrawBackendOptions): GpuSkinCharacterPartDrawBackend;
237
+ export interface GpuCrowdCharacterPartAllocation {
238
+ actorSlot: number;
239
+ revision: number;
240
+ kind: GpuCharacterPartKind;
241
+ asset: number;
242
+ /** Index within the corresponding hair/garment/attachment list. */
243
+ partIndex: number;
244
+ lod: number;
245
+ slot: number;
246
+ }
247
+ export interface GpuCrowdCharacterPartBindingLifecycleOptions {
248
+ /** Resolve the existing body/face crowd allocations. Their format and ownership stay unchanged. */
249
+ resolveBase: (identity: Readonly<GpuCharacterIdentityUpdate>) => Omit<GpuCrowdCharacterBinding, 'hair' | 'garments' | 'socketAttachments'>;
250
+ releaseBase?: (binding: GpuCrowdCharacterBinding, identity: Readonly<GpuCharacterIdentityUpdate>) => void;
251
+ /** Number of authored LODs for a part asset. */
252
+ lodCount: (kind: GpuCharacterPartKind, asset: number) => number;
253
+ /** Allocate one caller-owned opaque slot. Null explicitly marks an unsupported LOD. */
254
+ allocate: (request: Omit<GpuCrowdCharacterPartAllocation, 'slot'>) => number | null;
255
+ release: (allocation: GpuCrowdCharacterPartAllocation) => void;
256
+ }
257
+ export interface GpuCrowdCharacterPartBindingLifecycle {
258
+ resolveBinding: GpuCrowdCharactersBackendOptions['resolveBinding'];
259
+ releaseBinding: NonNullable<GpuCrowdCharactersBackendOptions['releaseBinding']>;
260
+ }
261
+ /**
262
+ * Cold-path allocator for hair, garments and socket attachments. It gives every actor/part/LOD a
263
+ * retained caller-owned slot, rolls partial failures back, and releases exactly those slots on
264
+ * identity replacement, removal or backend disposal. Body and face remain delegated to the
265
+ * existing crowd allocator so current games do not have to change their pool layout.
266
+ */
267
+ export declare function createGpuCrowdCharacterPartBindingLifecycle(options: GpuCrowdCharacterPartBindingLifecycleOptions): GpuCrowdCharacterPartBindingLifecycle;
130
268
  /** The narrow renderer surface used by the concrete crowd backend (and by its CPU-only tests). */
131
269
  export type GpuCrowdCharacterRenderer = Pick<GpuCrowdRenderer, 'morph' | 'enableFaceRig' | 'disableFaceRig' | 'setFaceWeights' | 'faceFrame' | 'setInstances' | 'setPalettes'>;
132
270
  export interface GpuCrowdCharactersBackendOptions {
@@ -142,6 +280,8 @@ export interface GpuCrowdCharactersBackendOptions {
142
280
  socketCount?: number;
143
281
  /** Explicit handoff to caller-owned hair, garment and attachment render passes. */
144
282
  composition?: GpuCrowdCharacterCompositionBackend;
283
+ /** Optional deterministic pressure policy. No budget means every requested visible part renders. */
284
+ budget?: GpuCharacterBudgetPolicy;
145
285
  }
146
286
  export interface GpuCrowdCharactersPreparedFrame {
147
287
  renderedCount: number;
@@ -151,6 +291,7 @@ export interface GpuCrowdCharactersPreparedFrame {
151
291
  palettes: Float32Array;
152
292
  buckets: readonly CrowdBucket[];
153
293
  composition: GpuCrowdCharacterCompositionFrame;
294
+ budget: GpuCharacterBudgetReport;
154
295
  }
155
296
  export interface GpuCharactersReport {
156
297
  capacity: number;
@@ -162,6 +303,8 @@ export interface GpuCharactersReport {
162
303
  removals: number;
163
304
  /** Counts by tier for visible actors in the most recently submitted hot frame. */
164
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;
165
308
  }
166
309
  /** Validate a hot frame without allocating or converting it. */
167
310
  export declare function validateGpuCharacterFrame(frame: GpuCharacterFrame, options: Omit<Required<GpuCharactersOptions>, 'socketCount'> & Pick<GpuCharactersOptions, 'socketCount'>): void;
@@ -202,6 +345,7 @@ export declare class GpuCrowdCharactersBackend implements GpuCharactersBackend {
202
345
  private readonly faceChannels;
203
346
  private readonly socketCount;
204
347
  private readonly maxRiggedFaceTier;
348
+ private readonly budgetPolicy;
205
349
  private readonly compositionBackend;
206
350
  private readonly resolveBinding;
207
351
  private readonly releaseBinding;
@@ -210,6 +354,7 @@ export declare class GpuCrowdCharactersBackend implements GpuCharactersBackend {
210
354
  constructor(options: GpuCrowdCharactersBackendOptions);
211
355
  submit(batch: GpuCharactersBatch): void;
212
356
  lastPreparedFrame(): GpuCrowdCharactersPreparedFrame;
357
+ characterBudgetReport(): GpuCharacterBudgetReport;
213
358
  dispose(): void;
214
359
  private applyRemovals;
215
360
  private applyIdentityUpdates;
package/dist/character.js CHANGED
@@ -49,6 +49,217 @@ export const GPU_CHARACTER_PART_KIND = {
49
49
  garment: 3,
50
50
  socketAttachment: 4,
51
51
  };
52
+ /**
53
+ * Converts the unified composition table into concrete instanced draw submissions. This is the
54
+ * generic boundary the engine can provide without inventing a mesh format: the caller maps each
55
+ * authored `asset` to its own GPU renderer and encodes those prepared batches in its scene pass.
56
+ */
57
+ export class GpuCrowdCharacterPartDispatcher {
58
+ backend;
59
+ includeBodyAndFace;
60
+ constructor(options) {
61
+ this.backend = options.backend;
62
+ this.includeBodyAndFace = options.includeBodyAndFace ?? false;
63
+ }
64
+ submitComposition(frame, resources) {
65
+ const paletteStride = positiveInt(resources.boneCount, 'boneCount') * 16;
66
+ if (resources.palettes.length % paletteStride !== 0)
67
+ throw new Error('composition palettes do not contain whole rows');
68
+ const groups = new Map();
69
+ for (let row = 0; row < frame.count; row++) {
70
+ const kind = frame.kinds[row];
71
+ if (!this.includeBodyAndFace &&
72
+ (kind === GPU_CHARACTER_PART_KIND.body ||
73
+ kind === GPU_CHARACTER_PART_KIND.face))
74
+ continue;
75
+ const paletteRow = frame.paletteRows[row];
76
+ if ((paletteRow + 1) * paletteStride > resources.palettes.length)
77
+ throw new Error(`composition row ${row} references unavailable palette ${paletteRow}`);
78
+ const key = `${kind}:${frame.assets[row]}:${frame.lods[row]}`;
79
+ const rows = groups.get(key);
80
+ if (rows)
81
+ rows.push(row);
82
+ else
83
+ groups.set(key, [row]);
84
+ }
85
+ const batches = [];
86
+ for (const rows of groups.values()) {
87
+ const first = rows[0];
88
+ const count = rows.length;
89
+ const actorSlots = new Uint32Array(count);
90
+ const bindingSlots = new Uint32Array(count);
91
+ const socketIndices = new Int32Array(count);
92
+ const models = new Float32Array(count * 16);
93
+ const palettes = new Float32Array(count * paletteStride);
94
+ const bounds = new Float32Array(count * 4);
95
+ rows.forEach((row, instance) => {
96
+ actorSlots[instance] = frame.actorSlots[row];
97
+ bindingSlots[instance] = frame.bindingSlots[row];
98
+ socketIndices[instance] = frame.socketIndices[row];
99
+ models.set(frame.transforms.subarray(row * 16, row * 16 + 16), instance * 16);
100
+ const paletteRow = frame.paletteRows[row];
101
+ palettes.set(resources.palettes.subarray(paletteRow * paletteStride, (paletteRow + 1) * paletteStride), instance * paletteStride);
102
+ bounds.set(frame.bounds.subarray(row * 4, row * 4 + 4), instance * 4);
103
+ });
104
+ batches.push({
105
+ kind: frame.kinds[first],
106
+ asset: frame.assets[first],
107
+ lod: frame.lods[first],
108
+ count,
109
+ actorSlots,
110
+ bindingSlots,
111
+ socketIndices,
112
+ models,
113
+ palettes,
114
+ bounds,
115
+ });
116
+ }
117
+ this.backend.submitPartDraws(batches);
118
+ }
119
+ }
120
+ export function createGpuCrowdCharacterPartDispatcher(options) {
121
+ return new GpuCrowdCharacterPartDispatcher(options);
122
+ }
123
+ /**
124
+ * Executable adapter for the engine's existing skinned-mesh renderer. After submission, the game's
125
+ * normal `GpuSkinRenderer.frame(...)` call deforms and draws every grouped part. Asset GPU resources
126
+ * remain caller-owned; a body-conformed garment must resolve to its conformed mesh (or use a pooled
127
+ * backend) because this adapter intentionally shares one immutable mesh per asset/LOD batch.
128
+ */
129
+ export class GpuSkinCharacterPartDrawBackend {
130
+ renderer;
131
+ resolveAsset;
132
+ constructor(options) {
133
+ this.renderer = options.renderer;
134
+ this.resolveAsset = options.resolveAsset;
135
+ }
136
+ submitPartDraws(batches) {
137
+ this.renderer.setCreatures(batches.map((batch) => {
138
+ positiveInt(batch.count, 'part draw count');
139
+ if (batch.models.length !== batch.count * 16)
140
+ throw new Error('part draw models do not match count');
141
+ if (batch.palettes.length === 0 ||
142
+ batch.palettes.length % (batch.count * 16) !== 0)
143
+ throw new Error('part draw palettes do not contain whole instance rows');
144
+ const asset = this.resolveAsset(batch.kind, batch.asset, batch.lod);
145
+ if (!asset)
146
+ throw new Error(`no GpuSkin asset for character part ${batch.kind}:${batch.asset}:LOD${batch.lod}`);
147
+ return {
148
+ ...asset,
149
+ // GpuSkin's legacy required fields remain valid; `instances` is the active path.
150
+ palette: batch.palettes.subarray(0, batch.palettes.length / batch.count),
151
+ model: batch.models.subarray(0, 16),
152
+ instances: {
153
+ count: batch.count,
154
+ palettes: batch.palettes,
155
+ models: batch.models,
156
+ },
157
+ };
158
+ }));
159
+ }
160
+ }
161
+ export function createGpuSkinCharacterPartDrawBackend(options) {
162
+ return new GpuSkinCharacterPartDrawBackend(options);
163
+ }
164
+ /**
165
+ * Cold-path allocator for hair, garments and socket attachments. It gives every actor/part/LOD a
166
+ * retained caller-owned slot, rolls partial failures back, and releases exactly those slots on
167
+ * identity replacement, removal or backend disposal. Body and face remain delegated to the
168
+ * existing crowd allocator so current games do not have to change their pool layout.
169
+ */
170
+ export function createGpuCrowdCharacterPartBindingLifecycle(options) {
171
+ const allocationFor = (identity, kind, asset, partIndex) => {
172
+ if (asset < 0)
173
+ return null;
174
+ const count = positiveInt(options.lodCount(kind, asset), 'part lodCount');
175
+ const lodSlots = [];
176
+ try {
177
+ for (let lod = 0; lod < count; lod++) {
178
+ const slot = options.allocate({
179
+ actorSlot: identity.slot,
180
+ revision: identity.revision,
181
+ kind,
182
+ asset,
183
+ partIndex,
184
+ lod,
185
+ });
186
+ if (slot !== null)
187
+ nonNegativeInt(slot, 'part allocation slot');
188
+ lodSlots.push(slot);
189
+ }
190
+ }
191
+ catch (error) {
192
+ lodSlots.forEach((slot, lod) => {
193
+ if (slot === null)
194
+ return;
195
+ options.release({
196
+ actorSlot: identity.slot,
197
+ revision: identity.revision,
198
+ kind,
199
+ asset,
200
+ partIndex,
201
+ lod,
202
+ slot,
203
+ });
204
+ });
205
+ throw error;
206
+ }
207
+ return { asset, lodSlots };
208
+ };
209
+ const releaseParts = (binding, identity) => {
210
+ const releaseOne = (part, kind, partIndex) => {
211
+ if (!part)
212
+ return;
213
+ part.lodSlots.forEach((slot, lod) => {
214
+ if (slot === null)
215
+ return;
216
+ options.release({
217
+ actorSlot: identity.slot,
218
+ revision: identity.revision,
219
+ kind,
220
+ asset: part.asset,
221
+ partIndex,
222
+ lod,
223
+ slot,
224
+ });
225
+ });
226
+ };
227
+ releaseOne(binding.hair, GPU_CHARACTER_PART_KIND.hair, 0);
228
+ binding.garments?.forEach((part, index) => {
229
+ releaseOne(part, GPU_CHARACTER_PART_KIND.garment, index);
230
+ });
231
+ binding.socketAttachments?.forEach((part, index) => {
232
+ releaseOne(part, GPU_CHARACTER_PART_KIND.socketAttachment, index);
233
+ });
234
+ };
235
+ const resolveBinding = (identity) => {
236
+ const base = options.resolveBase(identity);
237
+ const binding = {
238
+ ...base,
239
+ garments: [],
240
+ socketAttachments: [],
241
+ };
242
+ try {
243
+ binding.hair =
244
+ allocationFor(identity, GPU_CHARACTER_PART_KIND.hair, identity.hairAsset, 0) ?? undefined;
245
+ binding.garments = identity.garmentAssets.map((asset, index) => allocationFor(identity, GPU_CHARACTER_PART_KIND.garment, asset, index));
246
+ binding.socketAttachments = (identity.socketAttachments ?? []).map((attachment, index) => allocationFor(identity, GPU_CHARACTER_PART_KIND.socketAttachment, attachment.asset, index));
247
+ return binding;
248
+ }
249
+ catch (error) {
250
+ releaseParts(binding, identity);
251
+ options.releaseBase?.(binding, identity);
252
+ throw error;
253
+ }
254
+ };
255
+ return {
256
+ resolveBinding,
257
+ releaseBinding: (binding, identity) => {
258
+ releaseParts(binding, identity);
259
+ options.releaseBase?.(binding, identity);
260
+ },
261
+ };
262
+ }
52
263
  function positiveInt(value, name) {
53
264
  if (!Number.isInteger(value) || value <= 0)
54
265
  throw new Error(`${name} must be a positive integer`);
@@ -244,6 +455,7 @@ export class GpuCharacters {
244
455
  coldUpdates: this.coldUpdates,
245
456
  removals: this.removals,
246
457
  lastTierCounts: cloneTierCounts(this.lastTierCounts),
458
+ budget: this.backend?.characterBudgetReport?.() ?? null,
247
459
  };
248
460
  }
249
461
  dispose() {
@@ -328,6 +540,229 @@ function emptyComposition() {
328
540
  bounds: new Float32Array(0),
329
541
  };
330
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
+ }
331
766
  function validatePartBinding(binding, asset, label) {
332
767
  if (asset < 0) {
333
768
  if (binding)
@@ -355,6 +790,7 @@ export class GpuCrowdCharactersBackend {
355
790
  faceChannels;
356
791
  socketCount;
357
792
  maxRiggedFaceTier;
793
+ budgetPolicy;
358
794
  compositionBackend;
359
795
  resolveBinding;
360
796
  releaseBinding;
@@ -366,6 +802,7 @@ export class GpuCrowdCharactersBackend {
366
802
  palettes: new Float32Array(0),
367
803
  buckets: [],
368
804
  composition: emptyComposition(),
805
+ budget: planCharacterBudget([], undefined).report,
369
806
  };
370
807
  constructor(options) {
371
808
  this.renderer = options.renderer;
@@ -374,6 +811,7 @@ export class GpuCrowdCharactersBackend {
374
811
  if (this.faceChannels !== GPU_CHARACTER_FACE_CHANNELS)
375
812
  throw new Error(`GpuCrowdRenderer requires ${GPU_CHARACTER_FACE_CHANNELS} face channels`);
376
813
  this.socketCount = nonNegativeInt(options.socketCount ?? 0, 'socketCount');
814
+ this.budgetPolicy = options.budget;
377
815
  this.compositionBackend = options.composition;
378
816
  this.resolveBinding = options.resolveBinding;
379
817
  this.releaseBinding = options.releaseBinding;
@@ -389,7 +827,7 @@ export class GpuCrowdCharactersBackend {
389
827
  throw new Error(`socketTransforms length ${socketValues} does not match backend requirement ${expectedSocketValues}`);
390
828
  this.applyRemovals(batch.removedSlots);
391
829
  this.applyIdentityUpdates(batch.identityUpdates);
392
- const entries = [];
830
+ const requestedEntries = [];
393
831
  for (let i = 0; i < batch.frame.count; i++) {
394
832
  const tiers = unpackGpuCharacterFlags(batch.frame.flags[i]);
395
833
  if (!tiers.visible)
@@ -400,7 +838,7 @@ export class GpuCrowdCharactersBackend {
400
838
  throw new Error(`crowd backend has no identity for actor slot ${actorSlot}`);
401
839
  // Stable sorting below preserves actor order within a LOD, including blend ordering chosen
402
840
  // by the caller. That makes buckets contiguous without changing same-rung draw semantics.
403
- entries.push({
841
+ requestedEntries.push({
404
842
  actorSlot,
405
843
  sourceIndex: i,
406
844
  lod: tiers.body,
@@ -408,20 +846,16 @@ export class GpuCrowdCharactersBackend {
408
846
  state,
409
847
  });
410
848
  }
849
+ const budget = planCharacterBudget(requestedEntries, this.budgetPolicy, this.maxRiggedFaceTier);
850
+ const entries = budget.entries;
411
851
  entries.sort((a, b) => a.lod - b.lod);
412
852
  const records = new Float32Array(entries.length * CROWD_RECORD_FLOATS);
413
853
  const palettes = new Float32Array(entries.length * this.boneCount * 16);
414
854
  const actorSlots = new Uint32Array(entries.length);
415
855
  const buckets = [];
416
856
  const paletteStride = this.boneCount * 16;
417
- const compositionCount = entries.reduce((count, entry) => {
418
- const identity = entry.state.identity;
419
- return (count +
420
- 2 +
421
- (identity.hairAsset < 0 ? 0 : 1) +
422
- identity.garmentAssets.filter((asset) => asset >= 0).length +
423
- (identity.socketAttachments ?? []).filter((attachment) => attachment.asset >= 0).length);
424
- }, 0);
857
+ const compositionCount = entries.reduce((count, entry) => count +
858
+ budgetParts(entry).filter((part) => !budget.droppedPartKeys.has(part.key)).length, 0);
425
859
  const composition = {
426
860
  count: compositionCount,
427
861
  actorSlots: new Uint32Array(compositionCount),
@@ -445,9 +879,8 @@ export class GpuCrowdCharactersBackend {
445
879
  state.morphedLod = lod;
446
880
  }
447
881
  const wantsFace = tiers.face <= this.maxRiggedFaceTier;
448
- const facePoolSlot = wantsFace
449
- ? bindingFaceSlot(state.binding, lod)
450
- : null;
882
+ const composedFacePoolSlot = bindingFaceSlot(state.binding, lod);
883
+ const facePoolSlot = wantsFace ? composedFacePoolSlot : null;
451
884
  if (wantsFace && facePoolSlot === null)
452
885
  throw new Error(`character binding has no face pool slot for rigged actor ${actorSlot} at LOD ${lod}`);
453
886
  if (state.rigSource !== null && state.rigSource !== sourcePoolSlot) {
@@ -487,21 +920,24 @@ export class GpuCrowdCharactersBackend {
487
920
  const bodyAsset = state.identity.bodyAsset ?? -1;
488
921
  const faceAsset = state.identity.faceAsset ?? bodyAsset;
489
922
  writePart(GPU_CHARACTER_PART_KIND.body, bodyAsset, sourcePoolSlot, lod, tiers.body, transform);
490
- writePart(GPU_CHARACTER_PART_KIND.face, faceAsset, facePoolSlot ?? sourcePoolSlot, lod, tiers.face, transform);
491
- 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`)) {
492
926
  const binding = state.binding.hair;
493
927
  if (!binding)
494
928
  throw new Error('hair binding is unavailable');
495
929
  writePart(GPU_CHARACTER_PART_KIND.hair, state.identity.hairAsset, partBindingSlot(binding, tiers.hair, 'hair'), tiers.hair, tiers.hair, transform);
496
930
  }
497
931
  for (const [garmentIndex, asset,] of state.identity.garmentAssets.entries()) {
498
- if (asset < 0)
932
+ if (asset < 0 ||
933
+ budget.droppedPartKeys.has(`${actorSlot}:garment:${garmentIndex}`))
499
934
  continue;
500
935
  const binding = indexedPartBinding(state.binding.garments, garmentIndex, `garment ${garmentIndex}`);
501
936
  writePart(GPU_CHARACTER_PART_KIND.garment, asset, partBindingSlot(binding, tiers.cloth, `garment ${garmentIndex}`), tiers.cloth, tiers.cloth, transform);
502
937
  }
503
938
  for (const [attachmentIndex, attachment] of (state.identity.socketAttachments ?? []).entries()) {
504
- if (attachment.asset < 0)
939
+ if (attachment.asset < 0 ||
940
+ budget.droppedPartKeys.has(`${actorSlot}:attachment:${attachmentIndex}`))
505
941
  continue;
506
942
  const socketTransforms = batch.frame.socketTransforms;
507
943
  if (!socketTransforms)
@@ -529,12 +965,19 @@ export class GpuCrowdCharactersBackend {
529
965
  palettes,
530
966
  buckets: buckets.map((bucket) => ({ ...bucket })),
531
967
  composition,
968
+ budget: cloneBudgetReport(budget.report),
532
969
  };
533
- this.compositionBackend?.submitComposition(composition);
970
+ this.compositionBackend?.submitComposition(composition, {
971
+ palettes,
972
+ boneCount: this.boneCount,
973
+ });
534
974
  }
535
975
  lastPreparedFrame() {
536
976
  return this.prepared;
537
977
  }
978
+ characterBudgetReport() {
979
+ return cloneBudgetReport(this.prepared.budget);
980
+ }
538
981
  dispose() {
539
982
  for (const state of this.states.values())
540
983
  this.releaseState(state);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ugly-game",
3
- "version": "0.15.41",
3
+ "version": "0.15.43",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {