@margoengine/wfc 0.0.0-stage → 1.0.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 +201 -0
- package/NOTICE +4 -0
- package/README.md +298 -2
- package/dist/assemble.d.ts +38 -0
- package/dist/assemble.js +112 -0
- package/dist/chunks.d.ts +26 -0
- package/dist/chunks.js +309 -0
- package/dist/constraints.d.ts +51 -0
- package/dist/constraints.js +193 -0
- package/dist/graph-BI3KRQ6B.js +113 -0
- package/dist/graph.d.ts +35 -0
- package/dist/grid-BGBmzG3D.js +33 -0
- package/dist/grid.d.ts +13 -0
- package/dist/heap.d.ts +41 -0
- package/dist/hex.d.ts +65 -0
- package/dist/hex.js +130 -0
- package/dist/index.d.ts +63 -0
- package/dist/index.js +145 -0
- package/dist/overlapping.d.ts +59 -0
- package/dist/overlapping.js +147 -0
- package/dist/overlapping3d.d.ts +43 -0
- package/dist/overlapping3d.js +186 -0
- package/dist/sockets.d.ts +21 -0
- package/dist/sockets.js +92 -0
- package/dist/tileset.d.ts +31 -0
- package/dist/tileset.js +169 -0
- package/dist/wfc.wasm +0 -0
- package/dist/wfc.worker.d.ts +1 -0
- package/dist/worker.d.ts +34 -0
- package/dist/worker.js +82 -0
- package/dist/workers/wfc.js +1 -0
- package/package.json +84 -4
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
package/README.md
CHANGED
|
@@ -1,3 +1,299 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @margoengine/wfc
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
## Place loaded models on a solved grid (optional wfc/assemble)
|
|
149
|
+
|
|
150
|
+
`assembleWFC` turns a solved grid into meshes: each cell gets a copy of its tile's model, turned by the variant's rotation. Copies share the template's geometry and materials, so core draws all copies of one primitive as one instanced batch.
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
import {Engine, box} from 'margoengine/core';
|
|
154
|
+
import {assembleWFC} from 'margoengine/wfc/assemble';
|
|
155
|
+
import {buildSocketTiles} from 'margoengine/wfc/sockets';
|
|
156
|
+
import {ConstrainedWFC} from 'margoengine/wfc/constraints';
|
|
157
|
+
const canvas = document.createElement('canvas');
|
|
158
|
+
document.body.append(canvas);
|
|
159
|
+
const engine = await Engine.create(canvas, {backend: 'webgpu'});
|
|
160
|
+
// Two stand-in models; a model from loadGLTF (margoengine/gltf or gltf/pbr) passes as it is.
|
|
161
|
+
const straight = engine.createMesh();
|
|
162
|
+
const slab = engine.createMesh(straight).setGeometry(box(1, 0.2, 0.4));
|
|
163
|
+
const corner = engine.createMesh();
|
|
164
|
+
const arm = engine.createMesh(corner).setGeometry(box(0.6, 0.2, 0.4)).setPosition([0.2, 0, 0]);
|
|
165
|
+
straight.visible = corner.visible = false; // hide the templates; their tiles still show
|
|
166
|
+
const variants = buildSocketTiles([
|
|
167
|
+
{sockets: ['road', 'road', '', '', 'air', 'air']},
|
|
168
|
+
{sockets: ['road', 'air', '', '', 'road', 'air']},
|
|
169
|
+
]);
|
|
170
|
+
const cells = new ConstrainedWFC([6, 1, 6], variants).solve({seed: 3});
|
|
171
|
+
const town = assembleWFC(engine, [6, 1, 6], cells, variants, [
|
|
172
|
+
{root: straight, meshes: [slab]},
|
|
173
|
+
{root: corner, meshes: [arm]},
|
|
174
|
+
], {spacing: [2, 1, 2], origin: [-5, 0, -5]});
|
|
175
|
+
console.log(town.cells.length, town.meshes.length); // 36 72
|
|
176
|
+
console.log(town.cells[7].position.x, town.cells[7].position.z); // -3 -3
|
|
177
|
+
engine.start();
|
|
178
|
+
// town.dispose() removes the placed meshes; the templates stay yours.
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
- **Inputs.** `dimensions` is `[x, y, z]`, positive integers, at most 1,000,000 cells. `grid` holds one variant index
|
|
182
|
+
per cell, X fastest, then Y, then Z, as every solver here returns it. `variants[i]` is `{source, rotation}`: the index
|
|
183
|
+
of a model in `models` and a column-major 3x3 orthogonal matrix, so a rotation or a mirror (determinant -1), with no
|
|
184
|
+
scale or shear. `buildSocketTiles` returns exactly that, and a hand-written list works the same.
|
|
185
|
+
- **Models.** Each model is `{root, meshes}`, as `loadGLTF` returns it: `meshes` are the primitives to copy, each
|
|
186
|
+
inside `root`. Every node from a primitive up to the root is copied with its name, local position, quaternion and
|
|
187
|
+
scale, geometry, material, `visible` and `receiveShadow`, so the copy keeps the model's hierarchy. A hidden template
|
|
188
|
+
root does not hide its tiles; a hidden inner node stays hidden in every copy. Models must belong to this engine and
|
|
189
|
+
be still: the copy is taken once, so later changes to a template do not reach its tiles.
|
|
190
|
+
- **Placement.** Cell `(x, y, z)` sits at `origin + (x, y, z) * spacing` (defaults `[0, 0, 0]` and `[1, 1, 1]`), so
|
|
191
|
+
model origins land on the grid points: author tiles centred on their origin. A mirrored variant gets scale
|
|
192
|
+
`[-1, 1, 1]` on its cell node with the rotation taken from the rest. Everything hangs under `town.root`, a new
|
|
193
|
+
empty mesh under `parent` when you pass one (it must be of this engine), or at the top of the scene.
|
|
194
|
+
- **What you get.** `root`, `cells` (one node per cell, in grid order) and `meshes` (the copied nodes, cell by cell).
|
|
195
|
+
`town.root.visible = false` hides the whole assembly; move or parent `root` to place it.
|
|
196
|
+
- **Ownership.** The assembly owns its nodes; `dispose()` or `using` removes them, children first, and can run twice.
|
|
197
|
+
Geometry, materials and the template meshes stay yours and stay alive: dispose them yourself, after every assembly
|
|
198
|
+
that uses them.
|
|
199
|
+
- **Errors.** Bad dimensions, spacing or origin, a grid of the wrong length, an unknown variant or model index, a
|
|
200
|
+
non-orthogonal rotation, a primitive outside its root or a mesh of another engine throw `RangeError` before anything
|
|
201
|
+
is made. `signal` is checked before and between cells; an abort throws its own reason. A failure part way removes
|
|
202
|
+
every mesh made so far.
|
|
203
|
+
|
|
204
|
+
## Large outputs and chunks (optional wfc/chunks, 3,647 B min+gzip)
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
import {ChunkedWFC, HeapWFC} from 'margoengine/wfc/chunks';
|
|
208
|
+
const tiles = [0,1].map(() => ({neighbors: Array.from({length:6}, () => [0,1])}));
|
|
209
|
+
const large = await HeapWFC.create([192,192,1], tiles);
|
|
210
|
+
console.log(large.solve({seed:7}).length, large.backend);
|
|
211
|
+
using world = new ChunkedWFC([16,16,1], tiles, 7);
|
|
212
|
+
const left = await world.solveChunk([-1,0,0]);
|
|
213
|
+
const right = await world.solveChunk([0,0,0]);
|
|
214
|
+
console.log(left.length, right.length, world.size);
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
HeapWFC uses indexed binary-heap selection, bitset propagation and fixed seeded per-cell tie keys. A domain change
|
|
218
|
+
updates one heap position in O(log cells), without stale heap entries. This is a new seed algorithm; root,
|
|
219
|
+
overlapping and constraints seed streams keep their previous behavior. Local adjacency and pins only; it uses
|
|
220
|
+
bounded restarts, without global counts/connectivity or chronological backtracking. Defaults: seed 1, attempts 4
|
|
221
|
+
(1..64), pins empty, signal absent. Grid limits: 1..4096 IDs, <=1,000,000 cells, <=16,777,216 cell/tile pairs.
|
|
222
|
+
Invalid inputs throw RangeError/TypeError; exhausted attempts throw coded failed with a help link.
|
|
223
|
+
A cell that still holds every tile (every cell at the start of an attempt) propagates one neighbour union gathered
|
|
224
|
+
once per solve, so the first pass costs six words per cell rather than a walk over all tiles; the legacy `WFC` also
|
|
225
|
+
reuses the full domain's entropy. Solutions, seeds and `stats` are unchanged:
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
import {HeapWFC} from '@margoengine/wfc/chunks';
|
|
229
|
+
|
|
230
|
+
const all = Array.from({length: 8}, (_, t) => t);
|
|
231
|
+
const tiles = all.map((t) => ({weight: 1 + t, neighbors: Array.from({length: 6}, () => all)}));
|
|
232
|
+
const model = new HeapWFC([16, 16, 1], tiles); // weighted tiles stay on the TypeScript solver
|
|
233
|
+
const grid = model.solve({seed: 3});
|
|
234
|
+
console.log(grid.length, model.stats.decisions); // 256 256
|
|
235
|
+
```
|
|
236
|
+
All WFC entries reject holes in dimensions, coordinates, pins, rules and constraint lists before search;
|
|
237
|
+
all three dimensions and their safe integer product are validated before grid allocation.
|
|
238
|
+
|
|
239
|
+
Constructor HeapWFC is synchronous TypeScript. Async HeapWFC.create defaults to backend auto: lazily loads the
|
|
240
|
+
feature's own Rust/Wasm SIMD artifact for <=32 unit-weight tiles, using new URL relative to the module; wider or
|
|
241
|
+
weighted sets use TypeScript. Explicit typescript forces JS; explicit wasm rejects ineligible sets or missing SIMD
|
|
242
|
+
with coded unsupported and a help link. Load accepts AbortSignal; network, response-body, local-file and
|
|
243
|
+
instantiation failures are coded failed with a help link and the original cause. Abort throws the exact signal
|
|
244
|
+
reason. Build inputs and
|
|
245
|
+
artifact hashes live in native/solver, rebuild with node packages/wfc/scripts/build-wasm.mjs (Rust wasm32 target).
|
|
246
|
+
No shared Wasm bundle, core/stage import or import-time loading. Both implementations perform the same local solve
|
|
247
|
+
and produce identical IDs for identical seeds; benchmark decision is recorded below. Browser WebGPU and WebGL2 use
|
|
248
|
+
the same CPU code. Synchronous solving checks cancellation but cannot receive new events while blocking its thread.
|
|
249
|
+
Wasm work statistics use 32-bit counters (wrap above 4,294,967,295); measured fixtures stay below that bound.
|
|
250
|
+
|
|
251
|
+
ChunkedWFC solves a one-cell halo constrained by all previously committed neighbouring cells, then commits only the
|
|
252
|
+
interior. Every successful seam satisfies the tile rules. Coordinates, world cell bounds and halo bounds must be safe
|
|
253
|
+
integers; negative and distant addresses work. Grid/pair limits include the halo (each dimension plus 2). Chunk seed
|
|
254
|
+
is the world seed mixed with all coordinate halves; generation is reproducible for the same solve order. Order can
|
|
255
|
+
change layouts, and arbitrary rules may make a later chunk impossible: it throws rather than editing old chunks.
|
|
256
|
+
There is no global playability guarantee across chunks. Calls must be serial; concurrent generation/clear throws
|
|
257
|
+
coded failed. Cached outputs are copies. Storage grows with visited chunks; clear, dispose and Symbol.dispose release
|
|
258
|
+
it. Failed or aborted calls commit nothing. The world seed defaults to 1; solveChunk takes backend auto, attempts 4 and
|
|
259
|
+
signal absent. No hidden eviction, caller-authored boundary rules or caller repair is required.
|
|
260
|
+
|
|
261
|
+
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.
|
|
262
|
+
|
|
263
|
+
## Worker solving (optional wfc/worker, 1,331 B min+gzip)
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
import {WFCWorkerSolve} from 'margoengine/wfc/worker';
|
|
267
|
+
const tiles = [0,1].map(() => ({neighbors: Array.from({length:6}, () => [0,1])}));
|
|
268
|
+
const controller = new AbortController();
|
|
269
|
+
using job = new WFCWorkerSolve([64,64,1], tiles, {seed:7, signal:controller.signal});
|
|
270
|
+
const progress = (async () => {
|
|
271
|
+
for await (const work of job) document.body.dataset.wfcDecisions = String(work.decisions);
|
|
272
|
+
})();
|
|
273
|
+
const cells = await job.result;
|
|
274
|
+
await progress;
|
|
275
|
+
console.log(cells.length); // 4096. controller.abort(reason) terminates an active worker.
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
One dedicated classic Web Worker runs the same HeapWFC algorithm and the same eligible Rust SIMD artifact as chunks.
|
|
279
|
+
Rules, dimensions and pins are structured-cloned; the resulting Uint16Array transfers back without a copy. Construction
|
|
280
|
+
starts the worker immediately. No grid validation, heap construction or search runs on the calling thread; cloning
|
|
281
|
+
large input rules still has a cost. Auto, typescript and wasm have the same selection rules as HeapWFC.create, preserving
|
|
282
|
+
its seed stream exactly. This entry solves local adjacency and pins; it does not run the overlapping/global solvers or
|
|
283
|
+
maintain a chunk cache. Existing grid, tile, pair and restart limits apply.
|
|
284
|
+
|
|
285
|
+
Defaults: seed 1, pins empty, attempts 4, backend auto, signal absent, timeout 60000 ms including startup/downloads.
|
|
286
|
+
Timeout must be an integer from 1 to 2147483647 ms. Progress is a single-consumer async iterable of actual cumulative
|
|
287
|
+
decisions, heap updates, intersections, current attempt and selected backend, emitted during both TS and synchronous
|
|
288
|
+
Wasm work and once at completion. It is not a percentage: restarts can revisit cells. Slow readers retain only the latest
|
|
289
|
+
snapshot, so memory stays bounded. Completion closes the stream; always await result to observe errors. Stopping progress
|
|
290
|
+
iteration leaves the solve running. Abort, timeout and dispose terminate the worker, remove listeners and close progress.
|
|
291
|
+
Abort rejects with the signal reason, timeout with coded timeout, disposal with coded disposed. Dispose/Symbol.dispose
|
|
292
|
+
are idempotent. Crashes, message and clone failures reject with coded failed; solver TypeError/RangeError and coded
|
|
293
|
+
errors survive transport. Coded errors carry a help link. A pre-aborted signal starts no worker.
|
|
294
|
+
|
|
295
|
+
Browser WebGPU and WebGL2 both run real solves while submitting rendered animation frames, with in-flight progress,
|
|
296
|
+
abort and synchronous parity checks. There is no GPU work in the solver and no shared-memory/isolation requirement.
|
|
297
|
+
Node/SSR imports are safe; construction throws coded unsupported there (use HeapWFC). CSP must allow the same-origin
|
|
298
|
+
worker asset and Wasm where selected. No Blob, eval or caller-authored worker is needed. The optional entry downloads
|
|
299
|
+
workers/wfc.js only when constructed, and wfc.wasm only for an eligible backend; it imports no rendering backend.
|
|
@@ -0,0 +1,38 @@
|
|
|
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; the template
|
|
35
|
+
* root's own visibility is not copied, so templates can be hidden while their tiles show.
|
|
36
|
+
* @throws RangeError for malformed grids, IDs, transforms or more than one million cells; errors roll back all handles.
|
|
37
|
+
*/
|
|
38
|
+
export declare function assembleWFC(instance: EngineKernel, dimensions: readonly number[], grid: ArrayLike<number>, variants: readonly AssemblyVariant[], models: readonly TileModel[], { spacing, origin, parent, signal }?: AssemblyOptions): TileAssembly;
|