@aardworx/wombat.rendering 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/dist/core/command.d.ts +7 -9
  2. package/dist/core/command.d.ts.map +1 -1
  3. package/dist/core/renderTask.d.ts +64 -1
  4. package/dist/core/renderTask.d.ts.map +1 -1
  5. package/dist/core/renderTask.js +3 -1
  6. package/dist/core/renderTask.js.map +1 -1
  7. package/dist/resources/preparedRenderObject.js +3 -3
  8. package/dist/resources/preparedRenderObject.js.map +1 -1
  9. package/dist/resources/uniformBuffer.d.ts.map +1 -1
  10. package/dist/resources/uniformBuffer.js +17 -0
  11. package/dist/resources/uniformBuffer.js.map +1 -1
  12. package/dist/runtime/derivedUniforms/dispatch.d.ts +105 -0
  13. package/dist/runtime/derivedUniforms/dispatch.d.ts.map +1 -0
  14. package/dist/runtime/derivedUniforms/dispatch.js +355 -0
  15. package/dist/runtime/derivedUniforms/dispatch.js.map +1 -0
  16. package/dist/runtime/derivedUniforms/index.d.ts +6 -0
  17. package/dist/runtime/derivedUniforms/index.d.ts.map +1 -0
  18. package/dist/runtime/derivedUniforms/index.js +26 -0
  19. package/dist/runtime/derivedUniforms/index.js.map +1 -0
  20. package/dist/runtime/derivedUniforms/recipes.d.ts +42 -0
  21. package/dist/runtime/derivedUniforms/recipes.d.ts.map +1 -0
  22. package/dist/runtime/derivedUniforms/recipes.js +134 -0
  23. package/dist/runtime/derivedUniforms/recipes.js.map +1 -0
  24. package/dist/runtime/derivedUniforms/sceneIntegration.d.ts +56 -0
  25. package/dist/runtime/derivedUniforms/sceneIntegration.d.ts.map +1 -0
  26. package/dist/runtime/derivedUniforms/sceneIntegration.js +171 -0
  27. package/dist/runtime/derivedUniforms/sceneIntegration.js.map +1 -0
  28. package/dist/runtime/derivedUniforms/slotId.d.ts +15 -0
  29. package/dist/runtime/derivedUniforms/slotId.d.ts.map +1 -0
  30. package/dist/runtime/derivedUniforms/slotId.js +30 -0
  31. package/dist/runtime/derivedUniforms/slotId.js.map +1 -0
  32. package/dist/runtime/derivedUniforms/slots.d.ts +49 -0
  33. package/dist/runtime/derivedUniforms/slots.d.ts.map +1 -0
  34. package/dist/runtime/derivedUniforms/slots.js +123 -0
  35. package/dist/runtime/derivedUniforms/slots.js.map +1 -0
  36. package/dist/runtime/derivedUniforms/uberKernel.wgsl.d.ts +13 -0
  37. package/dist/runtime/derivedUniforms/uberKernel.wgsl.d.ts.map +1 -0
  38. package/dist/runtime/derivedUniforms/uberKernel.wgsl.js +218 -0
  39. package/dist/runtime/derivedUniforms/uberKernel.wgsl.js.map +1 -0
  40. package/dist/runtime/flattenTree.d.ts +5 -0
  41. package/dist/runtime/flattenTree.d.ts.map +1 -0
  42. package/dist/runtime/flattenTree.js +45 -0
  43. package/dist/runtime/flattenTree.js.map +1 -0
  44. package/dist/runtime/heapAdapter.d.ts +16 -0
  45. package/dist/runtime/heapAdapter.d.ts.map +1 -0
  46. package/dist/runtime/heapAdapter.js +263 -0
  47. package/dist/runtime/heapAdapter.js.map +1 -0
  48. package/dist/runtime/heapEffect.d.ts +235 -0
  49. package/dist/runtime/heapEffect.d.ts.map +1 -0
  50. package/dist/runtime/heapEffect.js +518 -0
  51. package/dist/runtime/heapEffect.js.map +1 -0
  52. package/dist/runtime/heapEffectIR.d.ts +34 -0
  53. package/dist/runtime/heapEffectIR.d.ts.map +1 -0
  54. package/dist/runtime/heapEffectIR.js +1161 -0
  55. package/dist/runtime/heapEffectIR.js.map +1 -0
  56. package/dist/runtime/heapEligibility.d.ts +9 -0
  57. package/dist/runtime/heapEligibility.d.ts.map +1 -0
  58. package/dist/runtime/heapEligibility.js +195 -0
  59. package/dist/runtime/heapEligibility.js.map +1 -0
  60. package/dist/runtime/heapScene.d.ts +240 -31
  61. package/dist/runtime/heapScene.d.ts.map +1 -1
  62. package/dist/runtime/heapScene.js +3334 -265
  63. package/dist/runtime/heapScene.js.map +1 -1
  64. package/dist/runtime/heapShaderFamily.d.ts +132 -0
  65. package/dist/runtime/heapShaderFamily.d.ts.map +1 -0
  66. package/dist/runtime/heapShaderFamily.js +866 -0
  67. package/dist/runtime/heapShaderFamily.js.map +1 -0
  68. package/dist/runtime/hybridScene.d.ts +133 -0
  69. package/dist/runtime/hybridScene.d.ts.map +1 -0
  70. package/dist/runtime/hybridScene.js +159 -0
  71. package/dist/runtime/hybridScene.js.map +1 -0
  72. package/dist/runtime/index.d.ts +8 -0
  73. package/dist/runtime/index.d.ts.map +1 -1
  74. package/dist/runtime/index.js +9 -0
  75. package/dist/runtime/index.js.map +1 -1
  76. package/dist/runtime/renderTask.d.ts +21 -4
  77. package/dist/runtime/renderTask.d.ts.map +1 -1
  78. package/dist/runtime/renderTask.js +127 -32
  79. package/dist/runtime/renderTask.js.map +1 -1
  80. package/dist/runtime/runtime.d.ts +33 -3
  81. package/dist/runtime/runtime.d.ts.map +1 -1
  82. package/dist/runtime/runtime.js +12 -3
  83. package/dist/runtime/runtime.js.map +1 -1
  84. package/dist/runtime/scenePass.d.ts +28 -3
  85. package/dist/runtime/scenePass.d.ts.map +1 -1
  86. package/dist/runtime/scenePass.js +37 -4
  87. package/dist/runtime/scenePass.js.map +1 -1
  88. package/dist/runtime/textureAtlas/atlasMipGutterKernel.d.ts +35 -0
  89. package/dist/runtime/textureAtlas/atlasMipGutterKernel.d.ts.map +1 -0
  90. package/dist/runtime/textureAtlas/atlasMipGutterKernel.js +247 -0
  91. package/dist/runtime/textureAtlas/atlasMipGutterKernel.js.map +1 -0
  92. package/dist/runtime/textureAtlas/atlasPool.d.ts +240 -0
  93. package/dist/runtime/textureAtlas/atlasPool.d.ts.map +1 -0
  94. package/dist/runtime/textureAtlas/atlasPool.js +798 -0
  95. package/dist/runtime/textureAtlas/atlasPool.js.map +1 -0
  96. package/dist/runtime/textureAtlas/bvhTree2d.d.ts +33 -0
  97. package/dist/runtime/textureAtlas/bvhTree2d.d.ts.map +1 -0
  98. package/dist/runtime/textureAtlas/bvhTree2d.js +501 -0
  99. package/dist/runtime/textureAtlas/bvhTree2d.js.map +1 -0
  100. package/dist/runtime/textureAtlas/packer.d.ts +50 -0
  101. package/dist/runtime/textureAtlas/packer.d.ts.map +1 -0
  102. package/dist/runtime/textureAtlas/packer.js +390 -0
  103. package/dist/runtime/textureAtlas/packer.js.map +1 -0
  104. package/dist/window/loop.d.ts +14 -0
  105. package/dist/window/loop.d.ts.map +1 -1
  106. package/dist/window/loop.js +18 -5
  107. package/dist/window/loop.js.map +1 -1
  108. package/package.json +5 -4
  109. package/src/core/command.ts +9 -9
  110. package/src/core/renderTask.ts +55 -2
  111. package/src/resources/preparedRenderObject.ts +3 -3
  112. package/src/resources/uniformBuffer.ts +15 -0
  113. package/src/runtime/derivedUniforms/dispatch.ts +407 -0
  114. package/src/runtime/derivedUniforms/index.ts +52 -0
  115. package/src/runtime/derivedUniforms/recipes.ts +159 -0
  116. package/src/runtime/derivedUniforms/sceneIntegration.ts +239 -0
  117. package/src/runtime/derivedUniforms/slotId.ts +35 -0
  118. package/src/runtime/derivedUniforms/slots.ts +155 -0
  119. package/src/runtime/derivedUniforms/uberKernel.wgsl.ts +220 -0
  120. package/src/runtime/flattenTree.ts +46 -0
  121. package/src/runtime/heapAdapter.ts +314 -0
  122. package/src/runtime/heapEffect.ts +719 -0
  123. package/src/runtime/heapEffectIR.ts +1211 -0
  124. package/src/runtime/heapEligibility.ts +189 -0
  125. package/src/runtime/heapScene.ts +3981 -349
  126. package/src/runtime/heapShaderFamily.ts +1102 -0
  127. package/src/runtime/hybridScene.ts +310 -0
  128. package/src/runtime/index.ts +46 -0
  129. package/src/runtime/renderTask.ts +167 -32
  130. package/src/runtime/runtime.ts +37 -4
  131. package/src/runtime/scenePass.ts +39 -4
  132. package/src/runtime/textureAtlas/atlasMipGutterKernel.ts +291 -0
  133. package/src/runtime/textureAtlas/atlasPool.ts +991 -0
  134. package/src/runtime/textureAtlas/bvhTree2d.ts +530 -0
  135. package/src/runtime/textureAtlas/packer.ts +429 -0
  136. package/src/window/loop.ts +32 -6
@@ -0,0 +1,429 @@
1
+ // TexturePacking — incremental immutable MaxRects-style 2D rectangle
2
+ // packer over `BvhTree2d`.
3
+ //
4
+ // Port of `Aardvark.Geometry.TexturePacking<'a>` from
5
+ // `aardvark.base/src/Aardvark.Geometry/TexturePacking.fs`. Algorithm:
6
+ // - Atlas is described by a set of free MaxRects (contained in a
7
+ // `BvhTree2d` keyed on the rect itself for O(log N) queries).
8
+ // - tryAdd picks the free rect with the smallest waste that fits the
9
+ // incoming size (with optional 90° rotation), splits the chosen
10
+ // rect into the placed sub-rect plus residual MaxRects.
11
+ // - Remove restores a sub-rect and merges with adjacent free rects
12
+ // using the F# `merge` routine, which incrementally maintains
13
+ // non-overlapping MaxRects covering the released region + neighbours.
14
+ //
15
+ // The wombat port keys the BVH on `Box2i` value-objects. We use a
16
+ // stable string key (`"minX,minY,maxX,maxY"`) so identical rectangles
17
+ // share a Map slot — Box2i instances themselves are reference types in
18
+ // JS and would not collide otherwise.
19
+
20
+ import { Box2d, Box2i, V2d, V2i } from "@aardworx/wombat.base";
21
+ import { BvhTree2d } from "./bvhTree2d.js";
22
+
23
+ // ─── Box2i helpers (mirroring the F# helpers in this module) ───────
24
+
25
+ const boxKey = (b: Box2i): string => {
26
+ const mn = b.min, mx = b.max;
27
+ return `${mn.x},${mn.y},${mx.x},${mx.y}`;
28
+ };
29
+
30
+ const sizeOf = (b: Box2i): V2i => {
31
+ const mn = b.min, mx = b.max;
32
+ return new V2i(mx.x - mn.x + 1, mx.y - mn.y + 1);
33
+ };
34
+
35
+ const isValid2i = (b: Box2i): boolean => {
36
+ const mn = b.min, mx = b.max;
37
+ return mn.x <= mx.x && mn.y <= mx.y;
38
+ };
39
+
40
+ const intersects2i = (a: Box2i, b: Box2i): boolean => {
41
+ const amin = a.min, amax = a.max, bmin = b.min, bmax = b.max;
42
+ return amin.x <= bmax.x && amax.x >= bmin.x && amin.y <= bmax.y && amax.y >= bmin.y;
43
+ };
44
+
45
+ const intersectsTouching2i = (a: Box2i, b: Box2i): boolean => {
46
+ // Mirror F# `intersects` inside `maxRects`: a 1-unit halo so adjacent
47
+ // rectangles count as overlapping (used to detect contact).
48
+ const amin = a.min, amax = a.max, bmin = b.min, bmax = b.max;
49
+ return amin.x <= bmax.x + 1 && amax.x >= bmin.x - 1 && amin.y <= bmax.y + 1 && amax.y >= bmin.y - 1;
50
+ };
51
+
52
+ const contains2i = (outer: Box2i, inner: Box2i): boolean => {
53
+ const omin = outer.min, omax = outer.max, imin = inner.min, imax = inner.max;
54
+ return omin.x <= imin.x && omin.y <= imin.y && omax.x >= imax.x && omax.y >= imax.y;
55
+ };
56
+
57
+ const equals2i = (a: Box2i, b: Box2i): boolean => {
58
+ const amin = a.min, amax = a.max, bmin = b.min, bmax = b.max;
59
+ return amin.x === bmin.x && amin.y === bmin.y && amax.x === bmax.x && amax.y === bmax.y;
60
+ };
61
+
62
+ const mkBox = (minX: number, minY: number, maxX: number, maxY: number): Box2i =>
63
+ new Box2i(minX, minY, maxX, maxY);
64
+
65
+ // `createBox`: half-pixel padded Box2d for BVH key. Exact mirror of
66
+ // F#'s `createBox`.
67
+ const createBox = (b: Box2i): Box2d => {
68
+ const mn = b.min, mx = b.max;
69
+ return Box2d.fromMinMax(
70
+ new V2d(mn.x - 0.5, mn.y - 0.5),
71
+ new V2d(mx.x + 0.5, mx.y + 0.5),
72
+ );
73
+ };
74
+
75
+ // Subtract `b` from `a` (the placed rect from a free rect) and produce
76
+ // up to four residual MaxRects strips. Mirrors F#'s `split`.
77
+ const splitRects = (a: Box2i, b: Box2i): Box2i[] => {
78
+ const cands: Box2i[] = [
79
+ mkBox(b.max.x + 1, a.min.y, a.max.x, a.max.y),
80
+ mkBox(a.min.x, a.min.y, b.min.x - 1, a.max.y),
81
+ mkBox(a.min.x, b.max.y + 1, a.max.x, a.max.y),
82
+ mkBox(a.min.x, a.min.y, a.max.x, b.min.y - 1),
83
+ ];
84
+ return cands.filter(isValid2i);
85
+ };
86
+
87
+ // MaxRects union/cleanup. Direct port of F#'s `maxRects`.
88
+ const maxRectsCombine = (a: Box2i, b: Box2i): Box2i[] => {
89
+ if (intersectsTouching2i(a, b)) {
90
+ if (contains2i(a, b)) return [a];
91
+ if (contains2i(b, a)) return [b];
92
+ const ax0 = a.min.x, ax1 = a.max.x, ay0 = a.min.y, ay1 = a.max.y;
93
+ const bx0 = b.min.x, bx1 = b.max.x, by0 = b.min.y, by1 = b.max.y;
94
+
95
+ // RangeX of a contains RangeX of b: ax0<=bx0 && ax1>=bx1
96
+ const abx = ax0 <= bx0 && ax1 >= bx1;
97
+ const bax = bx0 <= ax0 && bx1 >= ax1;
98
+ const aby = ay0 <= by0 && ay1 >= by1;
99
+ const bay = by0 <= ay0 && by1 >= ay1;
100
+
101
+ if (abx && bax) {
102
+ // identical X — Y-union
103
+ return [mkBox(ax0, Math.min(ay0, by0), ax1, Math.max(ay1, by1))];
104
+ }
105
+ if (aby && bay) {
106
+ return [mkBox(Math.min(ax0, bx0), ay0, Math.max(ax1, bx1), ay1)];
107
+ }
108
+ if (abx) {
109
+ return [mkBox(bx0, Math.min(ay0, by0), bx1, Math.max(ay1, by1)), a];
110
+ }
111
+ if (bax) {
112
+ return [mkBox(ax0, Math.min(ay0, by0), ax1, Math.max(ay1, by1)), b];
113
+ }
114
+ if (aby) {
115
+ return [mkBox(Math.min(ax0, bx0), by0, Math.max(ax1, bx1), by1), a];
116
+ }
117
+ if (bay) {
118
+ return [mkBox(Math.min(ax0, bx0), ay0, Math.max(ax1, bx1), ay1), b];
119
+ }
120
+ // Cross case: produce the two orthogonal strips of each rect's
121
+ // overlap with the other, plus both originals; filter invalid.
122
+ const out: Box2i[] = [
123
+ mkBox(Math.min(ax0, bx0), Math.max(ay0, by0), Math.max(ax1, bx1), Math.min(ay1, by1)),
124
+ mkBox(Math.max(ax0, bx0), Math.min(ay0, by0), Math.min(ax1, bx1), Math.max(ay1, by1)),
125
+ a,
126
+ b,
127
+ ];
128
+ return out.filter(isValid2i);
129
+ }
130
+ return [a, b];
131
+ };
132
+
133
+ // Merge a freshly-released rect `n` with already-known adjacent free
134
+ // rects, producing the new MaxRects covering the union. Direct port
135
+ // of F#'s `merge`.
136
+ const merge = (n: Box2i, boxes: Iterable<Box2i>): Box2i[] => {
137
+ const boxArr = [...boxes];
138
+ if (boxArr.length === 0) return [n];
139
+
140
+ type FreeT = BvhTree2d<string, Box2i>;
141
+ let free: FreeT = BvhTree2d.empty<string, Box2i>();
142
+
143
+ const addOne = (b: Box2i): void => {
144
+ const q = mkBox(b.min.x - 1, b.min.y - 1, b.max.x + 1, b.max.y + 1);
145
+ const touching: Box2i[] = [];
146
+ for (const [, val] of free.getIntersecting(createBox(q))) {
147
+ if (intersectsTouching2i(val, q)) touching.push(val);
148
+ }
149
+ if (touching.length === 0) {
150
+ free = free.add(boxKey(b), createBox(b), b);
151
+ return;
152
+ }
153
+ for (const o of touching) {
154
+ free = free.remove(boxKey(o));
155
+ for (const r of maxRectsCombine(o, b)) {
156
+ // skip if any existing free rect already contains r
157
+ let contained = false;
158
+ for (const [, val] of free.getContaining(createBox(r))) {
159
+ if (contains2i(val, r)) { contained = true; break; }
160
+ }
161
+ if (!contained) {
162
+ // remove any free rect r contains
163
+ const containedKeys: string[] = [];
164
+ for (const [k, val] of free.getContained(createBox(r))) {
165
+ if (contains2i(r, val)) containedKeys.push(k);
166
+ void val;
167
+ }
168
+ for (const k of containedKeys) free = free.remove(k);
169
+ free = free.add(boxKey(r), createBox(r), r);
170
+ }
171
+ }
172
+ }
173
+ };
174
+
175
+ addOne(n);
176
+ for (const b of boxArr) addOne(b);
177
+
178
+ return [...free.toSeq()].map(([, , v]) => v);
179
+ };
180
+
181
+ // Add a free rect into the tree iff no existing rect already contains
182
+ // it. Mirror of F#'s `addFree`.
183
+ const addFree = (b: Box2i, free: BvhTree2d<string, Box2i>): BvhTree2d<string, Box2i> => {
184
+ if (!isValid2i(b)) return free;
185
+ let containing = false;
186
+ for (const [, v] of free.getContaining(createBox(b))) {
187
+ if (contains2i(v, b)) { containing = true; break; }
188
+ }
189
+ if (containing) return free;
190
+ return free.add(boxKey(b), createBox(b), b);
191
+ };
192
+
193
+ /**
194
+ * Immutable 2D atlas. Generic over `K` (entry key — anything that's a
195
+ * valid `Map` key works; we recommend strings or numbers).
196
+ */
197
+ export class TexturePacking<K> {
198
+ private constructor(
199
+ public readonly size: V2i,
200
+ public readonly allowRotate: boolean,
201
+ private readonly free: BvhTree2d<string, Box2i>,
202
+ /** Used rects keyed on the user's K. */
203
+ public readonly used: ReadonlyMap<K, Box2i>,
204
+ ) {}
205
+
206
+ static empty<K>(size: V2i, allowRotate: boolean = true): TexturePacking<K> {
207
+ if (size.x <= 0 || size.y <= 0) {
208
+ return new TexturePacking<K>(new V2i(0, 0), allowRotate, BvhTree2d.empty<string, Box2i>(), new Map());
209
+ }
210
+ const bb = mkBox(0, 0, size.x - 1, size.y - 1);
211
+ const tree = BvhTree2d.empty<string, Box2i>().add(boxKey(bb), createBox(bb), bb);
212
+ return new TexturePacking<K>(size, allowRotate, tree, new Map());
213
+ }
214
+
215
+ static create<K>(size: V2i, allowRotate: boolean = true): TexturePacking<K> {
216
+ return TexturePacking.empty<K>(size, allowRotate);
217
+ }
218
+
219
+ get count(): number {
220
+ return this.used.size;
221
+ }
222
+
223
+ get isEmpty(): boolean {
224
+ return this.used.size === 0;
225
+ }
226
+
227
+ /** All free MaxRects. */
228
+ get freeRects(): Iterable<Box2i> {
229
+ return [...this.free.toSeq()].map(([, , v]) => v);
230
+ }
231
+
232
+ get occupancy(): number {
233
+ let area = 0;
234
+ for (const [, b] of this.used) {
235
+ const s = sizeOf(b);
236
+ area += s.x * s.y;
237
+ }
238
+ const total = this.size.x * this.size.y;
239
+ return total > 0 ? area / total : 0;
240
+ }
241
+
242
+ /**
243
+ * Try to insert one entry. Returns the new packing on success, or
244
+ * `null` if no free rect (with optional rotation) can accommodate
245
+ * `size`.
246
+ *
247
+ * If `id` is already present:
248
+ * - same size → returns `this` (no-op).
249
+ * - different size → removes then re-adds.
250
+ */
251
+ tryAdd(id: K, size: V2i): TexturePacking<K> | null;
252
+ /** Atomic batch insert: returns null if any element would not fit. */
253
+ tryAdd(many: Iterable<readonly [K, V2i]>): TexturePacking<K> | null;
254
+ tryAdd(a: K | Iterable<readonly [K, V2i]>, b?: V2i): TexturePacking<K> | null {
255
+ if (b === undefined) {
256
+ let cur: TexturePacking<K> | null = this;
257
+ for (const [id, sz] of a as Iterable<readonly [K, V2i]>) {
258
+ if (cur === null) return null;
259
+ cur = cur.tryAddOne(id, sz);
260
+ }
261
+ return cur;
262
+ }
263
+ return this.tryAddOne(a as K, b);
264
+ }
265
+
266
+ private tryAddOne(id: K, size: V2i): TexturePacking<K> | null {
267
+ if (size.x <= 0 || size.y <= 0) return this;
268
+ const ex = this.used.get(id);
269
+ if (ex !== undefined) {
270
+ const s = sizeOf(ex);
271
+ if (s.x === size.x && s.y === size.y) return this;
272
+ const removed = this.remove(id);
273
+ return removed.tryAddOne(id, size);
274
+ }
275
+
276
+ // Score each free rect; pick the smallest waste that fits.
277
+ let best: { rect: Box2i; upright: boolean; score: number } | undefined;
278
+ for (const [, , rect] of this.free.toSeq()) {
279
+ const sh = sizeOf(rect);
280
+ const f0 = sh.x >= size.x && sh.y >= size.y;
281
+ const f1 = this.allowRotate ? sh.x >= size.y && sh.y >= size.x : false;
282
+ const w0 = (sh.x - size.x) * (sh.y - size.y);
283
+ const w1 = (sh.x - size.y) * (sh.y - size.x);
284
+ let cand: { score: number; upright: boolean } | undefined;
285
+ if (f0 && f1) {
286
+ if (w0 < w1) cand = { score: w0, upright: true };
287
+ else cand = { score: w1, upright: false };
288
+ } else if (f0) cand = { score: w0, upright: true };
289
+ else if (f1) cand = { score: w1, upright: false };
290
+ if (cand !== undefined && (best === undefined || cand.score < best.score)) {
291
+ best = { rect, upright: cand.upright, score: cand.score };
292
+ }
293
+ }
294
+
295
+ if (best === undefined) return null;
296
+
297
+ const placedSize = best.upright ? size : new V2i(size.y, size.x);
298
+ const fitting = best.rect;
299
+
300
+ // Two slabs left of `fitting` after placement: right strip + top
301
+ // strip. Mirror F# layout.
302
+ const r0 = mkBox(fitting.min.x + placedSize.x, fitting.min.y, fitting.max.x, fitting.max.y);
303
+ const r1 = mkBox(fitting.min.x, fitting.min.y + placedSize.y, fitting.max.x, fitting.max.y);
304
+ const rect = mkBox(
305
+ fitting.min.x,
306
+ fitting.min.y,
307
+ fitting.min.x + placedSize.x - 1,
308
+ fitting.min.y + placedSize.y - 1,
309
+ );
310
+
311
+ let free = this.free.remove(boxKey(fitting));
312
+ free = addFree(r0, free);
313
+ free = addFree(r1, free);
314
+
315
+ // For every other free rect intersecting `rect`, replace with
316
+ // `splitRects(other, rect)`.
317
+ const intersecting: Array<[string, Box2i]> = [];
318
+ for (const [, , v] of free.toSeq()) {
319
+ if (intersects2i(v, rect)) intersecting.push([boxKey(v), v]);
320
+ }
321
+ for (const [k, other] of intersecting) {
322
+ free = free.remove(k);
323
+ for (const p of splitRects(other, rect)) free = addFree(p, free);
324
+ }
325
+
326
+ const newUsed = new Map(this.used);
327
+ newUsed.set(id, rect);
328
+ return new TexturePacking<K>(this.size, this.allowRotate, free, newUsed);
329
+ }
330
+
331
+ /** Remove `id` (no-op if absent). */
332
+ remove(id: K): TexturePacking<K> {
333
+ const rect = this.used.get(id);
334
+ if (rect === undefined) return this;
335
+ const newUsed = new Map(this.used);
336
+ newUsed.delete(id);
337
+
338
+ const qi = mkBox(rect.min.x - 1, rect.min.y - 1, rect.max.x + 1, rect.max.y + 1);
339
+ const adjacent: Box2i[] = [];
340
+ for (const [, , v] of [...this.free.getIntersecting(createBox(qi))].map(
341
+ ([k, vv]) => [k, vv, vv] as const,
342
+ )) {
343
+ if (
344
+ v.min.x === qi.max.x ||
345
+ v.max.x === qi.min.x ||
346
+ v.min.y === qi.max.y ||
347
+ v.max.y === qi.min.y
348
+ ) {
349
+ adjacent.push(v);
350
+ }
351
+ }
352
+ let free = this.free;
353
+ for (const a of adjacent) free = free.remove(boxKey(a));
354
+ for (const m of merge(rect, adjacent)) free = addFree(m, free);
355
+ return new TexturePacking<K>(this.size, this.allowRotate, free, newUsed);
356
+ }
357
+ }
358
+
359
+ // ─── Module-level helpers (matching the F# `module TexturePacking`) ─
360
+
361
+ export const empty = <K>(size: V2i): TexturePacking<K> => TexturePacking.empty<K>(size);
362
+ export const isEmpty = <K>(p: TexturePacking<K>): boolean => p.isEmpty;
363
+ export const count = <K>(p: TexturePacking<K>): number => p.count;
364
+ export const occupancy = <K>(p: TexturePacking<K>): number => p.occupancy;
365
+ export const tryAdd = <K>(id: K, size: V2i, p: TexturePacking<K>): TexturePacking<K> | null =>
366
+ p.tryAdd(id, size);
367
+
368
+ /** Sort-then-tryAdd helper. Sorting by descending max-extent matches the F# heuristic. */
369
+ export const tryAddMany = <K>(
370
+ elements: Iterable<readonly [K, V2i]>,
371
+ p: TexturePacking<K>,
372
+ ): TexturePacking<K> | null => {
373
+ const arr = [...elements];
374
+ arr.sort((a, b) => Math.max(b[1].x, b[1].y) - Math.max(a[1].x, a[1].y));
375
+ return p.tryAdd(arr);
376
+ };
377
+
378
+ export const tryOfArray = <K>(
379
+ size: V2i,
380
+ elements: ReadonlyArray<readonly [K, V2i]>,
381
+ ): TexturePacking<K> | null => tryAddMany(elements, empty<K>(size));
382
+
383
+ /**
384
+ * Build an optimal-square packing for the given elements, doubling
385
+ * the side until everything fits then binary-searching down. Mirrors
386
+ * F#'s `TexturePacking.square`.
387
+ */
388
+ export const square = <K>(elements: ReadonlyArray<readonly [K, V2i]>): TexturePacking<K> => {
389
+ const arr = [...elements];
390
+ arr.sort((a, b) => Math.max(b[1].x, b[1].y) - Math.max(a[1].x, a[1].y));
391
+ if (arr.length === 0) return empty<K>(new V2i(0, 0));
392
+ if (arr.length === 1) {
393
+ const [id, sz] = arr[0]!;
394
+ const s = Math.max(sz.x, sz.y);
395
+ return empty<K>(new V2i(s, s)).tryAdd(id, sz)!;
396
+ }
397
+ let area = 0;
398
+ for (const [, sz] of arr) area += sz.x * sz.y;
399
+ let lo = Math.floor(Math.sqrt(area));
400
+ let hi = nextPow2(lo);
401
+ let best = tryOfArray(new V2i(hi, hi), arr);
402
+ while (best === null) {
403
+ lo = hi;
404
+ hi = hi * 2;
405
+ best = tryOfArray(new V2i(hi, hi), arr);
406
+ }
407
+ let bestPacking = best;
408
+ while (hi > lo + 1) {
409
+ const m = (hi + lo) >> 1;
410
+ const p = tryOfArray(new V2i(m, m), arr);
411
+ if (p !== null) {
412
+ bestPacking = p;
413
+ hi = m;
414
+ } else {
415
+ lo = m;
416
+ }
417
+ }
418
+ return bestPacking;
419
+ };
420
+
421
+ function nextPow2(n: number): number {
422
+ if (n <= 1) return 1;
423
+ let p = 1;
424
+ while (p < n) p *= 2;
425
+ return p;
426
+ }
427
+
428
+ // silence unused-helper warning at export-time tooling
429
+ void equals2i;
@@ -39,6 +39,20 @@ export interface RunFrameOptions {
39
39
  * behavior.
40
40
  */
41
41
  readonly onAfterFrame?: () => void;
42
+ /**
43
+ * Frame pacer. When provided, runFrame awaits this promise after
44
+ * each frame's eval and BEFORE invoking `onAfterFrame` / scheduling
45
+ * the next rAF. Caps the JS encode rate to whatever the pacer
46
+ * resolves at — typically `() => device.queue.onSubmittedWorkDone()`
47
+ * to keep the GPU queue at depth 1 instead of letting submit-
48
+ * returns-immediately balloon the queue under load.
49
+ *
50
+ * Without a pacer, JS happily encodes 60 frames/s into a GPU that's
51
+ * actually running at 10 fps — the compositor then drops frames
52
+ * silently and the perceived rate has nothing to do with rAF rate.
53
+ * Always supply a pacer for continuous-redraw scenes.
54
+ */
55
+ readonly pacer?: () => Promise<void>;
42
56
  }
43
57
 
44
58
  export type FrameCallback = (token: AdaptiveToken, info: FrameInfo) => void;
@@ -79,6 +93,17 @@ export function runFrame(
79
93
  return frameNo;
80
94
  });
81
95
 
96
+ const finalizeFrame = (): void => {
97
+ if (stopped) return;
98
+ if (opts.onAfterFrame !== undefined) {
99
+ transact(opts.onAfterFrame);
100
+ }
101
+ if (opts.maxFrames !== undefined && frameNo >= opts.maxFrames) {
102
+ stopped = true;
103
+ sub.dispose();
104
+ }
105
+ };
106
+
82
107
  const tick = (): void => {
83
108
  if (stopped) return;
84
109
  pending = false;
@@ -93,12 +118,13 @@ export function runFrame(
93
118
  // Inside the eval the same mark would race the
94
119
  // `outOfDate=false` reset and animation would stall after one
95
120
  // frame.
96
- if (opts.onAfterFrame !== undefined) {
97
- transact(opts.onAfterFrame);
98
- }
99
- if (opts.maxFrames !== undefined && frameNo >= opts.maxFrames) {
100
- stopped = true;
101
- sub.dispose();
121
+ if (opts.pacer !== undefined) {
122
+ opts.pacer().then(finalizeFrame, (e) => {
123
+ stopped = true;
124
+ console.error("runFrame: pacer rejected", e);
125
+ });
126
+ } else {
127
+ finalizeFrame();
102
128
  }
103
129
  };
104
130