nucleation 0.7.0

A high-performance Minecraft schematic parser and utility library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
# Nucleation - JavaScript/TypeScript Documentation

Complete API reference and guide for using Nucleation in JavaScript and TypeScript (via WebAssembly).

Two import surfaces ship side by side:

- **`nucleation`** — the raw wasm-bindgen output (`SchematicWrapper`, `init`,
  etc.). Lowest overhead, snake_case Rust names.
- **`nucleation/api`** — a polished facade with `Schematic`, `Block`,
  `Cursor`, `UseBlock`, `ButtonPress`, `Item`, plus `chest()`, `sign()`,
  `text()` helpers. Camel-case JS conventions, structured state/NBT,
  chainable returns. The underlying raw instance is always available as
  `schem.raw`.

## Quick Start

```bash
npm install nucleation
```

### Polished API (recommended)

```typescript
import init from "nucleation";
import { Schematic, sign, text } from "nucleation/api";
await init();

const schem = Schematic.new("my_build");

// Tuple coordinates, structured state and NBT, chainable.
schem.setBlock([0, 0, 0], "minecraft:repeater", {
  state: { delay: 4, facing: "east" },
});
schem.setBlock([0, 1, 0], "minecraft:oak_sign", {
  state: { rotation: 8 },
  nbt: sign([text("Hello", { color: "gold" }), "world"]),
});

await schem.save("out.litematic");          // Node: writes to disk
const bytes = await schem.save("x.litematic");  // Browser: returns Uint8Array
```

### Per-block placement performance

| API | Throughput | When to use |
|-----|-----------:|-------------|
| `schem.raw.fill_cuboid(...)` | very fast | One block, axis-aligned cuboid |
| `schem.raw.set_blocks(positions, "id")` | ~10 M/s | Many positions, one block id |
| `prepareBlock("id")` + `place(...)` | **~85 M/s** | Hot loop, multiple unique ids |
| `schem.setBlock([x,y,z], "id")` | ~7 M/s | Single placement, polished |

Hot-loop pattern:

```typescript
const stone = schem.prepareBlock("minecraft:stone");
const place = schem.raw.place.bind(schem.raw);
for (const [x, y, z] of positions) place(x, y, z, stone);
```

WASM has dramatically lower per-call overhead than PyO3 — the JS
prepare+place path runs at near-native-Rust speed.

### Raw API

The raw wasm-bindgen output remains available without the polished facade:

```typescript
import init, { SchematicWrapper } from "nucleation";
await init();

const schematic = new SchematicWrapper();
schematic.set_block(0, 0, 0, "minecraft:stone");
const bytes = schematic.to_litematic();
```

## Table of Contents

1. [Installation & Setup]#installation--setup
2. [Core API]#core-api
3. [Loading and Saving]#loading-and-saving
4. [Block Operations]#block-operations
5. [Region Operations]#region-operations
6. [Block Entities]#block-entities
7. [SchematicBuilder]#schematicbuilder
8. [Simulation]#simulation
9. [TypedCircuitExecutor]#typedcircuitexecutor
10. [DefinitionRegion]#definitionregion
12. [Procedural Building]#procedural-building
13. [3D Mesh Generation]#3d-mesh-generation

## Installation & Setup

### Node.js / Bundlers

```bash
npm install nucleation
```

```typescript
import init, { SchematicWrapper } from "nucleation";

// Auto-detects environment and loads WASM
await init();

const schematic = new SchematicWrapper();
```

### Browser via CDN

```html
<script type="module">
	import init, {
		SchematicWrapper,
	} from "https://cdn.jsdelivr.net/npm/nucleation@latest/nucleation-cdn-loader.js";

	await init(); // Automatically resolves WASM path
	const schematic = new SchematicWrapper();
</script>
```

### Manual WASM Loading

```typescript
import init, { SchematicWrapper } from "nucleation";

const wasmBytes = await fetch("/path/to/nucleation_bg.wasm").then((r) =>
	r.arrayBuffer()
);

await init(wasmBytes);
```

## Core API

### SchematicWrapper

Main class for working with schematics.

```typescript
class SchematicWrapper {
	constructor(); // Creates empty schematic named "Default"

	// Loading/Saving
	from_data(bytes: Uint8Array): void;
	from_litematic(bytes: Uint8Array): void;
	from_schematic(bytes: Uint8Array): void;
	to_litematic(): Uint8Array;
	to_schematic(): Uint8Array;
	toSnapshot(): Uint8Array;
	fromSnapshot(bytes: Uint8Array): void;

	// Format Support
	static get_supported_import_formats(): string[];
	static get_supported_export_formats(): string[];
	static get_format_versions(format: string): string[];
	static get_default_format_version(format: string): string | undefined;
	
	save_as(format: string, version?: string): Uint8Array;

	// Block operations
	set_block(x: number, y: number, z: number, blockName: string): void;
	set_block_with_properties(
		x: number,
		y: number,
		z: number,
		blockName: string,
		properties: object
	): void;
	set_block_from_string(
		x: number,
		y: number,
		z: number,
		blockString: string
	): void;
	get_block(x: number, y: number, z: number): string | null;
	get_block_with_properties(
		x: number,
		y: number,
		z: number
	): BlockStateWrapper | null;

	// Block entities
	get_block_entity(x: number, y: number, z: number): object | null;
	get_all_block_entities(): Array<object>;

	// Region operations
	copy_region(
		sourceRegion: string,
		minX: number,
		minY: number,
		minZ: number,
		maxX: number,
		maxY: number,
		maxZ: number,
		targetX: number,
		targetY: number,
		targetZ: number,
		excludedBlocks: string[]
	): void;

	// Information
	get_dimensions(): [number, number, number];
	get_block_count(): number;
	get_volume(): number;
	get_region_names(): string[];
	debug_info(): string;
	print_schematic(): string;

	// Iteration
	blocks(): Array<{
		x: number;
		y: number;
		z: number;
		name: string;
		properties: object;
	}>;
	chunks(width: number, height: number, length: number): Array<any>;
	chunks_with_strategy(
		width: number,
		height: number,
		length: number,
		strategy: string,
		cx?: number,
		cy?: number,
		cz?: number
	): Array<any>;
	get_chunk_blocks(
		offsetX: number,
		offsetY: number,
		offsetZ: number,
		width: number,
		height: number,
		length: number
	): Array<any>;

	// Simulation (requires simulation feature)
	create_simulation_world(): MchprsWorldWrapper;
	create_simulation_world_with_options(
		options: SimulationOptionsWrapper
	): MchprsWorldWrapper;
}
```

### BlockStateWrapper

Represents a block with properties.

```typescript
class BlockStateWrapper {
	constructor(name: string);

	with_property(key: string, value: string): void; // Mutates in place
	name(): string;
	properties(): object;
}
```

## Loading and Saving

### Load from File

```typescript
// Browser
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener("change", async (e) => {
	const file = e.target.files[0];
	const bytes = new Uint8Array(await file.arrayBuffer());

	const schematic = new SchematicWrapper();
	schematic.from_data(bytes); // Auto-detects format

	console.log(schematic.get_dimensions());
});

// Node.js
import { readFileSync } from "fs";

const bytes = new Uint8Array(readFileSync("input.litematic"));
const schematic = new SchematicWrapper();
schematic.from_litematic(bytes);

// Check supported formats
console.log(SchematicWrapper.get_supported_import_formats());
// ["litematic", "schematic", "mcstructure"]
```

### Save to File

```typescript
// Browser - Download
const bytes = schematic.to_litematic();
const blob = new Blob([bytes], { type: "application/octet-stream" });
const url = URL.createObjectURL(blob);

const a = document.createElement("a");
a.href = url;
a.download = "output.litematic";
a.click();

URL.revokeObjectURL(url);

// Node.js
import { writeFileSync } from "fs";

const bytes = schematic.to_litematic();
writeFileSync("output.litematic", bytes);

// Check export formats
console.log(SchematicWrapper.get_supported_export_formats());
// ["litematic", "schematic", "mcstructure"]

// Check versions
console.log(SchematicWrapper.get_format_versions("schematic"));
// ["v1", "v2", "v3"]

console.log(SchematicWrapper.get_default_format_version("schematic"));
// "v3"

// Save with specific format and version
const schemBytes = schematic.save_as("schematic", "v2");
writeFileSync("output.v2.schem", schemBytes);
```

### Snapshot Format

The snapshot format is a fast binary serialization for caching and worker transfer. Much faster than standard formats but not compatible with Minecraft.

```typescript
// Serialize to snapshot bytes
const snapshotData = schematic.toSnapshot();

// Load from snapshot (e.g., received from a Web Worker)
const schematic2 = new SchematicWrapper();
schematic2.fromSnapshot(snapshotData);
```

## Block Operations

### Setting Blocks

```typescript
// Simple block
schematic.set_block(0, 0, 0, "minecraft:stone");

// Block with properties (object)
schematic.set_block_with_properties(0, 1, 0, "minecraft:lever", {
	facing: "east",
	powered: "false",
});

// Block from string (bracket notation)
schematic.set_block_from_string(
	1,
	1,
	0,
	"minecraft:redstone_wire[power=15,north=side,south=side]"
);

// Using BlockStateWrapper
const block = new BlockStateWrapper("minecraft:repeater");
block.with_property("facing", "east");
block.with_property("delay", "2");
// Note: BlockStateWrapper is mainly for reading, use set_block_with_properties for setting
```

### Getting Blocks

```typescript
// Get block name only
const blockName = schematic.get_block(0, 0, 0);
if (blockName) {
	console.log(`Block: ${blockName}`);
}

// Get block with properties
const blockState = schematic.get_block_with_properties(0, 1, 0);
if (blockState) {
	console.log(`Block: ${blockState.name()}`);
	console.log(`Properties:`, blockState.properties());
}
```

### Iterating Blocks

```typescript
// Get all blocks
const allBlocks = schematic.blocks();
for (const block of allBlocks) {
	console.log(`(${block.x}, ${block.y}, ${block.z}) = ${block.name}`);
	console.log(`Properties:`, block.properties);
}

// Filter non-air blocks
const nonAirBlocks = allBlocks.filter((b) => !b.name.includes("air"));

// Count block types
const blockCounts = new Map();
for (const block of allBlocks) {
	const count = blockCounts.get(block.name) || 0;
	blockCounts.set(block.name, count + 1);
}
```

### Chunk Iteration

```typescript
// Get chunks (bottom-up order)
const chunks = schematic.chunks(16, 16, 16);
for (const chunk of chunks) {
	console.log(
		`Chunk at (${chunk.offset_x}, ${chunk.offset_y}, ${chunk.offset_z})`
	);
	console.log(`Blocks:`, chunk.blocks);
}

// Get chunks with strategy
const strategies = [
	"distance_to_camera",
	"top_down",
	"bottom_up",
	"center_outward",
	"random",
];

const chunks = schematic.chunks_with_strategy(
	16,
	16,
	16,
	"distance_to_camera",
	0,
	100,
	0 // Camera position
);

// Get specific chunk
const chunkBlocks = schematic.get_chunk_blocks(0, 0, 0, 16, 16, 16);
```

## Region Operations

### Copying Regions

```typescript
// Copy a region
schematic.copy_region(
	"Main", // Source region name
	0,
	0,
	0, // Min coordinates
	10,
	10,
	10, // Max coordinates
	20,
	0,
	0, // Target position
	["minecraft:air"] // Excluded blocks
);
```

### Working with Multiple Regions

```typescript
// Get all region names
const regions = schematic.get_region_names();
console.log(`Regions:`, regions);

// Get dimensions
const [width, height, depth] = schematic.get_dimensions();
console.log(`Size: ${width}x${height}x${depth}`);

// Get block/volume counts
console.log(`Blocks: ${schematic.get_block_count()}`);
console.log(`Volume: ${schematic.get_volume()}`);
```

## Block Entities

### Setting Block Entities

```typescript
// Set block with entity using string notation
schematic.set_block_from_string(
	0,
	1,
	0,
	"minecraft:barrel[facing=up]{signal=13}"
);

// Note: Direct block entity manipulation is limited in WASM
// Use bracket notation with {nbt} for most cases
```

### Getting Block Entities

```typescript
// Get single block entity
const entity = schematic.get_block_entity(0, 1, 0);
if (entity) {
	console.log(`Entity:`, entity);
	// Entity is a plain JavaScript object with NBT data
}

// Get all block entities
const allEntities = schematic.get_all_block_entities();
for (const entity of allEntities) {
	console.log(
		`Entity at (${entity.x}, ${entity.y}, ${entity.z}):`,
		entity.data
	);
}
```

## SchematicBuilder

Build schematics programmatically with ASCII art and compositional design.

See [SchematicBuilder Guide](../shared/guide/schematic-builder.md) for complete documentation.

### Quick Example

```typescript
import init, { SchematicBuilder } from "nucleation";
await init();

const wall = new SchematicBuilder()
	.name("Wall")
	.palette({ "#": "minecraft:stone_bricks", ".": "minecraft:air" })
	.layers([
		["###", "#.#", "###"],
		["###", "#.#", "###"],
	])
	.build();
```

### Builder Methods

| Method | Description |
|--------|-------------|
| `name(name)` | Set the schematic name. |
| `map(ch, block)` | Map a single character to a block id. |
| `palette(mappings)` | Bulk-register character→block mappings. Accepts `{c: "minecraft:stone"}` or `[["c", "minecraft:stone"]]`. |
| `layer(rows)` | Append a single Y-layer (`string[]`). |
| `layers(layers)` | Set/replace all layers (`string[][]` — outer Y, inner rows). |
| `offset(x, y, z)` | Shift the origin where blocks are placed. |
| `useStandardPalette()` / `useMinimalPalette()` / `useCompactPalette()` | Built-in palettes. |
| `validate()` | Throws if any layer character is unmapped. |
| `toTemplate()` | Serialise to the text template format. |
| `static fromTemplate(template)` | Parse a template string into a builder. |
| `build()` | Materialise the `SchematicWrapper`. |

### Template Format

Layers are separated by a blank line; an optional `[palette]` section maps
characters to block IDs. Round-trips via `toTemplate` / `fromTemplate`.

```
###
#.#
###

###
#.#
###

[palette]
# = minecraft:stone_bricks
. = minecraft:air
```

## Simulation

Simulate redstone circuits in real-time.

### Basic Simulation

```typescript
import init, { SchematicWrapper } from "nucleation";
await init();

const schematic = new SchematicWrapper();
// Build circuit...
schematic.set_block_from_string(
	0,
	1,
	0,
	"minecraft:lever[facing=north,powered=false]"
);
schematic.set_block_from_string(5, 1, 0, "minecraft:redstone_lamp[lit=false]");
// ... add redstone wiring ...

// Create simulation world
const world = schematic.create_simulation_world();

// Toggle lever
world.on_use_block(0, 1, 0);

// Run simulation
world.tick(10);
world.flush();

// Check if lamp is lit
const isLit = world.is_lit(5, 1, 0);
console.log(`Lamp is lit: ${isLit}`);
```

### Custom IO Simulation

```typescript
import { SimulationOptionsWrapper } from "nucleation";

// Configure custom IO positions
const options = new SimulationOptionsWrapper();
options.addCustomIo(0, 1, 0); // Input position
options.addCustomIo(10, 1, 0); // Output position

const world = schematic.create_simulation_world_with_options(options);

// Inject custom signal strength (0-15)
world.setSignalStrength(0, 1, 0, 15); // Max power
world.tick(5);
world.flush();

// Read signal strength
const outputSignal = world.getSignalStrength(10, 1, 0);
console.log(`Output signal: ${outputSignal}`);
```

### Batch Signal Operations

```typescript
// Set multiple signals at once
const positions = [
	[0, 1, 0],
	[0, 1, 2],
	[0, 1, 4],
];
const strengths = [15, 0, 15];

for (let i = 0; i < positions.length; i++) {
	const [x, y, z] = positions[i];
	world.setSignalStrength(x, y, z, strengths[i]);
}

world.tick(10);
world.flush();

// Read multiple signals
const outputs = positions.map(([x, y, z]) => world.getSignalStrength(x, y, z));
```

## TypedCircuitExecutor

High-level API for circuit simulation with typed inputs/outputs.

See [TypedCircuitExecutor Guide](../shared/guide/typed-executor.md) for complete documentation.

### Quick Example

```typescript
import {
	TypedCircuitExecutor,
	IoType,
	LayoutFunction,
	Value,
} from "nucleation";

// Define IO mappings
const inputs = new Map([
	[
		"a",
		{
			io_type: IoType.Bool,
			layout: LayoutFunction.OneToOne,
			positions: [[0, 1, 0]],
		},
	],
	[
		"b",
		{
			io_type: IoType.Bool,
			layout: LayoutFunction.OneToOne,
			positions: [[0, 1, 2]],
		},
	],
]);

const outputs = new Map([
	[
		"result",
		{
			io_type: IoType.Bool,
			layout: LayoutFunction.OneToOne,
			positions: [[10, 1, 0]],
		},
	],
]);

// Create executor
const executor = new TypedCircuitExecutor(world, inputs, outputs);

// Execute with typed values
const inputValues = new Map([
	["a", Value.Bool(true)],
	["b", Value.Bool(true)],
]);

const result = executor.execute(inputValues, {
	mode: "fixed_ticks",
	ticks: 100,
});

// Get typed output
const output = result.outputs.get("result");
console.log(`Result: ${output}`); // Value.Bool(true)
```

## TypeScript Types

```typescript
// Block state
interface BlockState {
	name: string;
	properties: Record<string, string>;
}

// Block with position
interface PositionedBlock {
	x: number;
	y: number;
	z: number;
	name: string;
	properties: Record<string, string>;
}

// Chunk
interface Chunk {
	offset_x: number;
	offset_y: number;
	offset_z: number;
	blocks: PositionedBlock[];
}

// Execution mode
type ExecutionMode =
	| { mode: "fixed_ticks"; ticks: number }
	| { mode: "until_condition"; output: string; condition: any; timeout: number }
	| { mode: "until_stable"; stable_ticks: number; timeout: number }
	| { mode: "until_change"; timeout: number };
```

## Examples

### Download Schematic

```typescript
function downloadSchematic(schematic: SchematicWrapper, filename: string) {
	const bytes = schematic.to_litematic();
	const blob = new Blob([bytes], { type: "application/octet-stream" });
	const url = URL.createObjectURL(blob);

	const a = document.createElement("a");
	a.href = url;
	a.download = filename;
	a.click();

	URL.revokeObjectURL(url);
}
```

### Upload Schematic

```typescript
async function uploadSchematic(file: File): Promise<SchematicWrapper> {
	const bytes = new Uint8Array(await file.arrayBuffer());
	const schematic = new SchematicWrapper();
	schematic.from_data(bytes);
	return schematic;
}

// Usage
const input = document.querySelector('input[type="file"]');
input.addEventListener("change", async (e) => {
	const schematic = await uploadSchematic(e.target.files[0]);
	console.log(schematic.get_dimensions());
});
```

### Build and Test Circuit

```typescript
async function buildAndTestCircuit() {
	await init();

	const schematic = new SchematicWrapper();

	// Build AND gate
	schematic.set_block(0, 0, 0, "minecraft:stone");
	schematic.set_block_from_string(
		0,
		1,
		0,
		"minecraft:lever[facing=north,powered=false]"
	);
	// ... build circuit ...

	// Test simulation
	const world = schematic.create_simulation_world();
	world.on_use_block(0, 1, 0); // Toggle input
	world.tick(10);
	world.flush();

	const output = world.is_lit(10, 1, 0);
	console.log(`Test passed: ${output === true}`);
}
```

## DefinitionRegion

Advanced region manipulation for defining circuit IO areas.

See [Circuit API Guide](../shared/guide/circuit-api.md) for complete documentation.

### Creating Regions

```typescript
import { DefinitionRegionWrapper, BlockPosition } from "nucleation";

// Create empty region
const region = new DefinitionRegionWrapper();

// Add bounding box
region.addBounds(new BlockPosition(0, 1, 0), new BlockPosition(7, 1, 0));

// Add single point
region.addPoint(10, 1, 0);

// Create from bounds directly
const region2 = DefinitionRegionWrapper.fromBounds(
	new BlockPosition(0, 0, 0),
	new BlockPosition(10, 10, 10)
);
```

### Boolean Operations

```typescript
const regionA = new DefinitionRegionWrapper();
regionA.addBounds(new BlockPosition(0, 0, 0), new BlockPosition(5, 0, 0));

const regionB = new DefinitionRegionWrapper();
regionB.addBounds(new BlockPosition(3, 0, 0), new BlockPosition(8, 0, 0));

// Mutating operations (modify in-place)
regionA.subtract(regionB); // Remove B's points from A
regionA.intersect(regionB); // Keep only common points
regionA.unionInto(regionB); // Add B's points to A

// Immutable operations (return new region)
const diff = regionA.subtracted(regionB);
const common = regionA.intersected(regionB);
const combined = regionA.union(regionB);
```

### Geometric Transformations

```typescript
const region = new DefinitionRegionWrapper();
region.addBounds(new BlockPosition(0, 0, 0), new BlockPosition(10, 10, 10));

// Move region
region.shift(100, 50, 200);

// Expand outward
region.expand(2, 2, 2);

// Contract inward
region.contract(1);

// Get bounds
const bounds = region.getBounds();
// { min: [x, y, z], max: [x, y, z] } or null
```

### Connectivity Analysis

```typescript
// Check if all points are connected (6-connectivity)
const isConnected = region.isContiguous();

// Count separate islands
const componentCount = region.connectedComponents();
```

### Filtering by Block Properties

```typescript
const schematic = new SchematicWrapper();
// ... add blocks ...

// Filter by block name
const lamps = region.filterByBlock(schematic, "redstone_lamp");

// Filter by properties
const litLamps = region.filterByProperties(schematic, { lit: "true" });
```

### Position Iteration

```typescript
// Get all positions (in add order)
const positions = region.positions(); // [[x,y,z], ...]

// Get positions in deterministic Y→X→Z order (for bit assignment)
const sortedPositions = region.positionsSorted();
```

### Memory Management

```typescript
// ⚠️ IMPORTANT: Free WASM objects when done
const region = new DefinitionRegionWrapper();
// ... use region ...
region.free(); // Required to prevent memory leaks
```

## CircuitBuilder

Fluent API for creating `TypedCircuitExecutor` instances.

See [Circuit API Guide](../shared/guide/circuit-api.md) for complete documentation.

### Basic Usage

```typescript
import {
	CircuitBuilderWrapper,
	DefinitionRegionWrapper,
	IoTypeWrapper,
	BlockPosition,
} from "nucleation";

const schematic = new SchematicWrapper();
// ... build your circuit ...

// Define IO regions
const inputRegion = new DefinitionRegionWrapper();
inputRegion.addBounds(new BlockPosition(0, 1, 0), new BlockPosition(7, 1, 0));

const outputRegion = new DefinitionRegionWrapper();
outputRegion.addBounds(
	new BlockPosition(0, 1, 20),
	new BlockPosition(7, 1, 20)
);

// Build executor with fluent API
const executor = new CircuitBuilderWrapper(schematic)
	.withInputAuto("data_in", IoTypeWrapper.unsignedInt(8), inputRegion)
	.withOutputAuto("data_out", IoTypeWrapper.unsignedInt(8), outputRegion)
	.withStateMode("stateful")
	.buildValidated();

// Clean up regions (executor clones them)
inputRegion.free();
outputRegion.free();
```

### From Insign Annotations

```typescript
// Create from sign annotations in schematic
const builder = CircuitBuilderWrapper.fromInsign(schematic);
const executor = builder.build();
```

### Validation

```typescript
const builder = new CircuitBuilderWrapper(schematic)
	.withInputAuto("a", IoTypeWrapper.unsignedInt(8), regionA)
	.withOutputAuto("out", IoTypeWrapper.unsignedInt(8), regionOut);

// Explicit validation (throws on error)
builder.validate();

// Or validate during build
const executor = builder.buildValidated();
```

### State Modes

```typescript
// Reset before each execute (default)
builder.withStateMode("stateless");

// Preserve state between executes
builder.withStateMode("stateful");

// Manual control (use tick/flush)
builder.withStateMode("manual");
```

### Manual Tick Control

```typescript
const executor = builder.withStateMode("manual").build();

// Set inputs individually
executor.setInput("a", ValueWrapper.fromU32(5));
executor.setInput("b", ValueWrapper.fromU32(3));
executor.flush();

// Tick manually
for (let i = 0; i < 10; i++) {
	executor.tick(1);
	executor.flush();

	const result = executor.readOutput("sum");
	console.log(`Tick ${i}: ${result.toJs()}`);
}
```

### Layout Debugging

```typescript
// See exactly which block maps to which bit
const layoutInfo = executor.getLayoutInfo();

console.log("Inputs:");
for (const [name, info] of Object.entries(layoutInfo.inputs)) {
	console.log(`  ${name}: ${info.ioType} (${info.bitCount} bits)`);
	info.positions.forEach((pos, bit) => {
		console.log(`    Bit ${bit}: [${pos.join(", ")}]`);
	});
}
```

## Procedural Building

Generate structures procedurally using geometric shapes and brushes.

```typescript
import { 
    ShapeWrapper, 
    BrushWrapper, 
    WasmBuildingTool, 
    SchematicWrapper 
} from "nucleation";

const schematic = new SchematicWrapper();

// Create a sphere shape
const sphere = ShapeWrapper.sphere(
    0, 0, 0, // Center (x, y, z)
    10.0     // Radius
);

// Create a gradient brush (Red -> Blue)
const brush = BrushWrapper.linear_gradient(
    0, 0, 0, 255, 0, 0,      // Start: Pos(0,0,0), Red(255,0,0)
    10, 0, 0, 0, 0, 255,     // End: Pos(10,0,0), Blue(0,0,255)
    1,                       // 1 = Oklab interpolation (smoother), 0 = RGB
    ["wool"]                 // Optional filter: only use wool blocks
);

// Apply brush to shape
WasmBuildingTool.fill(schematic, sphere, brush);
```

### Simple Helpers

For simple tasks, you can use the direct methods on `SchematicWrapper`:

```typescript
// Fill a cuboid region with a solid block
schematic.fillCuboid(
    0, 0, 0,      // Min [x, y, z]
    10, 5, 10,    // Max [x, y, z]
    "minecraft:red_concrete"
);

// Fill a sphere with a solid block
schematic.fillSphere(
    0, 0, 0,      // Center [x, y, z]
    10.0,         // Radius
    "minecraft:blue_wool"
);
```

### Available Brushes

```typescript
// Solid block
const solid = BrushWrapper.solid("minecraft:stone");

// Solid color (matches closest block)
const color = BrushWrapper.color(255, 128, 0, null); // Orange

// 4-Point Bilinear Gradient (Quad)
const bilinear = BrushWrapper.bilinear_gradient(
    0, 0, 0, 10, 0, 0, 0, 10, 0,  // Origin, U-end, V-end
    255, 0, 0,    // Origin Color (Red)
    0, 0, 255,    // U-end Color (Blue)
    0, 255, 0,    // V-end Color (Green)
    255, 255, 0,  // Opposite Color (Yellow)
    1,            // Oklab interpolation
    null          // No filter
);

// Point Cloud Gradient (Arbitrary points, IDW)
const points = BrushWrapper.point_gradient(
    // Positions [x1, y1, z1, x2, y2, z2...]
    [0, 0, 0,  10, 10, 10,  5, 5, 5],
    // Colors [r1, g1, b1, r2, g2, b2...]
    [255, 0, 0,  0, 0, 255,  0, 255, 0], 
    2.5,  // Falloff (power), default 2.0
    1,    // Oklab
    null
);
```

### Palette Management

Use `PaletteManager` to get blocks for your UI dropdowns.

```typescript
import { PaletteManager } from "nucleation";

// Get all wool blocks
const woolBlocks = PaletteManager.getWoolBlocks();

// Get concrete blocks
const concreteBlocks = PaletteManager.getConcreteBlocks();

// Get custom mix (e.g., all wool + obsidian)
const customPalette = PaletteManager.getPaletteByKeywords(["wool", "obsidian"]);
```

## 3D Mesh Generation

Generate 3D meshes from schematics using Minecraft resource packs.

### Loading a Resource Pack

```javascript
import { ResourcePackWrapper, MeshConfigWrapper } from 'nucleation';

// Load from bytes (e.g., fetched ZIP file)
const response = await fetch('resourcepack.zip');
const data = new Uint8Array(await response.arrayBuffer());
const pack = new ResourcePackWrapper(data);

console.log(`Blockstates: ${pack.blockstateCount}`);
console.log(`Models: ${pack.modelCount}`);
console.log(`Textures: ${pack.textureCount}`);
```

### Generating Meshes

```javascript
const config = new MeshConfigWrapper();
config.setCullHiddenFaces(true);
config.setAmbientOcclusion(true);
config.setAoIntensity(0.4);
config.setCullOccludedBlocks(true);
config.setGreedyMeshing(true);

// Generate GLB mesh
const result = schematic.toMesh(pack, config);
const glbData = result.glbData; // Uint8Array
console.log(`Vertices: ${result.vertexCount}, Triangles: ${result.triangleCount}`);

// Generate USDZ mesh
const usdzResult = schematic.toUsdz(pack, config);

// Generate raw mesh data
const raw = schematic.toRawMesh(pack, config);
const positions = raw.positionsFlat(); // Float32Array
const indices = raw.indices(); // Uint32Array
```

### Per-Region and Per-Chunk Meshing

```javascript
// Per region
const multi = schematic.meshByRegion(pack, config);
const names = multi.getRegionNames();
names.forEach(name => {
    const mesh = multi.getMesh(name);
    // use mesh.glbData
});

// Per chunk
const chunks = schematic.meshByChunk(pack, config);
const coords = chunks.getChunkCoordinates(); // [[x,y,z], ...]

// Custom chunk size
const chunks32 = schematic.meshByChunkSize(pack, config, 32);
```

### Resource Pack Querying

```javascript
const blockstates = pack.listBlockstates();
const models = pack.listModels();
const json = pack.getBlockstateJson("minecraft:stone");
const info = pack.getTextureInfo("minecraft:block/stone");
// { width, height, isAnimated, frameCount }

// Add custom entries
pack.addBlockstateJson("custom:block", jsonString);
pack.addModelJson("custom:block/my_block", modelJson);
pack.addTexture("custom:texture", 16, 16, rgbaBytes);
```

## See Also

- [SchematicBuilder Guide]../shared/guide/schematic-builder.md
- [TypedCircuitExecutor Guide]../shared/guide/typed-executor.md
- [Circuit API Guide]../shared/guide/circuit-api.md
- [Unicode Palette Reference]../shared/unicode-palette.md
- [NPM Package]https://www.npmjs.com/package/nucleation