@margoengine/wfc 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,243 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/wfc
2
+
3
+ Import `margoengine/wfc` from the `margoengine` package, or `@margoengine/wfc` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Seeded 3D Wave Function Collapse with weighted entropy, six-direction adjacency, pinned cells and bounded restart attempts.
6
+
7
+ ```ts
8
+ import {WFC} from 'margoengine/wfc';
9
+ const generator = new WFC([4,4,4], [{neighbors: [[0],[0],[0],[0],[0],[0]]}]);
10
+ const cells = generator.solve(123);
11
+ ```
12
+
13
+ Tile IDs are 0..31; output is a flattened Uint8Array with X fastest, then Y, then Z. Directions are +X, -X, +Y, -Y, +Z, -Z. Adjacency must be reciprocal. solve(seed, pins, attempts, {signal}?) retries contradictions deterministically and throws when the bounded budget is exhausted. This is local WFC propagation with restart, not an exhaustive backtracking solver or a guaranteed connected-dungeon generator; use the optional constraints entry for connected layouts, required paths and count limits. Tile weights must have finite sums and weighted logarithms; overflowing arithmetic is rejected.
14
+
15
+ `signal` defaults to absent. Pre-abort throws the caller's exact reason before
16
+ changing `cells`; propagation and observation also check it. This method is
17
+ synchronous, so main-thread events cannot fire during solving. For responsive
18
+ cancellation use the existing `WFCWorkerSolve` from `/worker`, which terminates
19
+ active work on abort and supports the TypeScript and feature-local SIMD backends.
20
+
21
+ ```ts
22
+ import {WFC} from '@margoengine/wfc';
23
+ const solver = new WFC([4, 4, 4], [{neighbors: Array.from({length: 6}, () => [0])}]);
24
+ const controller = new AbortController();
25
+ const cells = solver.solve(123, [], 16, {signal: controller.signal});
26
+ console.log(cells.length);
27
+ ```
28
+
29
+ ## Overlapping model (`@margoengine/wfc/overlapping`, 2,457 B min+gzip)
30
+
31
+ Learns N x N patterns from a sample image and generates outputs in which every N x N window appears in the sample.
32
+
33
+ ```ts
34
+ import {OverlappingModel} from 'margoengine/wfc/overlapping';
35
+ // 0 floor, 1 wall, 2 door; any numbers work (palette indices, packed RGBA).
36
+ const rows = ['11111111', '10000101', '10000201', '11211111', '10000001', '11111111'];
37
+ const model = new OverlappingModel({data: rows.join('').split('').map(Number), width: 8, height: 6}, {N: 3, symmetry: 8});
38
+ const image = model.solve(64, 40, {seed: 7, periodic: false}); // Float64Array of sample values, X fastest
39
+ console.log(model.patterns, model.stats.backtracks, model.stats.attempts);
40
+ ```
41
+
42
+ Options: `N` 2..5, `periodicInput` (patterns wrap around the sample), `symmetry` 1..8 (rotations and reflections, in
43
+ Gumin's order); `solve` takes `seed`, `periodic` output, `backtracks` (per attempt, default 1000) and `attempts`
44
+ (default 4). Propagation is arc-consistent (supporter counts per cell, pattern and direction). On a contradiction the
45
+ latest choice is undone from the trail and forbidden in its cell (chronological backtracking); past the budget the
46
+ attempt restarts from scratch with the seed stream continuing; when the attempts run out `solve` throws. Every loop is
47
+ bounded by the budgets, so an unsatisfiable sample fails instead of hanging (the tests run one in a child process with a
48
+ timeout). A 7 x 7 maze sample with `symmetry: 1` fails every seed without backtracking and solves them all with it.
49
+ Limits: at most 4096 patterns, rejected during extraction before retaining a 4097th distinct pattern,
50
+ and `cells x patterns` <= 4,194,304 (memory: 18 bytes per cell and pattern); the
51
+ min-entropy scan is O(cells) per choice, fine to about 128 x 128; CPU only; works identically beside WebGPU and WebGL2 (tested in a real browser).
52
+ Example: `examples/overlapping.html`.
53
+
54
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
55
+
56
+ Build and unit tests: npm test --workspace @margoengine/wfc
57
+
58
+
59
+ ## Fixed entrances and floors
60
+
61
+ Overlapping pins use output pixel coordinates and original sample values. Every covering pattern is restricted before
62
+ search, including the final N-1 pixels and periodic seams; backtracking cannot undo those restrictions.
63
+
64
+ ```ts
65
+ import {OverlappingModel} from '@margoengine/wfc/overlapping';
66
+ const model = new OverlappingModel({data: [0,0,0,0], width: 2, height: 2}, {N: 2});
67
+ const image = model.solve(16, 12, {
68
+ seed: 7,
69
+ pins: [{position: [15, 0], value: 0}],
70
+ ground: {value: 0, rows: 2},
71
+ });
72
+ console.log(image[15], image.at(-1));
73
+ ```
74
+
75
+ Defaults: pins empty, ground absent, ground.rows 1, signal absent. Ground fixes the bottom image rows, and does not
76
+ forbid the value elsewhere. Pins and ground may coexist; conflicts or values absent from the sample exhaust the bounded
77
+ search and throw coded failed with a help link. Invalid coordinates/rows throw RangeError. A pre-aborted AbortSignal
78
+ throws its reason; synchronous checkpoints cannot receive new events while JavaScript owns the thread. No GPU resources
79
+ or shaders are used. Existing attempt/backtrack and memory limits apply. Generated binary/maze samples are stand-ins.
80
+ Heap/chunk backend selection and the paired Rust/Wasm SIMD measurement are documented below. Pattern extraction and the existing overlapping solver remain TypeScript.
81
+
82
+ ## Global constraints (`@margoengine/wfc/constraints`, 2,484 B min+gzip)
83
+
84
+ ```ts
85
+ import {ConstrainedWFC} from '@margoengine/wfc/constraints';
86
+ const ids = [0, 1]; // wall, walkable floor
87
+ const model = new ConstrainedWFC([4, 3, 1], ids.map(() => ({
88
+ neighbors: Array.from({length: 6}, () => ids),
89
+ })), {
90
+ connected: [1],
91
+ paths: [{from: [0, 0, 0], to: [3, 2, 0], tiles: [1]}],
92
+ counts: [{tiles: [1], min: 8, max: 8}],
93
+ });
94
+ const cells = model.solve({seed: 7}); // Uint16Array, X then Y then Z
95
+ console.log(cells[0], cells[11], model.stats.backtracks);
96
+ ```
97
+
98
+ Local reciprocal adjacency, group counts and potential reachability propagate together during chronological backtracking.
99
+ A returned layout satisfies every constraint. Connected means one nonempty six-neighbour component containing every cell
100
+ using that tile group. Each path forces its endpoints to its own walkable group and requires a six-neighbour route between
101
+ them. These are authored logical traversability rules; they do not infer avatar clearance, doors, jump physics or geometry.
102
+ No external validator, callback or caller repair is needed. Exhaustive binary 3x2 truth tables test satisfiable and
103
+ unsatisfiable combinations of counts, connectivity and corner paths; larger generated cases exercise backtracking.
104
+
105
+ Defaults: connected absent, paths/counts empty; count min 0, max cell count; solve seed 1, pins empty, backtracks 10,000
106
+ per attempt, attempts 4, signal absent. Counts group distinct tile IDs and include pinned/path endpoint cells. Input grids,
107
+ adjacency and constraint groups are copied. Limits: 1..4096 tile IDs, 1,000,000 cells, 16,777,216 cell/tile pairs;
108
+ Uint16 output removes the legacy root's 32-tile limit for this optional solver. Invalid inputs throw TypeError/RangeError;
109
+ unsatisfiable or budget-exhausted searches throw coded failed with a help link. Satisfiable inputs can exhaust the budget.
110
+ The entropy pick scans the grid; this entry does not promise fast large worlds. Domains and the undo trail scale with
111
+ cell/tile pairs; connectivity scratch scales with cells. CPU only, tested beside real WebGPU and WebGL2 contexts with
112
+ identical seeded output. AbortSignal checks are synchronous and cannot receive new events on the blocked thread.
113
+
114
+ ## Sockets and rotations (optional wfc/sockets, 776 B min+gzip)
115
+
116
+ ```ts
117
+ import {buildSocketTiles} from 'margoengine/wfc/sockets';
118
+ import {ConstrainedWFC} from 'margoengine/wfc/constraints';
119
+ const tiles = buildSocketTiles([
120
+ {sockets: ['road','road','air','air','air','air']},
121
+ {sockets: ['road','air','air','air','road','air']},
122
+ ]);
123
+ const cells = new ConstrainedWFC([4, 1, 4], tiles).solve({seed: 7});
124
+ const first = tiles[cells[0]];
125
+ console.log(first.source, first.rotation, cells.length);
126
+ ```
127
+
128
+ Six socket strings describe +X, -X, +Y, -Y, +Z, -Z. Opposite labels must be exactly equal; empty strings match too.
129
+ Labels represent orientation-independent connectors, not textured face patterns or gendered plugs. Default rotations
130
+ are four proper +Y-axis orientations; cube selects all 24 proper cube rotations, none selects identity. Identity is
131
+ first, followed by stable signed-axis enumeration. No reflections or symmetry deduplication. Each source weight
132
+ (default 1) is divided across its orientations, preserving total source frequency within floating-point rounding.
133
+ The quotient must remain positive in float64: a weight that rounds to zero after division by 4 or 24 is rejected
134
+ with RangeError. `Number.MIN_VALUE` is accepted with `rotations: 'none'`. Source weights at or below
135
+ `2 * Number.MIN_VALUE` for y or `12 * Number.MIN_VALUE` for cube round to zero per variant and are rejected;
136
+ `4 * Number.MIN_VALUE` and `24 * Number.MIN_VALUE`, respectively, split exactly into `Number.MIN_VALUE` variants.
137
+ Metadata gives the source index,
138
+ rotated sockets and a column-major 3x3 rotation to apply to geometry. Inputs are copied.
139
+
140
+ Up to 4096 expanded variants, checked before adding a source's orientations, Uint16 IDs through ConstrainedWFC;
141
+ legacy root WFC remains 32 IDs. Socket source arrays and all six string labels must be dense. Adjacency building
142
+ is O(variants squared), with six lists per variant; invalid inputs throw RangeError. Solver budgets and memory limits
143
+ still apply. Pure CPU, identical on WebGPU and WebGL2 pages. Generated 48-variant tests are stand-ins; no artist
144
+ asset compatibility claim. This entry builds rules only and imports no solver or rendering backend.
145
+
146
+ `npm run test:gpu --workspace @margoengine/wfc` runs the overlapping solver beside WebGPU and WebGL2. Its server resolves the repository root from the script location, so workspace execution uses the same imports, and teardown closes the browser and server together.
147
+
148
+ ## Large outputs and chunks (optional wfc/chunks, 3,647 B min+gzip)
149
+
150
+ ```ts
151
+ import {ChunkedWFC, HeapWFC} from 'margoengine/wfc/chunks';
152
+ const tiles = [0,1].map(() => ({neighbors: Array.from({length:6}, () => [0,1])}));
153
+ const large = await HeapWFC.create([192,192,1], tiles);
154
+ console.log(large.solve({seed:7}).length, large.backend);
155
+ using world = new ChunkedWFC([16,16,1], tiles, 7);
156
+ const left = await world.solveChunk([-1,0,0]);
157
+ const right = await world.solveChunk([0,0,0]);
158
+ console.log(left.length, right.length, world.size);
159
+ ```
160
+
161
+ HeapWFC uses indexed binary-heap selection, bitset propagation and fixed seeded per-cell tie keys. A domain change
162
+ updates one heap position in O(log cells), without stale heap entries. This is a new seed algorithm; root,
163
+ overlapping and constraints seed streams keep their previous behavior. Local adjacency and pins only; it uses
164
+ bounded restarts, without global counts/connectivity or chronological backtracking. Defaults: seed 1, attempts 4
165
+ (1..64), pins empty, signal absent. Grid limits: 1..4096 IDs, <=1,000,000 cells, <=16,777,216 cell/tile pairs.
166
+ Invalid inputs throw RangeError/TypeError; exhausted attempts throw coded failed with a help link.
167
+ A cell that still holds every tile (every cell at the start of an attempt) propagates one neighbour union gathered
168
+ once per solve, so the first pass costs six words per cell rather than a walk over all tiles; the legacy `WFC` also
169
+ reuses the full domain's entropy. Solutions, seeds and `stats` are unchanged:
170
+
171
+ ```ts
172
+ import {HeapWFC} from '@margoengine/wfc/chunks';
173
+
174
+ const all = Array.from({length: 8}, (_, t) => t);
175
+ const tiles = all.map((t) => ({weight: 1 + t, neighbors: Array.from({length: 6}, () => all)}));
176
+ const model = new HeapWFC([16, 16, 1], tiles); // weighted tiles stay on the TypeScript solver
177
+ const grid = model.solve({seed: 3});
178
+ console.log(grid.length, model.stats.decisions); // 256 256
179
+ ```
180
+ All WFC entries reject holes in dimensions, coordinates, pins, rules and constraint lists before search;
181
+ all three dimensions and their safe integer product are validated before grid allocation.
182
+
183
+ Constructor HeapWFC is synchronous TypeScript. Async HeapWFC.create defaults to backend auto: lazily loads the
184
+ feature's own Rust/Wasm SIMD artifact for <=32 unit-weight tiles, using new URL relative to the module; wider or
185
+ weighted sets use TypeScript. Explicit typescript forces JS; explicit wasm rejects ineligible sets or missing SIMD
186
+ with coded unsupported and a help link. Load accepts AbortSignal; network, response-body, local-file and
187
+ instantiation failures are coded failed with a help link and the original cause. Abort throws the exact signal
188
+ reason. Build inputs and
189
+ artifact hashes live in native/solver, rebuild with node packages/wfc/scripts/build-wasm.mjs (Rust wasm32 target).
190
+ No shared Wasm bundle, core/stage import or import-time loading. Both implementations perform the same local solve
191
+ and produce identical IDs for identical seeds; benchmark decision is recorded below. Browser WebGPU and WebGL2 use
192
+ the same CPU code. Synchronous solving checks cancellation but cannot receive new events while blocking its thread.
193
+ Wasm work statistics use 32-bit counters (wrap above 4,294,967,295); measured fixtures stay below that bound.
194
+
195
+ ChunkedWFC solves a one-cell halo constrained by all previously committed neighbouring cells, then commits only the
196
+ interior. Every successful seam satisfies the tile rules. Coordinates, world cell bounds and halo bounds must be safe
197
+ integers; negative and distant addresses work. Grid/pair limits include the halo (each dimension plus 2). Chunk seed
198
+ is the world seed mixed with all coordinate halves; generation is reproducible for the same solve order. Order can
199
+ change layouts, and arbitrary rules may make a later chunk impossible: it throws rather than editing old chunks.
200
+ There is no global playability guarantee across chunks. Calls must be serial; concurrent generation/clear throws
201
+ coded failed. Cached outputs are copies. Storage grows with visited chunks; clear, dispose and Symbol.dispose release
202
+ it. Failed or aborted calls commit nothing. The world seed defaults to 1; solveChunk takes backend auto, attempts 4 and
203
+ signal absent. No hidden eviction, caller-authored boundary rules or caller repair is required.
204
+
205
+ Rust/Wasm SIMD is selected for eligible sets because it was faster in every paired round on both the 192x192 open and 64x64x4 parity fixtures, with identical output hashes and work counts. The seven rounds interleave three runs per implementation and compare per-round minima. This is evidence from a loaded development machine, not a release speed claim; wider/weighted cases retain TypeScript because the measured Rust path supports only <=32 unit-weight IDs. See docs/whitepaper/results/batch-69-heap.json.
206
+
207
+ ## Worker solving (optional wfc/worker, 1,331 B min+gzip)
208
+
209
+ ```ts
210
+ import {WFCWorkerSolve} from 'margoengine/wfc/worker';
211
+ const tiles = [0,1].map(() => ({neighbors: Array.from({length:6}, () => [0,1])}));
212
+ const controller = new AbortController();
213
+ using job = new WFCWorkerSolve([64,64,1], tiles, {seed:7, signal:controller.signal});
214
+ const progress = (async () => {
215
+ for await (const work of job) document.body.dataset.wfcDecisions = String(work.decisions);
216
+ })();
217
+ const cells = await job.result;
218
+ await progress;
219
+ console.log(cells.length); // 4096. controller.abort(reason) terminates an active worker.
220
+ ```
221
+
222
+ One dedicated classic Web Worker runs the same HeapWFC algorithm and the same eligible Rust SIMD artifact as chunks.
223
+ Rules, dimensions and pins are structured-cloned; the resulting Uint16Array transfers back without a copy. Construction
224
+ starts the worker immediately. No grid validation, heap construction or search runs on the calling thread; cloning
225
+ large input rules still has a cost. Auto, typescript and wasm have the same selection rules as HeapWFC.create, preserving
226
+ its seed stream exactly. This entry solves local adjacency and pins; it does not run the overlapping/global solvers or
227
+ maintain a chunk cache. Existing grid, tile, pair and restart limits apply.
228
+
229
+ Defaults: seed 1, pins empty, attempts 4, backend auto, signal absent, timeout 60000 ms including startup/downloads.
230
+ Timeout must be an integer from 1 to 2147483647 ms. Progress is a single-consumer async iterable of actual cumulative
231
+ decisions, heap updates, intersections, current attempt and selected backend, emitted during both TS and synchronous
232
+ Wasm work and once at completion. It is not a percentage: restarts can revisit cells. Slow readers retain only the latest
233
+ snapshot, so memory stays bounded. Completion closes the stream; always await result to observe errors. Stopping progress
234
+ iteration leaves the solve running. Abort, timeout and dispose terminate the worker, remove listeners and close progress.
235
+ Abort rejects with the signal reason, timeout with coded timeout, disposal with coded disposed. Dispose/Symbol.dispose
236
+ are idempotent. Crashes, message and clone failures reject with coded failed; solver TypeError/RangeError and coded
237
+ errors survive transport. Coded errors carry a help link. A pre-aborted signal starts no worker.
238
+
239
+ Browser WebGPU and WebGL2 both run real solves while submitting rendered animation frames, with in-flight progress,
240
+ abort and synchronous parity checks. There is no GPU work in the solver and no shared-memory/isolation requirement.
241
+ Node/SSR imports are safe; construction throws coded unsupported there (use HeapWFC). CSP must allow the same-origin
242
+ worker asset and Wasm where selected. No Blob, eval or caller-authored worker is needed. The optional entry downloads
243
+ workers/wfc.js only when constructed, and wfc.wasm only for an eligible backend; it imports no rendering backend.
@@ -0,0 +1,37 @@
1
+ import type { EngineKernel, Mesh as MeshHandle } from '@margoengine/core';
2
+ import { type Mesh } from '@margoengine/core/extension';
3
+ /** A loaded glTF model, structurally compatible with gltf and gltf/pbr models. Resources stay caller-owned. */
4
+ export interface TileModel {
5
+ root: MeshHandle;
6
+ meshes: readonly MeshHandle[];
7
+ }
8
+ /** A solver ID maps to a source model and an orthogonal column-major 3x3 orientation (including reflections). */
9
+ export interface AssemblyVariant {
10
+ source: number;
11
+ rotation: readonly number[];
12
+ }
13
+ /** Grid placement defaults: unit spacing, zero origin, no parent and no cancellation signal. */
14
+ export interface AssemblyOptions {
15
+ spacing?: readonly number[];
16
+ origin?: readonly number[];
17
+ parent?: MeshHandle;
18
+ signal?: AbortSignal;
19
+ }
20
+ /** Owns the placed mesh handles, sharing template geometry and materials for automatic core instancing. */
21
+ export declare class TileAssembly {
22
+ readonly root: Mesh;
23
+ readonly cells: readonly Mesh[];
24
+ readonly meshes: readonly Mesh[];
25
+ /** @internal Created by assembleWFC. */
26
+ constructor(root: Mesh, cells: readonly Mesh[], meshes: readonly Mesh[]);
27
+ /** Releases placed handles only; the input models and their resources remain caller-owned. */
28
+ dispose(): void;
29
+ /** Explicit resource management. */
30
+ [Symbol.dispose](): void;
31
+ }
32
+ /**
33
+ * Place an X-fast solved grid using loaded glTF templates. Templates must belong to this engine and be static.
34
+ * Clones the complete primitive ancestry, retaining local TRS, materials, visibility and shadow flags.
35
+ * @throws RangeError for malformed grids, IDs, transforms or more than one million cells; errors roll back all handles.
36
+ */
37
+ export declare function assembleWFC(instance: EngineKernel, dimensions: readonly number[], grid: ArrayLike<number>, variants: readonly AssemblyVariant[], models: readonly TileModel[], { spacing, origin, parent, signal }?: AssemblyOptions): TileAssembly;
@@ -0,0 +1,112 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const e=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import { engineRuntime as __margoRuntime, meshRuntime as t } from "@margoengine/core/extension";
5
+ import { Quaternion as n } from "@margoengine/math";
6
+ //#region src/assemble.ts
7
+ var r = class {
8
+ constructor(e, t, n) {
9
+ this.root = e, this.cells = t, this.meshes = n;
10
+ }
11
+ dispose() {
12
+ for (let e = this.meshes.length - 1; e >= 0; e--) this.meshes[e].dispose();
13
+ for (let e = this.cells.length - 1; e >= 0; e--) this.cells[e].dispose();
14
+ this.root.dispose();
15
+ }
16
+ [Symbol.dispose]() {
17
+ this.dispose();
18
+ }
19
+ };
20
+ function i(i, a, o, s, c, { spacing: l = [
21
+ 1,
22
+ 1,
23
+ 1
24
+ ], origin: u = [
25
+ 0,
26
+ 0,
27
+ 0
28
+ ], parent: d, signal: f } = {}) {
29
+ f?.throwIfAborted();
30
+ let p = (e) => e.length === 3 && Array.from(e).every((e) => Number.isFinite(e) && Number.isFinite(Math.fround(e)));
31
+ if (!p(a) || a.some((e) => !Number.isSafeInteger(e) || e < 1) || a.reduce((e, t) => e * t, 1) > 1e6 || o.length !== a[0] * a[1] * a[2] || !p(l) || l.some((e) => e <= 0) || !p(u)) throw RangeError("Invalid WFC assembly grid or placement; provide three positive dimensions and finite spacing/origin");
32
+ let m = e(i);
33
+ if (d?.check(), d && t(d).engine !== m) throw RangeError("WFC assembly parent belongs to another engine; use this engine parent");
34
+ let h = c.map((e) => ({
35
+ root: t(e.root),
36
+ meshes: e.meshes.map(t)
37
+ })), g = h.map((e) => {
38
+ if (e.root.check(), e.root.engine !== m) throw RangeError("WFC tile model belongs to another engine; load it with this engine");
39
+ let t = /* @__PURE__ */ new Set([e.root]);
40
+ for (let n of e.meshes) {
41
+ if (n.check(), n.engine !== m) throw RangeError("WFC primitive belongs to another engine; load it with this engine");
42
+ let r = n;
43
+ for (; r !== e.root;) {
44
+ if (!r) throw RangeError("WFC primitive is outside its model root; provide a complete model");
45
+ t.add(r), r = m.meshes.get(m.store.parents[r.id]);
46
+ }
47
+ }
48
+ return t;
49
+ }), _ = Array.from(s, (e) => {
50
+ if (!e || !Number.isInteger(e.source) || !g[e.source]) throw RangeError("Invalid WFC assembly source; provide an existing model index");
51
+ let t = Array.from(e.rotation);
52
+ if (t.length !== 9 || t.some((e) => !Number.isFinite(e))) throw RangeError("Invalid WFC orientation; provide nine finite matrix values");
53
+ for (let e = 0; e < 3; e++) for (let n = 0; n < 3; n++) if (Math.abs(t[e * 3] * t[n * 3] + t[e * 3 + 1] * t[n * 3 + 1] + t[e * 3 + 2] * t[n * 3 + 2] - +(e === n)) > 1e-8) throw RangeError("WFC orientation must be orthogonal; remove scale and shear");
54
+ let r = Math.sign(t[0] * (t[4] * t[8] - t[5] * t[7]) - t[3] * (t[1] * t[8] - t[2] * t[7]) + t[6] * (t[1] * t[5] - t[2] * t[4]));
55
+ for (let e = 0; e < 3; e++) t[e] *= r;
56
+ let i = new n().setFromRotationMatrix({ elements: t });
57
+ return {
58
+ source: e.source,
59
+ sign: r,
60
+ q: [
61
+ i.x,
62
+ i.y,
63
+ i.z,
64
+ i.w
65
+ ]
66
+ };
67
+ });
68
+ for (let e = 0; e < o.length; e++) if (!Number.isInteger(o[e]) || !_[o[e]]) throw RangeError("Invalid WFC assembly tile ID; use an existing variant index");
69
+ let v = m.createMesh(d ? t(d) : null), y = [], b = [], x = new r(v, y, b);
70
+ try {
71
+ for (let e = 0; e < o.length; e++) {
72
+ f?.throwIfAborted();
73
+ let t = _[o[e]], n = m.createMesh(v);
74
+ y.push(n), n.setPosition([
75
+ u[0] + e % a[0] * l[0],
76
+ u[1] + Math.floor(e / a[0]) % a[1] * l[1],
77
+ u[2] + Math.floor(e / (a[0] * a[1])) * l[2]
78
+ ]), n.setQuaternion(t.q).setScale([
79
+ t.sign,
80
+ 1,
81
+ 1
82
+ ]);
83
+ let r = /* @__PURE__ */ new Map(), i = h[t.source], s = (e) => {
84
+ let t = r.get(e);
85
+ if (t) return t;
86
+ let a = e === i.root ? n : s(m.meshes.get(m.store.parents[e.id]));
87
+ t = m.createMesh(a), b.push(t), r.set(e, t), t.name = e.name, t.setPosition([
88
+ e.position.x,
89
+ e.position.y,
90
+ e.position.z
91
+ ]);
92
+ let o = m.store.transforms;
93
+ return t.setQuaternion([
94
+ o.qx[e.id],
95
+ o.qy[e.id],
96
+ o.qz[e.id],
97
+ o.qw[e.id]
98
+ ]), t.setScale([
99
+ e.scale.x,
100
+ e.scale.y,
101
+ e.scale.z
102
+ ]), t.setGeometry(e.geometry).setMaterial(e.material), t.visible = e.visible, t.receiveShadow = e.receiveShadow, t;
103
+ };
104
+ for (let e of g[t.source]) s(e);
105
+ }
106
+ return x;
107
+ } catch (e) {
108
+ throw x.dispose(), e;
109
+ }
110
+ }
111
+ //#endregion
112
+ export { r as TileAssembly, i as assembleWFC };
@@ -0,0 +1,26 @@
1
+ import { HeapWFC } from './heap.js';
2
+ import type { HeapBackendOptions, HeapSolveOptions } from './heap.js';
3
+ import type { Tile } from './index.js';
4
+ import type { CellPosition } from './constraints.js';
5
+ export { HeapWFC };
6
+ export type { HeapBackendOptions, HeapSolveOptions };
7
+ /** Chunked local WFC. Previously committed neighbour cells constrain a one-cell halo. */
8
+ export declare class ChunkedWFC {
9
+ private readonly seed;
10
+ private readonly dimensions;
11
+ private readonly tiles;
12
+ private readonly chunks;
13
+ private busy;
14
+ /** Construct a world with fixed chunk dimensions and rules. Seed defaults to 1. */
15
+ constructor(dimensions: CellPosition, tiles: readonly Tile[], seed?: number);
16
+ /** Number of retained chunks. Memory grows with visited coordinates until clear/dispose. */
17
+ get size(): number;
18
+ /** Generate or return a copy of a chunk. Serial calls commit atomically; concurrent calls are rejected. */
19
+ solveChunk(coordinate: CellPosition, options?: HeapBackendOptions & Pick<HeapSolveOptions, 'attempts'>): Promise<Uint16Array>;
20
+ /** Release saved chunks. Solve order affects new boundaries after clearing. */
21
+ clear(): void;
22
+ /** Release retained chunk outputs. */
23
+ dispose(): void;
24
+ /** Explicit resource management. */
25
+ [Symbol.dispose](): void;
26
+ }