poker-flopsolve 0.4.1 → 0.5.0-beta.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.
@@ -0,0 +1,238 @@
1
+ // src/engine.ts
2
+ var wasm = globalThis.WebAssembly;
3
+ var ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, size: 8 };
4
+
5
+ // src/engine-thread.ts
6
+ function serveEngine(setup) {
7
+ const GENERATION = 0;
8
+ const DONE = 1;
9
+ const COMMAND = 2;
10
+ const MODE = 3;
11
+ const TRAVERSER = 4;
12
+ const READY = 5;
13
+ const FAILED = 6;
14
+ const EXIT = 1;
15
+ const api = globalThis.WebAssembly;
16
+ const memory = setup.memory;
17
+ const imports = {
18
+ env: {
19
+ memory,
20
+ abort() {
21
+ throw new Error("engine abort");
22
+ }
23
+ }
24
+ };
25
+ const engine = new api.Instance(setup.module, imports).exports;
26
+ engine.init(setup.header);
27
+ engine.setMaxActions(setup.maxActions);
28
+ engine.setExchange(setup.exchange[0], setup.exchange[1], setup.exchange[2], setup.exchange[3]);
29
+ engine.setShard(setup.shard[0], setup.shard[1], setup.shard[2]);
30
+ engine.setPhase(0, 1);
31
+ const shared = setup.shared;
32
+ if (shared) engine.setShared(shared[0], shared[1], shared[2]);
33
+ const s = setup.sampling;
34
+ if (s) engine.setSampling(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11]);
35
+ const needsIteration = shared !== void 0 || setup.storage === true || s !== void 0;
36
+ const control = new Int32Array(setup.control);
37
+ const settings = new Float64Array(setup.settings);
38
+ const entries = setup.entryNodes.length;
39
+ const rowBytes = setup.stride * 4;
40
+ const partials = new Float32Array(memory.buffer, setup.partial, entries * setup.stride);
41
+ const reach = setup.exchange[1];
42
+ let generation = Atomics.load(control, GENERATION);
43
+ Atomics.add(control, READY, 1);
44
+ Atomics.notify(control, READY);
45
+ if (Atomics.load(control, COMMAND) === EXIT) return;
46
+ for (; ; ) {
47
+ Atomics.wait(control, GENERATION, generation);
48
+ generation = Atomics.load(control, GENERATION);
49
+ if (Atomics.load(control, COMMAND) === EXIT) return;
50
+ const mode = Atomics.load(control, MODE);
51
+ const traverser = Atomics.load(control, TRAVERSER);
52
+ const positive = settings[0];
53
+ const negative = settings[1];
54
+ const sum = settings[2];
55
+ const weight = settings[3];
56
+ const clamp = settings[4];
57
+ try {
58
+ engine.setPhase(0, settings[5]);
59
+ if (needsIteration) engine.setIteration(settings[6], settings[7]);
60
+ for (let entry = 0; entry < entries; entry++) {
61
+ const slot = reach + entry * 2 * rowBytes;
62
+ const out = engine.runChance(
63
+ mode,
64
+ traverser,
65
+ setup.entryNodes[entry],
66
+ slot,
67
+ slot + rowBytes,
68
+ positive,
69
+ negative,
70
+ sum,
71
+ weight,
72
+ clamp
73
+ ) >>> 0;
74
+ partials.set(new Float32Array(memory.buffer, out, setup.stride), entry * setup.stride);
75
+ }
76
+ } catch (error) {
77
+ Atomics.store(control, FAILED, 1);
78
+ throw error;
79
+ } finally {
80
+ Atomics.add(control, DONE, 1);
81
+ Atomics.notify(control, DONE);
82
+ }
83
+ }
84
+ }
85
+
86
+ // src/platform/browser-threads.ts
87
+ var THREADS_KEY = /* @__PURE__ */ Symbol.for("poker-flopsolve.browser-threads");
88
+ function pool() {
89
+ const holder = globalThis;
90
+ holder[THREADS_KEY] ??= {
91
+ threads: [],
92
+ idle: () => idleThreads(),
93
+ total: () => pool().length,
94
+ spawn: (setup, onError) => spawn(setup, onError)
95
+ };
96
+ return holder[THREADS_KEY].threads;
97
+ }
98
+ function idleThreads() {
99
+ return pool().filter((thread) => !thread.busy).length;
100
+ }
101
+ function drop(thread) {
102
+ thread.worker.terminate();
103
+ thread.busy = true;
104
+ const threads = pool();
105
+ const at = threads.indexOf(thread);
106
+ if (at >= 0) threads.splice(at, 1);
107
+ }
108
+ var COMMAND_EXIT = 1;
109
+ function spawn(setup, onError) {
110
+ const thread = pool().find((candidate) => !candidate.busy);
111
+ if (!thread) throw new Error("No idle engine thread; call enableThreads() from poker-flopsolve/threads first");
112
+ thread.busy = true;
113
+ thread.worker.onerror = (event) => {
114
+ event.preventDefault?.();
115
+ drop(thread);
116
+ onError(new Error(`Engine thread failed: ${event.message ?? "unknown error"}`));
117
+ };
118
+ thread.port.postMessage(setup);
119
+ const control = new Int32Array(setup.control);
120
+ let released = false;
121
+ return {
122
+ terminate() {
123
+ if (released) return;
124
+ released = true;
125
+ if (!pool().includes(thread)) return;
126
+ if (Atomics.load(control, ENGINE_CONTROL.failed) !== 0) {
127
+ drop(thread);
128
+ return;
129
+ }
130
+ if (Atomics.load(control, ENGINE_CONTROL.command) !== COMMAND_EXIT) {
131
+ Atomics.store(control, ENGINE_CONTROL.command, COMMAND_EXIT);
132
+ Atomics.add(control, ENGINE_CONTROL.generation, 1);
133
+ Atomics.notify(control, ENGINE_CONTROL.generation);
134
+ }
135
+ thread.busy = false;
136
+ thread.worker.onerror = () => drop(thread);
137
+ }
138
+ };
139
+ }
140
+ function threadsUnavailableReason() {
141
+ const g = globalThis;
142
+ if (typeof g.Worker !== "function" || typeof g.Blob !== "function" || typeof g.MessageChannel !== "function") {
143
+ return "no Web Workers here";
144
+ }
145
+ if (g.crossOriginIsolated !== true) {
146
+ return "the page is not cross-origin isolated (serve it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp)";
147
+ }
148
+ if (typeof SharedArrayBuffer !== "function") return "no SharedArrayBuffer here";
149
+ try {
150
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 1, 0);
151
+ } catch {
152
+ return "Atomics.wait is not allowed on this thread; solve inside a Web Worker";
153
+ }
154
+ try {
155
+ new g.WebAssembly.Memory({ initial: 1, maximum: 1, shared: true });
156
+ } catch {
157
+ return "no shared WebAssembly memory here";
158
+ }
159
+ return null;
160
+ }
161
+ var START_MS = 3e4;
162
+ function startThread(url) {
163
+ const g = globalThis;
164
+ return new Promise((resolve) => {
165
+ let worker;
166
+ try {
167
+ worker = new g.Worker(url);
168
+ } catch {
169
+ resolve(null);
170
+ return;
171
+ }
172
+ const timer = setTimeout(() => {
173
+ worker.terminate();
174
+ resolve(null);
175
+ }, START_MS);
176
+ const channel = new g.MessageChannel();
177
+ worker.onmessage = () => {
178
+ clearTimeout(timer);
179
+ worker.onmessage = null;
180
+ worker.onerror = null;
181
+ resolve({ worker, port: channel.port1, busy: false });
182
+ };
183
+ worker.postMessage(null, [channel.port2]);
184
+ worker.onerror = (event) => {
185
+ event.preventDefault?.();
186
+ clearTimeout(timer);
187
+ worker.terminate();
188
+ resolve(null);
189
+ };
190
+ });
191
+ }
192
+ function prepareThreads(count) {
193
+ const next = pending.then(() => resize(count));
194
+ pending = next.catch(() => void 0);
195
+ return next;
196
+ }
197
+ var pending = Promise.resolve();
198
+ async function resize(count) {
199
+ const g = globalThis;
200
+ const wanted = Math.max(1, Math.floor(count ?? g.navigator?.hardwareConcurrency ?? 1));
201
+ const threads = pool();
202
+ for (let i = threads.length - 1; i >= 0 && threads.length > wanted - 1; i--) {
203
+ if (!threads[i].busy) drop(threads[i]);
204
+ }
205
+ const missing = wanted - 1 - threads.length;
206
+ if (missing > 0 && threadsUnavailableReason() === null) {
207
+ const source = `const serveEngine = ${serveEngine.toString()};
208
+ onmessage = (event) => {
209
+ event.ports[0].onmessage = (solve) => serveEngine(solve.data);
210
+ postMessage('ready');
211
+ };
212
+ `;
213
+ const url = g.URL.createObjectURL(new g.Blob([source], { type: "text/javascript" }));
214
+ try {
215
+ const started = await Promise.all(Array.from({ length: missing }, () => startThread(url)));
216
+ for (const thread of started) if (thread) threads.push(thread);
217
+ } finally {
218
+ g.URL.revokeObjectURL(url);
219
+ }
220
+ }
221
+ return threadsUnavailableReason() === null ? Math.min(wanted, 1 + idleThreads()) : 1;
222
+ }
223
+
224
+ // src/platform/browser.ts
225
+ var DEFAULT_MAX_BYTES = 512 * 1024 * 1024;
226
+
227
+ // src/threads.ts
228
+ function enableThreads(count) {
229
+ return prepareThreads(count);
230
+ }
231
+ function threadsUnavailable() {
232
+ return threadsUnavailableReason();
233
+ }
234
+ export {
235
+ enableThreads,
236
+ threadsUnavailable
237
+ };
238
+ //# sourceMappingURL=browser-threads.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/engine.ts","../src/engine-thread.ts","../src/platform/browser-threads.ts","../src/platform/browser.ts","../src/threads.ts"],"sourcesContent":["/**\n * The WebAssembly traversal engine, set up.\n *\n * Purpose: lay a prepared spot out in one WebAssembly memory for\n * `assembly/engine.ts`, and give the solver its storage and a root traversal.\n *\n * The engine keeps the accumulators in its own memory as 32-bit floats; the\n * solver's `regret` and `strategySum` are views onto them, so everything that\n * reads storage from JavaScript — strategy queries, warm starts, `valuesAt` —\n * sees the very same numbers. It runs where WebAssembly SIMD is available,\n * on one thread or several; otherwise the JavaScript traversal in cfr.ts\n * runs. A second build, which only `poker-flopsolve/wasm-storage` carries,\n * keeps 16-bit and compact storage the same way (`EngineInput.storage`).\n *\n * WebAssembly memory is one buffer, but Chromium lets it reach wasm32's full\n * 4 GiB, plain or shared, made at that size or grown to it, where it refuses\n * any ArrayBuffer over 2 GiB less 2 MiB (measured in Chromium 153 by\n * bin/memory-ceiling.ts; issue #84). So compact storage needs no chunks of\n * its own in the engine: its chunks are regions of the one memory, laid out\n * as the JavaScript engine's buffers are.\n */\n\nimport { COMBOS } from './cards.ts';\nimport type { ActiveLists, CompactPlan, Layout, PlayerIndex, RegretStore, RootTraversal, SamplingPlan, SumStore } from './cfr.ts';\nimport { dcfrFactors, Mode, treeDepth } from './cfr.ts';\nimport type { HandSpace } from './hands.ts';\nimport type { Runouts } from './runouts.ts';\nimport type { Tree } from './tree.ts';\nimport { ENGINE_WASM } from './wasm/engine.ts';\nimport { ENGINE_SHARED_WASM } from './wasm/engine-shared.ts';\nimport type { ShardPlan } from './parallel.ts';\nimport { awaitThreads, THREAD_FAILED_ERROR, WORKER_START_ERROR, WORKER_START_MS } from './parallel.ts';\n\n/** The parts of the WebAssembly API used here, typed locally: the project builds without DOM typings. */\ninterface WasmApi {\n\tvalidate(bytes: Uint8Array): boolean;\n\tModule: new (bytes: Uint8Array) => object;\n\tInstance: new (module: object, imports: object) => { exports: Record<string, unknown> };\n\tMemory: new (descriptor: { initial: number; maximum?: number; shared?: boolean }) => { buffer: ArrayBuffer };\n}\n\nconst wasm = (globalThis as unknown as { WebAssembly?: WasmApi }).WebAssembly;\nconst modules: Record<'plain' | 'shared', object | null | undefined> = { plain: undefined, shared: undefined };\n\n/** The compiled engine, over plain or shared memory; null where unavailable. */\nexport function compiledEngine(kind: 'plain' | 'shared'): object | null {\n\treturn compileInto(modules, kind, kind === 'plain' ? ENGINE_WASM : ENGINE_SHARED_WASM);\n}\n\n/** Compile base64 WebAssembly into `cache[kind]` once; null there where unavailable. */\nfunction compileInto(cache: Record<'plain' | 'shared', object | null | undefined>, kind: 'plain' | 'shared', text: string): object | null {\n\tif (cache[kind] !== undefined) return cache[kind]!;\n\tcache[kind] = null;\n\ttry {\n\t\tif (!wasm) return null;\n\t\tconst bytes = Uint8Array.from(atob(text), (c) => c.charCodeAt(0));\n\t\tif (!wasm.validate(bytes)) return null;\n\t\tcache[kind] = new wasm.Module(bytes);\n\t} catch {\n\t\tcache[kind] = null;\n\t}\n\treturn cache[kind]!;\n}\n\n/**\n * The engine with 16-bit and compact storage (issue #84), as base64 for plain\n * and shared memory. Only `poker-flopsolve/wasm-storage` holds the bytes, so\n * a build that never imports it carries none of them; a solve opts in by\n * passing it as `SolveOptions.wasmStorage`.\n */\nexport interface WasmStorage {\n\treadonly plain: string;\n\treadonly shared: string;\n}\n\nconst storageModules = new WeakMap<WasmStorage, Record<'plain' | 'shared', object | null | undefined>>();\n\n/** The storage engine compiled, over plain or shared memory; null where unavailable. */\nfunction compiledStorage(source: WasmStorage, kind: 'plain' | 'shared'): object | null {\n\tlet cache = storageModules.get(source);\n\tif (!cache) storageModules.set(source, (cache = { plain: undefined, shared: undefined }));\n\treturn compileInto(cache, kind, source[kind]);\n}\n\nfunction compiled(): object | null {\n\treturn compiledEngine('plain');\n}\n\n/** Whether this platform can run the WebAssembly engine. */\nexport function engineAvailable(): boolean {\n\treturn compiled() !== null;\n}\n\n/** What the engine needs from a prepared spot. */\nexport interface EngineInput {\n\treadonly tree: Tree;\n\treadonly runouts: Runouts;\n\treadonly players: readonly [PlayerIndex, PlayerIndex];\n\treadonly layout: Layout;\n\treadonly active: ActiveLists;\n\treadonly hands: HandSpace;\n\treadonly runoutWeight: Float64Array;\n\treadonly chipScale: number;\n\t/** Chance sampling's layout, for `Approximations.chanceSampling`; unset for none. */\n\treadonly sampling?: SamplingPlan;\n\t/** Bytes left unused below the layout, rounded up to 16; tests set it to place every pointer past 2 GiB. */\n\treadonly lowBytes?: number;\n\t/**\n\t * 16-bit or compact storage, run by the storage engine `source` holds;\n\t * unset for 32-bit storage on the default engine. `quantised` keeps\n\t * the nodes before `compact.from` (all of them without `compact`) at 16\n\t * bits, as `precision: 'i16'` does.\n\t */\n\treadonly storage?: { readonly source: WasmStorage; readonly quantised: boolean; readonly compact: CompactPlan | null };\n}\n\n/** Compact storage's arrays, per chunk, as `Context` holds them; views onto the engine's memory. */\nexport interface EngineCompact {\n\treadonly regret: (Int8Array | Float32Array)[];\n\treadonly handShift: Uint8Array[] | null;\n\treadonly sum: Uint8Array[] | null;\n\treadonly sumShift: Uint8Array[] | null;\n\treadonly scale: Float64Array | null;\n}\n\n/** A running engine. */\nexport interface Engine {\n\t/** The accumulators, as views onto the engine's memory: 32-bit, or 16-bit with `EngineInput.storage`. */\n\treadonly regret: RegretStore;\n\treadonly strategySum: SumStore;\n\t/** With 16-bit storage, the per-block scales `Context.regretScale` and `sumScale` hold; else null. */\n\treadonly regretScale: Float64Array | null;\n\treadonly sumScale: Float64Array | null;\n\t/** With compact storage, its arrays; else null. */\n\treadonly compact: EngineCompact | null;\n\t/** Chance sampling's state, as views onto the engine's memory; null without sampling. */\n\treadonly sampling: { baseline: Float32Array; lastWalk: Int32Array; lastUpdate: Int32Array } | null;\n\t/** With shared storage, `Context.discounted` as a view onto the engine's memory; else null. */\n\treadonly discounted: Int32Array | null;\n\t/** Install as the solver's root traversal; `dcfr` picks the update rule. */\n\troot(dcfr: boolean): RootTraversal;\n\t/** Release worker threads, if any. */\n\tclose(): void;\n\t/** Threads doing the work, this one included. */\n\treadonly threads: number;\n}\n\n/** What an engine worker needs; see src/engine-worker.ts. */\nexport interface EngineWorkerSetup {\n\treadonly memory: unknown;\n\treadonly module: unknown;\n\treadonly header: number;\n\treadonly maxActions: number;\n\treadonly exchange: readonly [number, number, number, number];\n\treadonly shard: readonly [number, number, number];\n\treadonly entryNodes: Int32Array;\n\treadonly rootMe: number;\n\treadonly rootOpp: number;\n\treadonly partial: number;\n\treadonly stride: number;\n\treadonly control: SharedArrayBuffer;\n\treadonly settings: SharedArrayBuffer;\n\t/** With shared storage: where the discount marks, the block table and the weighted nodes (or 0) sit. */\n\treadonly shared?: readonly [number, number, number];\n\t/** Set for the storage engine, whose updates need the iteration on every walk. */\n\treadonly storage?: boolean;\n\t/**\n\t * With chance sampling, `setSampling`'s arguments as the main thread\n\t * passed them: its state is in the shared memory, and each thread walks\n\t * and marks only its own runouts' deals.\n\t */\n\treadonly sampling?: SamplingArgs;\n}\n\n/** `EngineExports.setSampling`'s arguments, in order. */\nexport type SamplingArgs = Parameters<EngineExports['setSampling']>;\n\n/** How a pool starts its workers; the platform layer supplies it. */\nexport type SpawnEngineWorker = (setup: EngineWorkerSetup, onError: (error: Error) => void) => { terminate(): void };\n\n/** The most memory the engine lays out: just under wasm32's 4 GB. */\nconst MAX_MEMORY = 0xffff0000;\n\n/**\n * Control slots shared with engine workers. `failed` is set, never cleared,\n * once any thread's part of a step threw: the main thread waits in\n * `Atomics.wait` and so never sees a worker's error event while a step runs.\n */\nexport const ENGINE_CONTROL = { generation: 0, done: 1, command: 2, mode: 3, traverser: 4, ready: 5, failed: 6, size: 8 } as const;\n\n/**\n * Lay a spot out in a fresh memory and instantiate the engine over it, or\n * null where unavailable. With `pool`, the memory is shared and that many\n * threads split the runouts at the plan's round, as src/parallel.ts does for\n * the JavaScript engine.\n */\nexport function createEngine(\n\tinput: EngineInput,\n\tpool?: {\n\t\tplan: ShardPlan;\n\t\tthreads: number;\n\t\tspawn: SpawnEngineWorker;\n\t\t/** The shortest a step waits for the other threads; see `awaitThreads` in src/parallel.ts. */\n\t\tbackstopFloorMs?: number;\n\t},\n): Engine | null {\n\tconst shared = pool !== undefined;\n\tconst storage = input.storage ?? null;\n\tconst compiledModule = storage\n\t\t? compiledStorage(storage.source, shared ? 'shared' : 'plain')\n\t\t: compiledEngine(shared ? 'shared' : 'plain');\n\tif (!compiledModule || !wasm) return null;\n\tconst { tree, runouts, layout, active, hands } = input;\n\tconst compact = storage?.compact ?? null;\n\tconst quantised = storage?.quantised ?? false;\n\t// Its accumulators alone would pass wasm32's 4 GB, so no engine; checked\n\t// before anything is built. Such a layout is also the only kind that\n\t// holds offsets as Float64, which the engine's 32-bit offset table could\n\t// not take.\n\tconst width = quantised ? 2 : 4;\n\tconst compactBytes = !compact\n\t\t? 0\n\t\t: compact.float\n\t\t\t? layout.compactSlots * 4\n\t\t\t: (layout.compactSlots + (compact.perHand ? layout.compactHands : 0)) * (compact.sums ? 2 : 1);\n\tif (layout.totalSlots * width * 2 + compactBytes > MAX_MEMORY || !(layout.offset instanceof Int32Array)) return null;\n\tconst threads = pool ? pool.threads : 1;\n\n\tconst flatten = (parts: readonly Int32Array[]): [Int32Array, Int32Array] => {\n\t\tconst bases = new Int32Array(parts.length + 1);\n\t\tfor (let i = 0; i < parts.length; i++) bases[i + 1] = bases[i] + parts[i].length;\n\t\tconst flat = new Int32Array(bases[parts.length]);\n\t\tparts.forEach((part, i) => flat.set(part, bases[i]));\n\t\treturn [bases, flat];\n\t};\n\tconst [upRound, upStart] = flatten(hands.upStart);\n\tconst [childRound, childStart] = flatten(runouts.childStart);\n\tconst [orbitRound, orbitStart] = flatten(runouts.orbitStart);\n\tconst maxCount = Math.max(4, ...active.count);\n\tconst stride = Math.ceil(maxCount / 4) * 4;\n\tconst maxActions = Math.max(1, layout.maxActions);\n\tconst depths = treeDepth(tree) + 2;\n\tconst rowBytes = stride * 4;\n\tconst depthBytes = rowBytes * (3 + 2 * maxActions);\n\n\tconst pieces: { data: ArrayBufferView | null; bytes: number }[] = [];\n\tconst add = (data: ArrayBufferView | null, bytes = data ? data.byteLength : 0): number => {\n\t\tpieces.push({ data, bytes: Math.ceil(Math.max(bytes, 4) / 16) * 16 });\n\t\treturn pieces.length - 1;\n\t};\n\t// Shared by every thread, in header order.\n\tconst common = [\n\t\tadd(tree.kind), add(tree.round), add(Uint8Array.from(tree.player, (p) => (p < 0 ? 255 : p))), add(tree.firstEdge),\n\t\tadd(tree.numEdges), add(tree.edgeChild), add(tree.payoff), add(layout.offset), add(layout.rowStart),\n\t\tadd(active.roundBase), add(active.start), add(Int32Array.from(active.count)), add(active.cardA), add(active.cardB),\n\t\tadd(active.strength), add(active.packed), add(Float32Array.from(active.multiplicity)), add(active.memberStart),\n\t\tadd(active.memberA), add(active.memberB), add(upRound), add(upStart), add(hands.up),\n\t\tadd(hands.sameStart), add(hands.same), add(childRound), add(childStart), add(orbitRound), add(orbitStart),\n\t\tadd(input.runoutWeight),\n\t\tadd(null, layout.totalSlots * width), // regret\n\t\tadd(null, layout.totalSlots * width), // strategy sums\n\t];\n\tconst REGRET = common[common.length - 2];\n\tconst SUMS = common[common.length - 1];\n\t// Each thread's own.\n\tconst own = Array.from({ length: threads }, () => ({\n\t\tbuffers: add(null, depths * depthBytes),\n\t\tcardSums: add(null, 52 * 8 + stride * 8),\n\t\trootMe: add(null, rowBytes),\n\t\trootOpp: add(null, rowBytes),\n\t\theader: add(null, 40 * 4),\n\t}));\n\t// The exchange between threads.\n\tconst entries = pool ? pool.plan.entryNodes.length : 0;\n\tconst entryIndexOf = pool ? add(pool.plan.entryIndexOf) : -1;\n\tconst reach = pool ? add(null, entries * 2 * rowBytes) : -1;\n\tconst values = pool ? add(null, entries * rowBytes) : -1;\n\tconst partials = pool ? add(null, (threads - 1) * entries * rowBytes) : -1;\n\t// Chance sampling, only when asked for.\n\tconst plan = input.sampling;\n\tconst sample = plan\n\t\t? {\n\t\t\t\tbaseOffset: add(plan.baseOffset), boardOffset: add(plan.boardOffset), walkOffset: add(plan.walkOffset),\n\t\t\t\tblockOffset: add(layout.blockOffset), baseline: add(null, plan.values * 4), lastWalk: add(null, plan.walks * 4),\n\t\t\t\tlastUpdate: add(null, plan.blocks * 4),\n\t\t\t}\n\t\t: null;\n\t// History sharing's once-an-iteration discount marks, only when storage is shared.\n\tconst share = layout.shared\n\t\t? {\n\t\t\t\tmarks: add(null, layout.blocks * 4),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : add(layout.blockOffset),\n\t\t\t\tweighted: layout.reachWeighted ? add(layout.reachWeighted) : -1,\n\t\t\t}\n\t\t: null;\n\t// 16-bit and compact storage's settings, scales and chunks, only on the storage engine.\n\tconst chunks = compact ? layout.chunkSlots.length : 0;\n\tconst stored = storage\n\t\t? {\n\t\t\t\tblock: add(null, 128),\n\t\t\t\tblockOffset: sample ? sample.blockOffset : share ? share.blockOffset : add(layout.blockOffset),\n\t\t\t\tregretScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tsumScale: quantised ? add(null, layout.blocks * 8) : -1,\n\t\t\t\tcompactChunk: compact ? add(layout.compactChunk) : -1,\n\t\t\t\thandOffset: compact ? add(Int32Array.from(layout.handOffset!)) : -1,\n\t\t\t\ttables: compact ? add(null, chunks * 4 * 5) : -1,\n\t\t\t\tregrets: layout.chunkSlots.map((slots) => add(null, slots * (compact!.float ? 4 : 1))),\n\t\t\t\tshifts: compact?.perHand ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tsums: compact?.sums ? layout.chunkSlots.map((slots) => add(null, slots)) : [],\n\t\t\t\tsumShifts: compact?.sums ? layout.chunkHands.map((count) => add(null, count)) : [],\n\t\t\t\tcompactScale: compact && !compact.perHand && !compact.float ? add(null, layout.blocks * 8) : -1,\n\t\t\t}\n\t\t: null;\n\n\tconst offsets: number[] = [];\n\tlet total = 64 + Math.ceil(Math.max(input.lowBytes ?? 0, 0) / 16) * 16;\n\tfor (const piece of pieces) {\n\t\toffsets.push(total);\n\t\ttotal += piece.bytes;\n\t}\n\tif (total > MAX_MEMORY) return null;\n\tconst pages = Math.ceil(total / 65536) + 1;\n\tconst memory = shared ? new wasm.Memory({ initial: pages, maximum: pages, shared: true }) : new wasm.Memory({ initial: pages });\n\tconst bytes = new Uint8Array(memory.buffer);\n\tpieces.forEach((piece, i) => {\n\t\tif (piece.data) bytes.set(new Uint8Array(piece.data.buffer, piece.data.byteOffset, piece.data.byteLength), offsets[i]);\n\t});\n\tfor (const mine of own) {\n\t\tconst head = new Uint32Array(memory.buffer, offsets[mine.header], 40);\n\t\tcommon.forEach((slot, i) => (head[i] = offsets[slot]));\n\t\thead[common.length] = offsets[mine.buffers];\n\t\thead[common.length + 1] = depthBytes;\n\t\thead[common.length + 2] = rowBytes;\n\t\thead[common.length + 3] = offsets[mine.cardSums];\n\t\thead[common.length + 4] = input.chipScale;\n\t\tif (stored) head[common.length + 5] = offsets[stored.block];\n\t}\n\tif (stored) {\n\t\tconst at = (slot: number): number => (slot >= 0 ? offsets[slot] : 0);\n\t\tconst block = new Uint32Array(memory.buffer, offsets[stored.block], 20);\n\t\tblock.set([\n\t\t\tquantised ? 1 : 0, compact ? compact.from : 255, !compact ? 0 : compact.float ? 3 : compact.perHand ? 1 : 2,\n\t\t\tcompact?.sums ? 1 : 0, compact?.stochastic ? 1 : 0, compact?.steps ?? 127,\n\t\t\tat(stored.regretScale), at(stored.sumScale), offsets[stored.blockOffset], at(stored.compactChunk),\n\t\t\tat(stored.handOffset),\n\t\t]);\n\t\tif (compact) {\n\t\t\t// Per chunk: where its regrets, hand scales, sums and sum scales sit, and its first slot.\n\t\t\tconst tables = offsets[stored.tables];\n\t\t\tconst table = new Uint32Array(memory.buffer, tables, chunks * 5);\n\t\t\tfor (let c = 0; c < chunks; c++) {\n\t\t\t\ttable[c] = offsets[stored.regrets[c]];\n\t\t\t\ttable[chunks + c] = stored.shifts.length ? offsets[stored.shifts[c]] : 0;\n\t\t\t\ttable[2 * chunks + c] = stored.sums.length ? offsets[stored.sums[c]] : 0;\n\t\t\t\ttable[3 * chunks + c] = stored.sumShifts.length ? offsets[stored.sumShifts[c]] : 0;\n\t\t\t\ttable[4 * chunks + c] = layout.chunkStart[c] >>> 0;\n\t\t\t}\n\t\t\tblock.set([tables, tables + chunks * 4, tables + chunks * 8, tables + chunks * 12, tables + chunks * 16, at(stored.compactScale)], 11);\n\t\t}\n\t}\n\t// The update rule's factors, as float64, which the storage engine reads before each walk.\n\tconst factors = stored ? new Float64Array(memory.buffer, offsets[stored.block] + 80, 4) : null;\n\n\tconst instance = new wasm.Instance(compiledModule, { env: { memory, abort: () => { throw new Error('engine abort'); } } });\n\tconst exports = instance.exports as unknown as EngineExports;\n\texports.init(offsets[own[0].header]);\n\texports.setMaxActions(maxActions);\n\tlet samplingViews: Engine['sampling'] = null;\n\tlet samplingArgs: SamplingArgs | null = null;\n\tif (plan && sample) {\n\t\tlet mask = 0;\n\t\tfor (let r = 0; r < plan.rounds.length; r++) if (plan.rounds[r]) mask |= 1 << r;\n\t\tsamplingArgs = [\n\t\t\tmask, plan.p, plan.every, plan.unbiased ? 1 : 0, plan.catchUp ? 1 : 0,\n\t\t\toffsets[sample.baseOffset], offsets[sample.boardOffset], offsets[sample.walkOffset],\n\t\t\toffsets[sample.baseline], offsets[sample.lastWalk], offsets[sample.lastUpdate], offsets[sample.blockOffset],\n\t\t];\n\t\tconst a = samplingArgs;\n\t\texports.setSampling(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11]);\n\t\tsamplingViews = {\n\t\t\tbaseline: new Float32Array(memory.buffer, offsets[sample.baseline], plan.values),\n\t\t\tlastWalk: new Int32Array(memory.buffer, offsets[sample.lastWalk], plan.walks),\n\t\t\tlastUpdate: new Int32Array(memory.buffer, offsets[sample.lastUpdate], plan.blocks),\n\t\t};\n\t}\n\n\tconst weightedAt = share && share.weighted >= 0 ? offsets[share.weighted] : 0;\n\tif (share) exports.setShared(offsets[share.marks], offsets[share.blockOffset], weightedAt);\n\tconst discounted = share ? new Int32Array(memory.buffer, offsets[share.marks], layout.blocks) : null;\n\n\tconst regret: RegretStore = quantised\n\t\t? new Int16Array(memory.buffer, offsets[REGRET], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[REGRET], layout.totalSlots);\n\tconst strategySum: SumStore = quantised\n\t\t? new Uint16Array(memory.buffer, offsets[SUMS], layout.totalSlots)\n\t\t: new Float32Array(memory.buffer, offsets[SUMS], layout.totalSlots);\n\tconst scaleView = (slot: number): Float64Array | null =>\n\t\tslot >= 0 ? new Float64Array(memory.buffer, offsets[slot], layout.blocks) : null;\n\tconst compactViews: EngineCompact | null = stored && compact\n\t\t? {\n\t\t\t\tregret: stored.regrets.map((slot, c) =>\n\t\t\t\t\tcompact.float\n\t\t\t\t\t\t? new Float32Array(memory.buffer, offsets[slot], layout.chunkSlots[c])\n\t\t\t\t\t\t: new Int8Array(memory.buffer, offsets[slot], layout.chunkSlots[c]),\n\t\t\t\t),\n\t\t\t\thandShift: compact.perHand ? stored.shifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tsum: compact.sums ? stored.sums.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkSlots[c])) : null,\n\t\t\t\tsumShift: compact.sums ? stored.sumShifts.map((slot, c) => new Uint8Array(memory.buffer, offsets[slot], layout.chunkHands[c])) : null,\n\t\t\t\tscale: scaleView(stored.compactScale),\n\t\t\t}\n\t\t: null;\n\tconst me = new Float32Array(memory.buffer, offsets[own[0].rootMe], stride);\n\tconst opp = new Float32Array(memory.buffer, offsets[own[0].rootOpp], stride);\n\tconst result = new Float64Array(COMBOS);\n\tconst rootList = (player: 0 | 1): [number, number] => {\n\t\tconst slot = active.roundBase[0] * 2 + player;\n\t\treturn [active.start[slot], active.count[slot]];\n\t};\n\tconst settingsFor = (mode: number, iterWeight: number, dcfr: boolean): [number, number, number, number, number] => {\n\t\tif (mode === Mode.Train && dcfr) {\n\t\t\tconst { keepPositive, keepNegative, keepSum } = dcfrFactors(iterWeight);\n\t\t\treturn [keepPositive, keepNegative, keepSum, 1, 0];\n\t\t}\n\t\treturn [1, 1, 1, iterWeight, dcfr ? 0 : 1];\n\t};\n\n\t// Threads: workers over the same memory, each with its own header.\n\tlet control: Int32Array | null = null;\n\tlet settings: Float64Array | null = null;\n\tconst workers: { terminate(): void }[] = [];\n\tlet failure: Error | null = null;\n\tif (pool) {\n\t\tconst plan = pool.plan;\n\t\tconst controlBuffer = new SharedArrayBuffer(ENGINE_CONTROL.size * 4);\n\t\tconst settingsBuffer = new SharedArrayBuffer(8 * 8);\n\t\tcontrol = new Int32Array(controlBuffer);\n\t\tsettings = new Float64Array(settingsBuffer);\n\t\texports.setExchange(offsets[entryIndexOf], offsets[reach], offsets[values], stride);\n\t\tfor (let w = 1; w < threads; w++) {\n\t\t\tconst setup: EngineWorkerSetup = {\n\t\t\t\tmemory, module: compiledModule, header: offsets[own[w].header], maxActions,\n\t\t\t\texchange: [offsets[entryIndexOf], offsets[reach], offsets[values], stride],\n\t\t\t\tshard: [plan.round, plan.bounds[w], plan.bounds[w + 1]],\n\t\t\t\tentryNodes: plan.entryNodes,\n\t\t\t\trootMe: offsets[own[w].rootMe], rootOpp: offsets[own[w].rootOpp],\n\t\t\t\tpartial: offsets[partials] + (w - 1) * entries * rowBytes,\n\t\t\t\tstride, control: controlBuffer, settings: settingsBuffer,\n\t\t\t\t...(share ? { shared: [offsets[share.marks], offsets[share.blockOffset], weightedAt] as const } : {}),\n\t\t\t\t...(stored ? { storage: true } : {}),\n\t\t\t\t...(samplingArgs ? { sampling: samplingArgs } : {}),\n\t\t\t};\n\t\t\tworkers.push(pool.spawn(setup, (error) => {\n\t\t\t\tfailure ??= error;\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.ready, threads);\n\t\t\t\tAtomics.add(control!, ENGINE_CONTROL.done, threads);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.done);\n\t\t\t\tAtomics.notify(control!, ENGINE_CONTROL.ready);\n\t\t\t}));\n\t\t}\n\t\t// A worker that fails to start reports it by an event, which cannot\n\t\t// be delivered while this thread waits here, so the wait is bounded.\n\t\tconst deadline = Date.now() + WORKER_START_MS;\n\t\tfor (;;) {\n\t\t\tconst ready = Atomics.load(control, ENGINE_CONTROL.ready);\n\t\t\tif (ready >= threads - 1 || failure) break;\n\t\t\tif (Date.now() > deadline) failure = new Error(WORKER_START_ERROR);\n\t\t\telse Atomics.wait(control, ENGINE_CONTROL.ready, ready, 20);\n\t\t}\n\t\tif (failure) {\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t\tthrow failure;\n\t\t}\n\t}\n\n\tconst failed = (): Error | null =>\n\t\tfailure ?? (control && Atomics.load(control, ENGINE_CONTROL.failed) ? new Error(THREAD_FAILED_ERROR) : null);\n\n\t// The iteration a step is for, and its rule, which shared storage's threads need.\n\tlet iteration = 0;\n\tlet dcfrRule = 0;\n\tconst run = (asked: number, traverser: 0 | 1, iterWeight: number, dcfr: boolean): Float64Array => {\n\t\t// Once any thread has failed, so does every step after, before it\n\t\t// touches anything.\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\t// The engine knows three modes; the current profile is its Train\n\t\t// with updates off.\n\t\tconst apply = asked === Mode.Current ? 0 : 1;\n\t\tconst mode = asked === Mode.Current ? Mode.Train : asked;\n\t\tfor (const player of [0, 1] as const) {\n\t\t\tconst [from, count] = rootList(player);\n\t\t\tconst into = player === traverser ? me : opp;\n\t\t\tconst weights = input.players[player].weights;\n\t\t\tfor (let i = 0; i < count; i++) into[i] = weights[active.list[from + i]];\n\t\t}\n\t\tconst [positive, negative, sum, weight, clamp] = settingsFor(mode, iterWeight, dcfr);\n\t\titeration = mode === Mode.Train ? iterWeight : 0;\n\t\tdcfrRule = dcfr ? 1 : 0;\n\t\tif (plan || share || stored) exports.setIteration(iteration, dcfrRule);\n\t\t// CFR+ at 16 bits or compact floors a negative regret, as `updateQuantised`\n\t\t// and `updateCompact` do (one only a warm start could bring); 32-bit storage keeps it.\n\t\tfactors?.set([positive, mode === Mode.Train && !dcfr ? 0 : negative, sum, weight]);\n\t\tlet at: number;\n\t\tif (!pool) {\n\t\t\tif (apply === 0) exports.setPhase(0, 0);\n\t\t\ttry {\n\t\t\t\tat = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\t\t} finally {\n\t\t\t\tif (apply === 0) exports.setPhase(0, 1);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tat = runThreaded(mode, traverser, apply, positive, negative, sum, weight, clamp);\n\t\t\t} catch (error) {\n\t\t\t\t// This thread's own part may have thrown with the workers still\n\t\t\t\t// walking; no later step may run over them.\n\t\t\t\tAtomics.store(control!, ENGINE_CONTROL.failed, 1);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tconst [, count] = rootList(traverser);\n\t\tconst values32 = new Float32Array(memory.buffer, at, count);\n\t\tfor (let i = 0; i < count; i++) result[i] = values32[i];\n\t\treturn result;\n\t};\n\n\t/** One threaded traversal, returning where the root values are. */\n\tconst runThreaded = (\n\t\tmode: number, traverser: 0 | 1, apply: number,\n\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t): number => {\n\t\tconst plan = pool!.plan;\n\t\t// Collect: walk above the split, recording what the workers need.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(1, 0);\n\t\texports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp);\n\t\t// Every thread walks its slice of the split round.\n\t\tsettings!.set([positive, negative, sum, weight, clamp, apply, iteration, dcfrRule]);\n\t\tAtomics.store(control!, ENGINE_CONTROL.done, 0);\n\t\tAtomics.store(control!, ENGINE_CONTROL.mode, mode);\n\t\tAtomics.store(control!, ENGINE_CONTROL.traverser, traverser);\n\t\tAtomics.store(control!, ENGINE_CONTROL.command, 0);\n\t\tAtomics.add(control!, ENGINE_CONTROL.generation, 1);\n\t\tAtomics.notify(control!, ENGINE_CONTROL.generation);\n\t\tconst dispatched = performance.now();\n\t\texports.setShard(plan.round, plan.bounds[0], plan.bounds[1]);\n\t\texports.setPhase(0, apply);\n\t\tconst valueView = new Float32Array(memory.buffer, offsets[values], entries * stride);\n\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\tconst slot = offsets[reach] + entry * 2 * rowBytes;\n\t\t\tconst out = exports.runChance(mode, traverser, plan.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp) >>> 0;\n\t\t\tvalueView.set(new Float32Array(memory.buffer, out, stride), entry * stride);\n\t\t}\n\t\t// A thread whose walk throws says so in `failed` and counts itself\n\t\t// done, as its error event cannot reach this thread while it waits.\n\t\t// One killed without unwinding does neither, hence the backstop.\n\t\tfailure ??= awaitThreads(\n\t\t\tcontrol!, ENGINE_CONTROL.done, threads - 1, dispatched, pool!.backstopFloorMs, () => failure !== null,\n\t\t);\n\t\tconst dead = failed();\n\t\tif (dead) throw dead;\n\t\tconst partialView = new Float32Array(memory.buffer, offsets[partials], (threads - 1) * entries * stride);\n\t\tfor (let w = 0; w < threads - 1; w++) {\n\t\t\tfor (let i = 0; i < entries * stride; i++) valueView[i] += partialView[w * entries * stride + i];\n\t\t}\n\t\t// Finish above the split from the totals, now applying updates\n\t\t// unless this is a current-profile read.\n\t\texports.setShard(plan.round, 0, 0);\n\t\texports.setPhase(2, apply);\n\t\tconst at = exports.run(mode, traverser, offsets[own[0].rootMe], offsets[own[0].rootOpp], positive, negative, sum, weight, clamp) >>> 0;\n\t\texports.setPhase(0, 1);\n\t\texports.setShard(-1, 0, 0);\n\t\treturn at;\n\t};\n\n\treturn {\n\t\tregret,\n\t\tstrategySum,\n\t\tregretScale: stored ? scaleView(stored.regretScale) : null,\n\t\tsumScale: stored ? scaleView(stored.sumScale) : null,\n\t\tcompact: compactViews,\n\t\tsampling: samplingViews,\n\t\tdiscounted,\n\t\tthreads,\n\t\troot(dcfr) {\n\t\t\treturn (mode, traverser, iterWeight) => run(mode, traverser, iterWeight, dcfr);\n\t\t},\n\t\tclose() {\n\t\t\tif (!control) return;\n\t\t\tAtomics.store(control, ENGINE_CONTROL.command, 1);\n\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\tfor (const worker of workers) worker.terminate();\n\t\t},\n\t};\n}\n\n/**\n * The engine's exports. A pointer one returns is a wasm32 `usize`, which\n * JavaScript receives as a signed 32-bit integer: read it with `>>> 0`, or\n * any address past 2 GiB comes back negative (#62).\n */\nexport interface EngineExports {\n\tinit(header: number): void;\n\tsetMaxActions(count: number): void;\n\tsetShard(round: number, start: number, end: number): void;\n\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\tsetPhase(phase: number, apply: number): void;\n\tsetSampling(\n\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t): void;\n\tsetIteration(t: number, dcfr: number): void;\n\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\trun(mode: number, traverser: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n\trunChance(mode: number, traverser: number, node: number, me: number, opp: number, positive: number, negative: number, sum: number, weight: number, clamp: number): number;\n}\n","/**\n * One thread of a WebAssembly solve: the loop every engine worker runs.\n *\n * Purpose: walk this thread's slice of the runouts at the split round, over\n * the memory every thread shares, each time the main thread signals, until it\n * says exit. The protocol is src/parallel.ts's: the main thread collects the\n * reach each entry needs, every thread walks its slice from each entry, the\n * main thread adds the slices up and finishes. All of it happens in shared\n * WebAssembly memory, so nothing is copied between threads but a few numbers\n * of control.\n *\n * Node runs it from `engine-worker.ts`. The browser build has no file to\n * start a worker from, so `platform/browser.ts` ships this function as its\n * own source text (`Function.prototype.toString`) inside a Blob worker. That\n * is why it must stay self-contained: no imports, no reference to anything\n * outside its body, no nested named functions (a bundler may wrap those in a\n * helper the worker would not have). The control slots are written out as\n * numbers for the same reason; a test pins them to `ENGINE_CONTROL`.\n */\n\nimport type { EngineWorkerSetup } from './engine.ts';\n\n/**\n * Serve one solve, returning once the main thread sends exit.\n * @param setup what `createEngine` hands each worker\n */\nexport function serveEngine(setup: EngineWorkerSetup): void {\n\t// ENGINE_CONTROL, inlined.\n\tconst GENERATION = 0;\n\tconst DONE = 1;\n\tconst COMMAND = 2;\n\tconst MODE = 3;\n\tconst TRAVERSER = 4;\n\tconst READY = 5;\n\tconst FAILED = 6;\n\tconst EXIT = 1;\n\n\tconst api = (globalThis as unknown as {\n\t\tWebAssembly: { Instance: new (module: unknown, imports: object) => { exports: Record<string, unknown> } };\n\t}).WebAssembly;\n\tconst memory = setup.memory as { buffer: SharedArrayBuffer };\n\tconst imports = {\n\t\tenv: {\n\t\t\tmemory,\n\t\t\tabort(): never {\n\t\t\t\tthrow new Error('engine abort');\n\t\t\t},\n\t\t},\n\t};\n\tconst engine = new api.Instance(setup.module, imports).exports as unknown as {\n\t\tinit(header: number): void;\n\t\tsetMaxActions(count: number): void;\n\t\tsetShard(round: number, start: number, end: number): void;\n\t\tsetExchange(entries: number, reach: number, values: number, stride: number): void;\n\t\tsetPhase(phase: number, apply: number): void;\n\t\tsetShared(marks: number, blockOffsets: number, weighted: number): void;\n\t\tsetSampling(\n\t\t\trounds: number, p: number, every: number, unbiased: number, catchUp: number,\n\t\t\tbaseOffsets: number, boardOffsets: number, walkOffsets: number,\n\t\t\tbaselines: number, lastWalks: number, lastUpdates: number, blockOffsets: number,\n\t\t): void;\n\t\tsetIteration(t: number, dcfr: number): void;\n\t\trunChance(\n\t\t\tmode: number, traverser: number, node: number, me: number, opp: number,\n\t\t\tpositive: number, negative: number, sum: number, weight: number, clamp: number,\n\t\t): number;\n\t};\n\tengine.init(setup.header);\n\tengine.setMaxActions(setup.maxActions);\n\tengine.setExchange(setup.exchange[0], setup.exchange[1], setup.exchange[2], setup.exchange[3]);\n\tengine.setShard(setup.shard[0], setup.shard[1], setup.shard[2]);\n\tengine.setPhase(0, 1);\n\tconst shared = setup.shared;\n\tif (shared) engine.setShared(shared[0], shared[1], shared[2]);\n\t// Chance sampling's state is in the shared memory, at the main thread's offsets.\n\tconst s = setup.sampling;\n\tif (s) engine.setSampling(s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11]);\n\t// Shared storage discounts by iteration, the storage engine's rounding\n\t// hashes it, and chance sampling picks deals and catches up by it.\n\tconst needsIteration = shared !== undefined || setup.storage === true || s !== undefined;\n\n\tconst control = new Int32Array(setup.control);\n\tconst settings = new Float64Array(setup.settings);\n\tconst entries = setup.entryNodes.length;\n\tconst rowBytes = setup.stride * 4;\n\tconst partials = new Float32Array(memory.buffer, setup.partial, entries * setup.stride);\n\tconst reach = setup.exchange[1];\n\n\t// Latch the generation before announcing readiness, so no dispatch is missed.\n\tlet generation = Atomics.load(control, GENERATION);\n\tAtomics.add(control, READY, 1);\n\tAtomics.notify(control, READY);\n\t// A solve that gave up before this thread started has already said exit.\n\tif (Atomics.load(control, COMMAND) === EXIT) return;\n\n\tfor (;;) {\n\t\tAtomics.wait(control, GENERATION, generation);\n\t\tgeneration = Atomics.load(control, GENERATION);\n\t\tif (Atomics.load(control, COMMAND) === EXIT) return;\n\t\tconst mode = Atomics.load(control, MODE);\n\t\tconst traverser = Atomics.load(control, TRAVERSER);\n\t\tconst positive = settings[0];\n\t\tconst negative = settings[1];\n\t\tconst sum = settings[2];\n\t\tconst weight = settings[3];\n\t\tconst clamp = settings[4];\n\t\ttry {\n\t\t\t// Off for a current-profile read, which updates nothing.\n\t\t\tengine.setPhase(0, settings[5]);\n\t\t\tif (needsIteration) engine.setIteration(settings[6], settings[7]);\n\t\t\tfor (let entry = 0; entry < entries; entry++) {\n\t\t\t\tconst slot = reach + entry * 2 * rowBytes;\n\t\t\t\tconst out = engine.runChance(\n\t\t\t\t\tmode, traverser, setup.entryNodes[entry], slot, slot + rowBytes, positive, negative, sum, weight, clamp,\n\t\t\t\t) >>> 0; // a usize, signed on its way out; see `EngineExports`\n\t\t\t\tpartials.set(new Float32Array(memory.buffer, out, setup.stride), entry * setup.stride);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// The main thread is blocked in Atomics.wait and cannot see this\n\t\t\t// thread's error event, so say so in shared memory (and count as\n\t\t\t// done, below). Then let the thread die: its engine is not to be trusted.\n\t\t\tAtomics.store(control, FAILED, 1);\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tAtomics.add(control, DONE, 1);\n\t\t\tAtomics.notify(control, DONE);\n\t\t}\n\t}\n}\n","/**\n * The browser build's engine threads: started ahead of time, borrowed by solves.\n *\n * Purpose: everything behind `enableThreads` (`poker-flopsolve/threads`), kept\n * out of `platform/browser.ts` so the main browser build carries none of it.\n * See that file for why the threads must be started before a solve.\n */\n\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { ENGINE_CONTROL } from '../engine.ts';\nimport { serveEngine } from '../engine-thread.ts';\n\n/** A spawned solver thread. */\ninterface WorkerHandle {\n\tterminate(): void;\n}\n\n/** The parts of the Web Worker API used here, typed locally: the project builds without DOM typings. */\ninterface WebWorker {\n\tpostMessage(message: unknown, transfer?: unknown[]): void;\n\tterminate(): void;\n\tonmessage: ((event: { data: unknown }) => void) | null;\n\tonerror: ((event: { message?: string; preventDefault?(): void }) => void) | null;\n}\n\ninterface MessagePortLike {\n\tpostMessage(message: unknown): void;\n}\n\ninterface BrowserGlobals {\n\tWorker?: new (url: string) => WebWorker;\n\tMessageChannel?: new () => { port1: MessagePortLike; port2: unknown };\n\tBlob?: new (parts: string[], options: { type: string }) => object;\n\tURL: { createObjectURL(blob: object): string; revokeObjectURL(url: string): void };\n\tcrossOriginIsolated?: boolean;\n\tnavigator?: { hardwareConcurrency?: number };\n\tWebAssembly?: { Memory: new (descriptor: { initial: number; maximum: number; shared: boolean }) => object };\n}\n\n/** One pre-started engine thread. */\ninterface Thread {\n\treadonly worker: WebWorker;\n\t/**\n\t * Where its solves are posted. A message posted on the Worker object\n\t * itself does not reach a running child while the parent is blocked in\n\t * `Atomics.wait` (Chromium), and a solve blocks right after posting; a\n\t * transferred MessagePort delivers regardless.\n\t */\n\treadonly port: MessagePortLike;\n\tbusy: boolean;\n}\n\n/** Where the pool is published on `globalThis`. */\nexport const THREADS_KEY = Symbol.for('poker-flopsolve.browser-threads');\n\n/** What the main build sees of the pool. */\nexport interface ThreadProvider {\n\tidle(): number;\n\ttotal(): number;\n\tspawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle;\n}\n\ntype Holder = Record<symbol, (ThreadProvider & { threads: Thread[] }) | undefined>;\n\n/** The engine threads started so far, shared by every copy of this module. */\nfunction pool(): Thread[] {\n\tconst holder = globalThis as unknown as Holder;\n\tholder[THREADS_KEY] ??= {\n\t\tthreads: [],\n\t\tidle: () => idleThreads(),\n\t\ttotal: () => pool().length,\n\t\tspawn: (setup, onError) => spawn(setup, onError),\n\t};\n\treturn holder[THREADS_KEY]!.threads;\n}\n\nfunction idleThreads(): number {\n\treturn pool().filter((thread) => !thread.busy).length;\n}\n\n/** Stop a thread for good and forget it. */\nfunction drop(thread: Thread): void {\n\tthread.worker.terminate();\n\tthread.busy = true;\n\tconst threads = pool();\n\tconst at = threads.indexOf(thread);\n\tif (at >= 0) threads.splice(at, 1);\n}\n\n/** `ENGINE_CONTROL.command`'s value that ends a thread's solve. */\nconst COMMAND_EXIT = 1;\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nfunction spawn(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst thread = pool().find((candidate) => !candidate.busy);\n\tif (!thread) throw new Error('No idle engine thread; call enableThreads() from poker-flopsolve/threads first');\n\tthread.busy = true;\n\tthread.worker.onerror = (event) => {\n\t\tevent.preventDefault?.();\n\t\tdrop(thread);\n\t\tonError(new Error(`Engine thread failed: ${event.message ?? 'unknown error'}`));\n\t};\n\tthread.port.postMessage(setup);\n\tconst control = new Int32Array(setup.control);\n\tlet released = false;\n\treturn {\n\t\tterminate() {\n\t\t\t// A run may be closed twice; by then the thread may serve another.\n\t\t\tif (released) return;\n\t\t\treleased = true;\n\t\t\tif (!pool().includes(thread)) return;\n\t\t\t// A solve a thread failed: its error event is still queued, and\n\t\t\t// would fail whichever solve borrowed the thread next. Which thread\n\t\t\t// failed is not recorded, so every one of that solve's goes;\n\t\t\t// `prepareThreads` starts replacements.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.failed) !== 0) {\n\t\t\t\tdrop(thread);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// Whether this solve finished or gave up on starting, tell the\n\t\t\t// thread its solve is over: it returns to waiting for the next\n\t\t\t// setup, having started this one or not (serveEngine checks for\n\t\t\t// exit before it first waits). A thread that died is dropped by\n\t\t\t// its error handler instead.\n\t\t\tif (Atomics.load(control, ENGINE_CONTROL.command) !== COMMAND_EXIT) {\n\t\t\t\tAtomics.store(control, ENGINE_CONTROL.command, COMMAND_EXIT);\n\t\t\t\tAtomics.add(control, ENGINE_CONTROL.generation, 1);\n\t\t\t\tAtomics.notify(control, ENGINE_CONTROL.generation);\n\t\t\t}\n\t\t\tthread.busy = false;\n\t\t\tthread.worker.onerror = () => drop(thread);\n\t\t},\n\t};\n}\n\n/** Why threads cannot run here, or null if they can. */\nexport function threadsUnavailableReason(): string | null {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tif (typeof g.Worker !== 'function' || typeof g.Blob !== 'function' || typeof g.MessageChannel !== 'function') {\n\t\treturn 'no Web Workers here';\n\t}\n\tif (g.crossOriginIsolated !== true) {\n\t\treturn 'the page is not cross-origin isolated (serve it with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp)';\n\t}\n\tif (typeof SharedArrayBuffer !== 'function') return 'no SharedArrayBuffer here';\n\ttry {\n\t\t// Throws where blocking is not allowed: a page's main thread.\n\t\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 1, 0);\n\t} catch {\n\t\treturn 'Atomics.wait is not allowed on this thread; solve inside a Web Worker';\n\t}\n\ttry {\n\t\tnew g.WebAssembly!.Memory({ initial: 1, maximum: 1, shared: true });\n\t} catch {\n\t\treturn 'no shared WebAssembly memory here';\n\t}\n\treturn null;\n}\n\n/** How long a thread may take to start before it is given up on. */\nconst START_MS = 30_000;\n\nfunction startThread(url: string): Promise<Thread | null> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\treturn new Promise((resolve) => {\n\t\tlet worker: WebWorker;\n\t\ttry {\n\t\t\tworker = new g.Worker!(url);\n\t\t} catch {\n\t\t\tresolve(null);\n\t\t\treturn;\n\t\t}\n\t\tconst timer = setTimeout(() => {\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t}, START_MS);\n\t\tconst channel = new g.MessageChannel!();\n\t\tworker.onmessage = () => {\n\t\t\tclearTimeout(timer);\n\t\t\tworker.onmessage = null;\n\t\t\tworker.onerror = null;\n\t\t\tresolve({ worker, port: channel.port1, busy: false });\n\t\t};\n\t\tworker.postMessage(null, [channel.port2]);\n\t\tworker.onerror = (event) => {\n\t\t\tevent.preventDefault?.();\n\t\t\tclearTimeout(timer);\n\t\t\tworker.terminate();\n\t\t\tresolve(null);\n\t\t};\n\t});\n}\n\n/**\n * Start engine threads so that solves can use up to `count` threads, this one\n * included, and resolve to how many a solve can use now. Threads already\n * started are kept; idle ones beyond `count` are stopped, so `prepareThreads(1)`\n * stops every thread no open run is holding. Resolves to 1 where threads cannot run; see\n * {@link threadsUnavailableReason}.\n * @param count threads wanted, this one included; defaults to `navigator.hardwareConcurrency`\n */\nexport function prepareThreads(count?: number): Promise<number> {\n\t// One call at a time, so two calls in a row cannot both start the missing threads.\n\tconst next = pending.then(() => resize(count));\n\tpending = next.catch(() => undefined);\n\treturn next;\n}\n\nlet pending: Promise<unknown> = Promise.resolve();\n\nasync function resize(count?: number): Promise<number> {\n\tconst g = globalThis as unknown as BrowserGlobals;\n\tconst wanted = Math.max(1, Math.floor(count ?? g.navigator?.hardwareConcurrency ?? 1));\n\tconst threads = pool();\n\tfor (let i = threads.length - 1; i >= 0 && threads.length > wanted - 1; i--) {\n\t\tif (!threads[i].busy) drop(threads[i]);\n\t}\n\tconst missing = wanted - 1 - threads.length;\n\tif (missing > 0 && threadsUnavailableReason() === null) {\n\t\t// The worker is this module's own loop, as source: there is no file\n\t\t// to point a worker at that every bundler would ship.\n\t\tconst source =\n\t\t\t`const serveEngine = ${serveEngine.toString()};\\n` +\n\t\t\t'onmessage = (event) => {\\n' +\n\t\t\t'\\tevent.ports[0].onmessage = (solve) => serveEngine(solve.data);\\n' +\n\t\t\t\"\\tpostMessage('ready');\\n\" +\n\t\t\t'};\\n';\n\t\tconst url = g.URL.createObjectURL(new g.Blob!([source], { type: 'text/javascript' }));\n\t\ttry {\n\t\t\tconst started = await Promise.all(Array.from({ length: missing }, () => startThread(url)));\n\t\t\tfor (const thread of started) if (thread) threads.push(thread);\n\t\t} finally {\n\t\t\tg.URL.revokeObjectURL(url);\n\t\t}\n\t}\n\treturn threadsUnavailableReason() === null ? Math.min(wanted, 1 + idleThreads()) : 1;\n}\n","/**\n * Browser platform.\n *\n * Purpose: stand in for `node.ts` in a browser build, with the same exports.\n *\n * Out of the box the browser build is single-threaded: no worker threads, no\n * SharedArrayBuffer, and so no cross-origin isolation headers needed on the\n * page. Run the solve inside a Web Worker to keep the page responsive; see\n * `examples/browser-worker.ts`.\n *\n * Threads are opt-in, through `enableThreads` in `poker-flopsolve/threads`\n * (`prepareThreads` here). A browser starts a Web Worker only asynchronously —\n * a worker spawned and then waited on with `Atomics.wait` never starts, as\n * the thread that would start it is the one blocked — while a solve is\n * synchronous. So the workers are started ahead of time, once, and wait idle\n * between solves; a solve with `workers: n` hands n − 1 of them its setup and\n * takes them back on `close()`. Only the WebAssembly engine is threaded here:\n * its workers share the engine's memory exactly as Node's do and run the same\n * loop (`serveEngine`), so a fixed thread count gives the same answer as Node\n * at that count.\n *\n * The pool lives in `browser-threads.ts` and is found through `globalThis`\n * under a registered symbol, so the threads entry and the main build share\n * it even when bundled separately, and the main build carries none of it.\n */\n\nimport type { WorkerSetup } from '../parallel.ts';\nimport type { EngineWorkerSetup } from '../engine.ts';\nimport { compiledEngine } from '../engine.ts';\nimport type { ThreadProvider } from './browser-threads.ts';\nimport { THREADS_KEY } from './browser-threads.ts';\n\nexport { prepareThreads, threadsUnavailableReason } from './browser-threads.ts';\n\n/** Which build this is. */\nexport const PLATFORM = 'browser';\n\n/**\n * Default ceiling on solver storage. A tab gets far less memory than a Node\n * process, so an accidental flop solve fails fast with a clear message rather\n * than taking the tab down.\n */\nexport const DEFAULT_MAX_BYTES = 512 * 1024 * 1024;\n\n/** A spawned solver thread. */\nexport interface WorkerHandle {\n\tterminate(): void;\n}\n\n/** The engine threads `prepareThreads` started, if any. */\nfunction provider(): ThreadProvider | undefined {\n\treturn (globalThis as unknown as Record<symbol, ThreadProvider | undefined>)[THREADS_KEY];\n}\n\n/**\n * The most threads a solve can use now: one, plus the idle engine threads\n * when the WebAssembly engine is to run and can run over shared memory here.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadLimit(engine: boolean): number {\n\tconst threads = provider();\n\tif (!engine || !threads || threads.idle() === 0) return 1;\n\treturn compiledEngine('shared') ? 1 + threads.idle() : 1;\n}\n\n/** One, plus every idle engine thread `prepareThreads` started. */\nexport function defaultWorkerCount(): number {\n\treturn 1 + (provider()?.idle() ?? 0);\n}\n\n/**\n * Why a solve gets fewer threads than it asked for, for the one warning.\n * @param engine whether the WebAssembly engine is to run\n */\nexport function threadAdvice(engine: boolean): string {\n\tif (!provider()) return 'call enableThreads() from poker-flopsolve/threads first, in a cross-origin isolated Web Worker';\n\tif (!engine) return 'browser threads run only the WebAssembly engine (default engine, f32 precision)';\n\treturn 'the other threads are held by open runs; close() a run to free its threads';\n}\n\n/** Never called: the browser build threads only the WebAssembly engine; see `threadLimit`. */\nexport function spawnWorker(_setup: WorkerSetup, _onError: (error: Error) => void): WorkerHandle {\n\tthrow new Error('The browser build threads only the WebAssembly engine; use workers: 1 with this solve');\n}\n\n/**\n * Hand one idle engine thread a solve's setup.\n * @param setup what the thread needs to join the solve\n * @param onError called if the thread dies, so the solve can stop waiting on it\n */\nexport function spawnEngineWorker(setup: EngineWorkerSetup, onError: (error: Error) => void): WorkerHandle {\n\tconst threads = provider();\n\tif (!threads) throw new Error('No engine threads; call enableThreads() from poker-flopsolve/threads first');\n\treturn threads.spawn(setup, onError);\n}\n","/**\n * Opt-in threads for the browser build: `poker-flopsolve/threads`.\n *\n * Purpose: let a page split a solve across cores, as Node does, without the\n * main build depending on it. Nothing here runs unless it is imported and\n * called; a solve that never asks for threads is the same, bit for bit, as\n * one in a build without this entry.\n *\n * In a browser, call `enableThreads` once, inside a Web Worker on a\n * cross-origin isolated page, and await it before solving:\n *\n * import { createRun, defineSpot } from 'poker-flopsolve';\n * import { enableThreads } from 'poker-flopsolve/threads';\n * const threads = await enableThreads(); // 1 if the page cannot thread\n * const run = createRun(defineSpot(config), { workers: threads });\n *\n * In Node this resolves to the thread count straight away: Node starts\n * threads with each solve and needs no preparation.\n */\n\nimport { prepareThreads, threadsUnavailableReason } from './platform/node.ts';\n\n/**\n * Start engine threads so that solves can use up to `count` threads, the\n * calling one included, and resolve to how many they can use: 1 where the\n * page cannot thread (see {@link threadsUnavailable}).\n *\n * Threads stay started between solves; a solve borrows them with\n * `workers: n` and returns them on `close()`. Calling again with a smaller\n * count stops the idle surplus, so `enableThreads(1)` stops them all.\n *\n * @param count threads wanted, the calling one included; defaults to the\n * machine's core count (`navigator.hardwareConcurrency` in a browser)\n */\nexport function enableThreads(count?: number): Promise<number> {\n\treturn prepareThreads(count);\n}\n\n/**\n * Why threads cannot run here, or null if they can. In a browser they need\n * a cross-origin isolated page (`Cross-Origin-Opener-Policy: same-origin`\n * and `Cross-Origin-Embedder-Policy: require-corp`) and a Web Worker to\n * solve in, since a page's main thread may not block.\n */\nexport function threadsUnavailable(): string | null {\n\treturn threadsUnavailableReason();\n}\n"],"mappings":";AAyCA,IAAM,OAAQ,WAAoD;AAmJ3D,IAAM,iBAAiB,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,WAAW,GAAG,OAAO,GAAG,QAAQ,GAAG,MAAM,EAAE;;;AClKjH,SAAS,YAAY,OAAgC;AAE3D,QAAM,aAAa;AACnB,QAAM,OAAO;AACb,QAAM,UAAU;AAChB,QAAM,OAAO;AACb,QAAM,YAAY;AAClB,QAAM,QAAQ;AACd,QAAM,SAAS;AACf,QAAM,OAAO;AAEb,QAAM,MAAO,WAEV;AACH,QAAM,SAAS,MAAM;AACrB,QAAM,UAAU;AAAA,IACf,KAAK;AAAA,MACJ;AAAA,MACA,QAAe;AACd,cAAM,IAAI,MAAM,cAAc;AAAA,MAC/B;AAAA,IACD;AAAA,EACD;AACA,QAAM,SAAS,IAAI,IAAI,SAAS,MAAM,QAAQ,OAAO,EAAE;AAkBvD,SAAO,KAAK,MAAM,MAAM;AACxB,SAAO,cAAc,MAAM,UAAU;AACrC,SAAO,YAAY,MAAM,SAAS,CAAC,GAAG,MAAM,SAAS,CAAC,GAAG,MAAM,SAAS,CAAC,GAAG,MAAM,SAAS,CAAC,CAAC;AAC7F,SAAO,SAAS,MAAM,MAAM,CAAC,GAAG,MAAM,MAAM,CAAC,GAAG,MAAM,MAAM,CAAC,CAAC;AAC9D,SAAO,SAAS,GAAG,CAAC;AACpB,QAAM,SAAS,MAAM;AAC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