# MCSchemora documentation > Build, edit, convert, and render Minecraft schematics with Python, Rust, and browser WASM. Generated from the website's Markdown sources. Includes quickstarts, SDK chapters, examples, and API references. Check installed package signatures when versions differ. ## Contents - [MCSchemora](https://tiltedlabs-ai.github.io/mcschemora/) - [Developer quickstart](https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/) - [Agent quickstart](https://tiltedlabs-ai.github.io/mcschemora/quickstart/agents/) - [Schematics](https://tiltedlabs-ai.github.io/mcschemora/sdk/schematics/) - [Editing](https://tiltedlabs-ai.github.io/mcschemora/sdk/editing/) - [Palettes](https://tiltedlabs-ai.github.io/mcschemora/sdk/palettes/) - [Inspection](https://tiltedlabs-ai.github.io/mcschemora/sdk/inspection/) - [Costs](https://tiltedlabs-ai.github.io/mcschemora/sdk/materials-and-costs/) - [Conversion](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/) - [Rendering](https://tiltedlabs-ai.github.io/mcschemora/sdk/rendering/) - [Validation](https://tiltedlabs-ai.github.io/mcschemora/sdk/validation/) - [Minecraft data](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/) - [Examples](https://tiltedlabs-ai.github.io/mcschemora/examples/) - [Importing a farm](https://tiltedlabs-ai.github.io/mcschemora/examples/import-farm/) - [Litematica to WorldEdit](https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-schem/) - [Litematica to structure NBT](https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-nbt/) - [Export a material list](https://tiltedlabs-ai.github.io/mcschemora/examples/material-list/) - [Raw ingredients](https://tiltedlabs-ai.github.io/mcschemora/examples/raw-materials/) - [Compare palette costs](https://tiltedlabs-ai.github.io/mcschemora/examples/compare-palettes/) - [Restyle a workshop](https://tiltedlabs-ai.github.io/mcschemora/examples/restyle-workshop/) - [Replace blocks](https://tiltedlabs-ai.github.io/mcschemora/examples/replace-blocks/) - [Rotate a schematic](https://tiltedlabs-ai.github.io/mcschemora/examples/rotate-schematic/) - [Layer diagrams](https://tiltedlabs-ai.github.io/mcschemora/examples/layer-diagrams/) - [Batch conversion](https://tiltedlabs-ai.github.io/mcschemora/examples/batch-conversion/) - [Island banner](https://tiltedlabs-ai.github.io/mcschemora/examples/banner/) - [Rainbow reef](https://tiltedlabs-ai.github.io/mcschemora/examples/reef/) - [Jade mountain scroll](https://tiltedlabs-ai.github.io/mcschemora/examples/jade-scroll/) - [Eiffel Tower](https://tiltedlabs-ai.github.io/mcschemora/examples/eiffel-tower/) - [Python API](https://tiltedlabs-ai.github.io/mcschemora/reference/python/) - [Browser WASM API](https://tiltedlabs-ai.github.io/mcschemora/reference/wasm/) - [Formats](https://tiltedlabs-ai.github.io/mcschemora/reference/formats/) - [Data sources](https://tiltedlabs-ai.github.io/mcschemora/reference/sources/) - [Rust](https://tiltedlabs-ai.github.io/mcschemora/languages/rust/) - [Browser WASM](https://tiltedlabs-ai.github.io/mcschemora/languages/wasm/) - [Contributing](https://tiltedlabs-ai.github.io/mcschemora/contributing/) --- Source: https://tiltedlabs-ai.github.io/mcschemora/ # MCSchemora MCSchemora is a Minecraft schematic SDK designed to be a simple and fast interface to programmatically create Minecraft schematics. ![Floating islands built and rendered with MCSchemora](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/banner.png) ## Why MCSchemora? Minecraft schematic libraries have traditionally been extremely fragmented, where often tools are directly hosted on closed webpages that require tons of jumping around. Furthermore, existing authoring interfaces tend to be quite difficult to work with, especially for agents who require clean and well documented interfaces that can handle all the small intricacies and weirdness of Minecraft blocks. MCSchemora is designed to address these issues by abstracting away all the engineering, cataloging, and authoring finnickiness to allow developers and agents to easily examine, edit, and deploy Minecraft schematics. By keeping the core interface and functionality small and Pythonic, MCSchemora can better support different agentic harnesses that don't need to learn specialized conventions to use the system while also easily integrating with existing packages that might be more familiar. ## MCSchemora for agents The full documentation is available as Markdown in [llms.txt](https://tiltedlabs-ai.github.io/mcschemora/llms.txt), generated from the same sources as this website on every build. It includes the quickstarts, MCSchemora chapters, examples with their code, and API references. For example, paste the documentation with this prompt: ```text Documentation: {paste the contents of llms.txt here} --- Using this documentation, write a Python script that loads a Litematica build, replaces oak materials with birch while preserving compatible block states, compares the raw-material estimates, and saves a new schematic and PNG preview. Report changed blocks, replacements you could not verify, and export/render diagnostics. Use the installed package's signatures if its version differs from these docs. ``` You can use the same format for API questions: replace the build request with your question. The [agent quickstart](https://tiltedlabs-ai.github.io/mcschemora/quickstart/agents/#use-the-full-documentation) explains how to combine the documentation with local API inspection. --- Source: https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/ # Developer quickstart Build a small workshop, save it as a schematic, and render a cutaway of its interior. Keeping the build in a script lets you recreate it with different materials or dimensions. MCSchemora handles versioned block states, paired placements, file export, and previews through the same API; [why MCSchemora](https://tiltedlabs-ai.github.io/mcschemora/#why-mcschemora) explains the motivation and agent workflow. ## Setup Use [uv](https://docs.astral.sh/uv/getting-started/installation/) with Python 3.10 or later. After installation, run: ```sh uv init --python 3.12 uv add mcschemora ``` Creating or loading a schematic downloads required catalogs on first use; textured rendering also downloads visual assets. See [offline setup](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/) if your environment restricts network access. ## Create a schematic ```python from pathlib import Path from mcschemora import Schematic, bed, block, chest, item scene = Schematic.create(version="1.21.1") region = scene.region() ``` A `Schematic` follows Litematica's model of a mutable build with Minecraft version metadata, blocks, and named regions. Edits through the region update that build. ### Structure ```python floor = region.select(start=(0, 0, 0), size=(7, 1, 7)) floor.fill(block("stone_bricks")) for x, z in ((0, 0), (6, 0), (0, 6), (6, 6)): region.select(start=(x, 1, z), size=(1, 3, 1)).fill(block("oak_log", axis="y")) region.select(start=(0, 4, 0), size=(7, 1, 7)).fill(block("oak_slab", type="bottom")) ``` Selections describe areas to edit: the floor is a 7 × 1 × 7 box, and each pillar is a 1 × 3 × 1 box. Positions are `(x, y, z)`, with Y pointing up. ### Block states ```python region.set((4, 1, 2), block("crafting_table")) region.set((4, 1, 1), block("furnace", facing="west")) print(region.get((4, 1, 1))) ``` Use `set` to place a single block and `get` to read its state. Here the print shows the furnace's full state, including its facing and default properties. `block("furnace")` expands the ID to `minecraft:furnace`. To find valid properties for a block, call `scene.registry.describe("furnace")`. For a generated shape, use `region.set_many(placements)` to submit `(position, block)` pairs in one batch. The [building guide](https://tiltedlabs-ai.github.io/mcschemora/sdk/schematics/) covers both in more detail. ### Placements ```python region.place(bed(color="red", head_toward="north"), at=(1, 1, 4)) region.place(chest(items={0: item("stone", count=64)}), at=(4, 1, 4)) ``` The bed helper places both halves, and the chest helper adds 64 stone in inventory slot 0. `place` rejects occupied destinations by default. Using `set` for these placements would require constructing the paired blocks or attached data yourself. ## Validation and export Append the validation and export steps: ```python output = Path("output") output.mkdir(exist_ok=True) report = scene.validate() print(report) if report.errors: raise SystemExit("Fix the validation errors before exporting.") scene.save(output / "workshop.schem") diagnostics = scene.export_png(output / "workshop.png", size=(800, 600), y=(0, 3)) for diagnostic in diagnostics: print(diagnostic) ``` `validate` checks supported Java game rules without changing the build. Read its warnings and unknown checks along with any errors. This workshop should print `No issues found.` after the furnace state. The `.schem` extension selects Sponge schematic output. `export_png` returns render diagnostics; `y=(0, 3)` hides the roof in the preview while keeping it in the schematic. Render ranges include both endpoints. Run the script: ```sh uv run build.py ``` Open `output/workshop.png` to inspect it. Rendering this version can also print a notice that it uses the shared Java 1.21.6 visual bundle. To place the saved build in Minecraft, follow the [WorldEdit or Litematica instructions](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/#minecraft-import). ### Editing Save this as `edit.py` in the same project: ```python from mcschemora import Schematic, block scene = Schematic.load("output/workshop.schem") area = scene.region().select(start=(0, 0, 0), size=(7, 5, 7)) area.replace("oak_log", block("birch_log", axis="y")) scene.save("output/birch-workshop.schem") print(scene.export_png("output/birch-workshop.png", size=(800, 600), y=(0, 3))) ``` Run `uv run edit.py`. It replaces the pillars and writes new files, leaving the original workshop untouched. For rotation, copies, and named regions, continue with the [editing guide](https://tiltedlabs-ai.github.io/mcschemora/sdk/editing/). ## Result The preview shows the original workshop with its roof hidden. The downloadable script creates the same scene and accepts `--output` to choose another directory. [Download the build script](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/build.py) [Download the schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.schem) ![Workshop generated by the developer quickstart](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.png) --- Source: https://tiltedlabs-ai.github.io/mcschemora/quickstart/agents/ # Agent quickstart Give your coding agent the setup prompt below, then describe the build or edit you want. It can use MCSchemora to write blocks in a reproducible script, inspect errors, and render the result. The pavilion on this page was built that way. Read [why MCSchemora](https://tiltedlabs-ai.github.io/mcschemora/#why-mcschemora) for the workflow, or give the agent the full documentation before starting. ## Use the full documentation [llms.txt](https://tiltedlabs-ai.github.io/mcschemora/llms.txt) contains the documentation as one Markdown file, including the API references and expanded example code. It is generated with each website build. Download it and attach or paste it into your assistant's context in Cursor, Windsurf, GitHub Copilot, Claude, or another tool. For a documentation question, use: ```text Documentation: {paste the contents of llms.txt here} --- Based on this documentation, how do I apply a reusable material profile across all regions without resetting compatible block states? Show the Python API calls and explain how to check which replacements occurred. ``` For a build request, put the dimensions, Minecraft version, material palette, and required output files after the documentation. The setup prompt below adds the validation, rendering, and export checks. If the full file exceeds your tool's context limit, include the relevant SDK chapter and API section instead. The bundle matches the website build, so check the installed package's signatures and docstrings if you are using a different version. The file gives the agent API reference material; inspecting a preview still requires an image tool. ## Setup ```text Set up MCSchemora in this project and learn its API before working on my Minecraft build request. Use uv for Python setup and execution. Inspect the project first. If it already declares mcschemora, run uv sync. For an existing uv project without it, run uv add mcschemora. In an empty directory, start with: uv init --python 3.12 uv add mcschemora Run Python scripts with uv run script.py. Read https://tiltedlabs-ai.github.io/mcschemora/llms.txt for the full SDK docs and examples. If it exceeds your context limit, use the relevant chapters and https://tiltedlabs-ai.github.io/mcschemora/reference/python/ instead. Check installed signatures and docstrings when a method is uncertain. The installed package is authoritative if its version differs from the website. Use this object model: - Schematic.create(version="1.21.1") starts a new Java build. Pin the version requested by the user. Schematic.load(path) opens an existing file. - scene.region() returns the default named region. Its block positions are local (x, y, z), with Y pointing up. Region origins place them globally. - block("stone_bricks") describes a block. Properties such as facing or axis depend on that block and the selected Minecraft version. Query supported properties with scene.registry.describe("block_name") before guessing. - region.set(position, block) writes one cell. select(start=..., size=...) selects a box by cell counts; fill(block) edits its cells. set_many accepts a mapping or iterable of (position, block) pairs for generated geometry. - Use placement helpers for beds, doors, signs, and inventory chests. Blocks, free entities, and attached block-entity data have separate APIs. Before editing, establish the input file or requested dimensions, Minecraft version, materials, and output paths. Keep randomness seeded and the build reproducible in a standalone script. Preserve input files unless the user asked to replace them. After changes, run scene.validate() and read its errors, warnings, and unknown checks. Fix errors; inspect changes and skipped reasons if using repair(). Render a preview with scene.export_png(...) and read its diagnostics. Open the image if your tools support it, check the requested details, and revise. Validation does not simulate ticks, and a render does not prove that a farm or redstone machine works. Before saving, check scene.check_export(format="schem") or the requested format. Resolve errors and review any losses. Save with scene.save(path). Use .litematic to retain named regions. Create output directories first. Deliver the script, schematic, and PNG with the Minecraft version, validation result, and unresolved export/render diagnostics. Say whether you inspected the image. When setup is ready, continue with the user's build request. ``` ## Build a schematic ```text Build a mountain pavilion for Minecraft Java 1.21.1 within 32 × 24 × 32 blocks. Use spruce, stone bricks, and dark prismarine. Add a raised floor, an entrance, a pitched roof, a path, and a waterfall with surrounding terrain. Write a standalone agent_pavilion.py that recreates it. Save pavilion.schem and pavilion.png in output/. Keep randomness seeded, validate the build, and inspect the rendered image before delivering the files. ``` ## Review the result The subagent produced a 29 × 20 × 28 build containing 4,004 non-air blocks. After inspecting the PNG and a render diagnostic, it revised the foliage. The final validation, export checks, and render diagnostics reported no issues. To reproduce it, download the script below. In the uv project you set up, run: ```sh uv run agent_pavilion.py ``` ## Result [Download the build script](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/agent_pavilion.py) [Download the schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/agent-pavilion.schem) ![Mountain pavilion generated by a coding agent using MCSchemora](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/agent-pavilion.png) --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/schematics/ # Schematics A schematic stores blocks in named regions (such as how it is down in `.litematic` files). Each region has its own coordinates, so you can build parts separately and position them within the schematic. Use `set` for individual blocks, selections for areas, and batches for generated geometry. ## Create a schematic ```python from mcschemora import Schematic, bed, block, chest, door, item, sign scene = Schematic.create(version="1.21.1") region = scene.region() region.select(start=(0, 0, 0), size=(7, 1, 7)).fill(block("stone_bricks")) region.set((4, 1, 1), block("furnace", facing="west")) ``` `scene.region()` returns the default region, named `main`, and edits through this handle update the schematic. Positions are `(x, y, z)`, with Y pointing up; negative coordinates are allowed. A selection starts at the inclusive `start` and extends for `size` cells, so this floor covers X and Z from 0 through 6 at Y=0. ## Block states `block("stone_bricks")` expands the name to `minecraft:stone_bricks`. Pass block states as keyword arguments, such as `facing="west"` or `axis="y"`. Writes are checked against the schematic's Minecraft version. Look up a block's supported properties before choosing a value: ```python print(scene.registry.describe("furnace")) print(region.get((4, 1, 1))) ``` The registry description includes the ID, properties, version, and numeric ID. When you read an empty cell, you get air. ## Batch writes Continue with the same region: ```python region.select(start=(0, 1, 0), size=(1, 3, 1)).fill(block("oak_log", axis="y")) region.set_many({ (4, 1, 2): block("crafting_table"), (6, 1, 0): block("oak_log", axis="y"), }) ``` The fill creates a three-block pillar, while `set_many` places the crafting table and second log together. It accepts a mapping or an iterable of `(position, block)` pairs and validates the entire batch before writing. If any input is invalid, the batch stays unwritten; if a coordinate appears more than once, the last entry wins. An iterable works well for procedural shapes such as the [rainbow reef](https://tiltedlabs-ai.github.io/mcschemora/examples/reef/). ## Placement helpers Placement helpers handle paired blocks and attached inventory or sign data: ```python region.place(bed(color="red", head_toward="north"), at=(1, 1, 4)) region.place(door(material="oak", facing="north"), at=(3, 1, 0)) region.place(chest(items={0: item("stone", count=64)}), at=(4, 1, 4)) region.place(sign(["Workshop", "Tools inside"]), at=(0, 1, 3)) ``` The anchor identifies the bed's foot, the door's lower block, or the sign or chest position. These helpers reject occupied destinations unless you pass `replace=True`. For the chest, the mapping keys are inventory slot numbers. ## Region coordinates Block operations use coordinates local to their region. A region's origin sets where those coordinates sit in the schematic: ```python tower = scene.add_region("tower", origin=(40, 0, 0)) tower.set((2, 1, 4), block("stone")) print(tower.to_global((2, 1, 4))) print(tower.to_local((42, 1, 4))) ``` The first conversion prints `(42, 1, 4)`; the second prints `(2, 1, 4)`. Rendering filters use global coordinates. Save as `.litematic` when you want to keep multiple regions; see [load, save, and convert](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/). The [developer quickstart](https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/) puts these operations together in a complete workshop. See [Region](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#region) and [placement helpers](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-bed) for signatures. ## Bounds and air New regions have no bounds until blocks are written. Handle `region.bounds is None` before selecting a whole region. Bounds have an inclusive `start` and a `size` in cells; the exclusive end is `start + size`. A selection includes air within its selected cells even though `get_all()` and `counts()` omit air. A rectangular fragment can clear destination cells wherever it contains selected air. A sparse selection copies only its selected cells. Deleting selected cells also removes attached data and selected entities; filling blocks leaves free entities unchanged. See [selections and transformations](https://tiltedlabs-ai.github.io/mcschemora/sdk/editing/). ## Generated geometry ```python wall = block("stone_bricks") region.set_many( ((x, y, z), wall) for x in range(7) for y in range(1, 4) for z in range(7) if x in (0, 6) or z in (0, 6) ) ``` This adds walls to the current scene. Start with a fresh scene if you want to keep the workshop unchanged for later examples. Immutable `Block` values can be reused across cells, and a generator avoids creating an extra Python list. `set_many` still validates and stores the whole batch before writing, so each batch must fit in memory. --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/editing/ # Editing Selections let you edit part of a region or transform a build as a whole. Start with `output/workshop.schem` from the [developer quickstart](https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/) and make a rotated copy with birch pillars. ## Transform a copy ```python from mcschemora import Schematic, block scene = Schematic.load("output/workshop.schem") region = scene.region() area = region.select(start=(0, 0, 0), size=(7, 5, 7)) copy = area.duplicate(offset=(10, 0, 0)) copy.rotate(steps=1) copy.replace("oak_log", block("birch_log", axis="y")) scene.save("output/workshops.schem") ``` `duplicate` leaves the original in place and returns a selection of the copy. Rotating that selection updates its coordinates and directional block states, including the furnace and bed. Each step is a quarter turn around Y; one positive step turns north toward west. ## Filters Continue with the same scene: ```python logs = area.select(block="oak_log") print(logs.counts()) logs.patch(axis="y") ``` A filter can match block IDs, properties, or both. It records the matching coordinates when you create the selection, then reads the current blocks at those coordinates as you edit. Use `get_all()` when you need an independent snapshot. ## Fragments ```python copy.flip(axis="x") copy.move(offset=(0, 0, 10)) fragment = area.copy() tower = scene.add_region("tower", origin=(40, 0, 0)) tower.set((0, 0, 0), fragment) scene.save("output/regions.litematic") ``` `copy()` creates an independent fragment anchored at its minimum corner. Pasting requires matching editions and Minecraft versions. Moving, rotating, and mirroring reject occupied targets by default; pass `replace=True` when you intend to overwrite them. Selected air can clear destination cells. The transformed selection follows its new coordinates, while other selections keep their own coordinates. You can rotate around Y and mirror across X or Z. Off-grid results and unsupported state transforms raise an error before the change commits. For whole-build replacements that retain compatible properties, use [palettes and material profiles](https://tiltedlabs-ai.github.io/mcschemora/sdk/palettes/). Selection replacement writes the supplied target block state. ## Selection contents Filtered selections remember the matching coordinates at the time they are created, without rerunning the filter after every edit. For example: ```python logs = area.select(block="oak_log") logs.replace("oak_log", block("birch_log", axis="y")) print(logs.counts()) ``` `logs` still selects the same cells and now reads birch logs. Create a fresh filtered selection to find the current oak logs. `get_all()` returns an independent dictionary of current non-air blocks. `counts()` groups full states; `describe_layer(y=...)` returns a region-local text grid and state legend. Text layers are limited to 65,536 cells of X/Z area. ## Collisions Move, rotate, and mirror check for occupied targets outside the source selection before changing the build. A move can overlap its own source cells; pass `replace=True` to allow overwriting other destinations. Because selected air also clears target cells, a bounding box containing mostly air can affect a large area. Transformations validate coordinates, block states, and attached content before committing. Unsupported state changes, off-grid pivots, or collisions raise an error. Each call commits separately. An earlier edit remains applied if a later operation fails. Rotation supports quarter turns around Y; mirroring supports X and Z. A pivot or mirror plane is in region-local coordinates. Custom pivots must map the integer cell grid back onto itself. After the transformation, the selected coordinates move with the content; other selection handles retain their own membership. ## Entities and deletion `copy()` snapshots selected cells, attached data, and entities into an independent fragment, anchored at its minimum selected corner. Pasting through `Region.set(at, fragment)` requires matching Minecraft editions and versions. If versions differ, convert the source and inspect its conversion losses first. Copied free entities receive new references. `fill()` changes blocks while leaving free entities unchanged. `delete()` clears selected blocks, their attached data, and selected entities. ## Export transformed builds The [rotation example](https://tiltedlabs-ai.github.io/mcschemora/examples/rotate-schematic/) saves the transformed coordinates and directional states, so another importer loads the rotated build. Reload your output to inspect its block states and inventories, then test any redstone mechanisms in-game: transforms do not simulate ticks. ## Run the example [Download edit.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/edit.py) to make the rotated birch copy with a preview. Give it the file from the quickstart: ```sh uv run --with mcschemora edit.py output/workshop.schem ``` It writes `output/workshops.schem` and `output/workshops.png`, leaving the input file untouched. The copied workshop contains 12 birch logs. ```python import argparse from pathlib import Path from mcschemora import Schematic, block def main(): parser = argparse.ArgumentParser(description="Copy, rotate, and restyle the workshop.") parser.add_argument("source", type=Path, help="Workshop schematic created by build.py") parser.add_argument("--output", type=Path, default=Path("output")) args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=True) schematic = Schematic.load(args.source) area = schematic.region().select(start=(0, 0, 0), size=(7, 5, 7)) copy = area.duplicate(offset=(10, 0, 0)) copy.rotate(steps=1) copy.replace("oak_log", block("birch_log", axis="y")) print(f"Original bounds: {area.bounds}") print(f"Copy bounds: {copy.bounds}") print(f"Birch logs: {copy.counts()['minecraft:birch_log[axis=y]']}") print(schematic.validate()) schematic.save(args.output / "workshops.schem") diagnostics = schematic.export_png(args.output / "workshops.png", size=(1200, 600), y=(0, 3)) print("Saved workshops.schem and workshops.png") for diagnostic in diagnostics: print(diagnostic) if __name__ == "__main__": main() ``` ![Workshop and a rotated copy with birch pillars](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshops.png) [Download the edited schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshops.schem) --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/palettes/ # Palettes A build's palette is the set of complete block states it uses, such as `minecraft:oak_log[axis=y]`. You can count those states to inspect a build, choose an authoring palette in Python, or apply a normalization profile to change its materials. Wiki imports and render exports have separate mappings for symbols and sprites. ## Count block states Load the [workshop](https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/) and count its non-air states: ```python from collections import Counter from mcschemora import Schematic scene = Schematic.load("output/workshop.schem") states = Counter() for name in scene.regions: region = scene.region(name) bounds = region.bounds if bounds is not None: states.update(region.select(start=bounds.start, size=bounds.size).counts()) for state, count in states.most_common(): print(state, count) ``` Counts use full state strings, so differently oriented stairs have distinct entries. To group them by block ID, use `state.split("[", 1)[0]`. Each region contributes its stored cells, including any that overlap another region at the same world position. These counts describe the palette; edits happen through selections or normalization, without a separate palette handle. ## Authoring palettes ```python from mcschemora import block palette = { "wall": block("stone_bricks"), "pillar": block("oak_log", axis="y"), "roof": block("oak_slab", type="bottom"), } region = scene.region() region.select(start=(0, 0, 0), size=(7, 1, 7)).fill(palette["wall"]) ``` An authoring palette is a collection of immutable `Block` values that you can reuse across placements. Changing its dictionary affects future writes; existing cells keep their states. Every write is checked against the destination schematic's catalog. ## Material replacement For a whole-build material change, normalize by identifier: ```python changes = scene.normalize( keep=["chest", "furnace"], replace={"oak_log": "birch_log", "stone_bricks": "deepslate_bricks"}, ) print(changes["changed"]) print(changes["replacements"]) ``` Normalization changes matching IDs across all regions while retaining compatible properties such as log axis, stair facing, and slab type. It removes properties the target does not support and uses defaults for new ones; values of shared properties must remain valid. Attached data also needs a compatible block-entity type, so a chest-to-stone replacement is skipped and the chest keeps its inventory. `Selection.replace(identifier, block(...))` instead writes the exact target block description to matching selected cells. Use it when deliberately setting the target state. To alter a property without changing material, filter a selection and call `patch(...)`. See [selections and transformations](https://tiltedlabs-ai.github.io/mcschemora/sdk/editing/). ## Profiles Save a profile with explicit edition, preserved IDs, replacement groups, and an optional fallback. This is the profile used by the [workshop restyling example](https://tiltedlabs-ai.github.io/mcschemora/examples/restyle-workshop/): ```json title="workshop_palette.json" { "edition": "java", "keep": ["minecraft:chest", "minecraft:furnace", "minecraft:red_bed"], "replacements": [ {"from": ["minecraft:oak_log"], "to": "minecraft:birch_log"}, {"from": ["minecraft:oak_slab"], "to": "minecraft:birch_slab"}, {"from": ["minecraft:stone_bricks"], "to": "minecraft:deepslate_bricks"} ] } ``` ```python changes = scene.normalize("workshop_palette.json") ``` Python accepts a profile file path or the bundled name `redstone`. Rust accepts a parsed `normalize::Profile`; browser WASM accepts a profile object or the bundled name. For inline Python rules, pass the `keep`, `replace`, and `fallback` keyword arguments. The profile argument does not accept Python dictionaries. | Field | Meaning | | --- | --- | | `edition` | Must match the schematic's edition. | | `keep` | IDs that stay unchanged across all states and attached data. | | `replacements` | Groups with `from` ID lists and a `to` ID. | | `fallback` | Optional material for other eligible, unpreserved blocks. Omit it to retain unlisted materials. | Profiles reject unknown fields and malformed input, and block names must exist in the schematic's version. A valid profile can still contain a replacement that is incompatible with the content of a particular build. ## Rule precedence Explicit `keep` takes priority over replacements. Inline replacements override profile replacement/keep rules; an explicit fallback overrides the profile fallback. Replacement chains such as A→B→C are not followed. Incompatible or chained mappings can be skipped. ```python changes = scene.normalize( "redstone", keep=["oak_log", "oak_slab"], replace={"stone_bricks": "deepslate_bricks"}, ) ``` The redstone profile preserves listed mechanisms and related materials, maps material families to representative blocks, and replaces other eligible blocks with gray concrete. Review decorative changes before saving and test mechanisms in-game after simplification. Read the [bundled profile](https://github.com/tiltedlabs-ai/mcschemora/blob/main/data/profiles/java/redstone.json) when adapting it to a particular build. ## Compare variants The report gives the changed-block count and sorted records of each source ID, target ID, and quantity. It can skip incompatible replacements without reporting a reason, so compare palette counts before and after to find unchanged blocks. Malformed profiles raise an error. Normalization edits the scene in place. For independent alternatives, reload the original or clone through `to_bytes(format="litematic")` and `from_bytes(...)`, checking the source's export report before accepting any losses. Assigning `variant = scene` only creates another reference to the same object. To compare costs, calculate a report before and after applying the profile, using the same version, recipe policy, and valuation profile. Check unpriced materials alongside the totals. See [materials and costs](https://tiltedlabs-ai.github.io/mcschemora/sdk/materials-and-costs/#valuation) and the [complete comparison example](https://tiltedlabs-ai.github.io/mcschemora/examples/compare-palettes/). ## Visual mappings For Wiki imports, `palette={"A": block("stone")}` resolves symbols into blocks. For sprite/blueprint exports, `sprites={"minecraft:stone": "BlockSprite:stone"}` chooses visual identifiers. Sprite overrides do not edit the schematic or affect cost calculations. See [rendering and blueprints](https://tiltedlabs-ai.github.io/mcschemora/sdk/rendering/). The [normalize reference](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#schematicnormalize) documents the callable interface; [replace](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#selectionreplace) and [patch](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#selectionpatch) cover selection edits. --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/inspection/ # Inspection Inspection reports describe the blocks and contents stored in a schematic, including inventories and entities. Load the [workshop](https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/) to inspect its structure and the 64 stone in its chest. ## Blocks and inventories ```python from mcschemora import Schematic scene = Schematic.load("output/workshop.schem") region = scene.region() print(region.bounds) print(region.get((4, 1, 4))) resources = scene.inspect() print(resources["blocks"]) print(resources["items"]) print(resources["inventories"]) ``` Block counts describe the placed structure, while item counts also include stored inventory contents. Inspection follows nested containers, equipment, and passengers. Check the diagnostics and `complete` field to see whether it could interpret everything that contributes to the totals. For a block-state count in one area, call `region.select(...).counts()`. To read non-air cells and their positions, use `region.get_all()`. For construction quantities, recipe ingredients, and EMC/EssentialsX values, see [materials and costs](https://tiltedlabs-ai.github.io/mcschemora/sdk/materials-and-costs/). ## Data managers `region.entities` manages free entities such as mobs. `region.block_entities` manages the [NBT](https://minecraft.wiki/w/NBT_format) attached to blocks such as chests. Both are separate from `get_all()`, which returns blocks only. See [Entities](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#entities) and [BlockEntities](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#blockentities) for adding, updating, or reading their typed SNBT. ## Completeness ```python report = scene.inspect() print(report["complete"], report["retained_data"]) for diagnostic in report["diagnostics"]: print(diagnostic["path"], diagnostic["message"]) print(report["identifiers"]) print(report["payload_fields"]) ``` If `complete=False`, inspection could not interpret some content; keep the diagnostic paths with any totals you export. The separate `retained_data` flag identifies imported data that MCSchemora preserves without fully modeling. Inspection can complete with this flag set, even though resizing, copying, or converting that data can still fail. The report also includes volume, data version, entity counts, moving-entity and outside-bounds flags, and maximum stack counts. These fields describe the stored schematic. Inspection does not execute commands, infer resources that commands could create, or certify a downloaded build as safe. ## Typed NBT ```python region = scene.region() existing = region.block_entities.get((4, 1, 4)) print(existing) region.block_entities.set( (4, 1, 4), '{id:"minecraft:chest",Items:[{Slot:0b,id:"minecraft:stone",count:64}]}', ) ``` Pass NBT as a typed SNBT string, keeping byte/short/long suffixes, lists, arrays, and compound structure intact. The compound must include its ID and be compatible with the owning block's block-entity type. Because `set` replaces the whole compound, read the existing value first if you need to preserve fields. To remove the attached NBT while keeping the block, call `remove(at)`. The common `chest` and `sign` [placement helpers](https://tiltedlabs-ai.github.io/mcschemora/sdk/schematics/#placement-helpers) handle version-specific data for normal authoring. Prefer those when a full custom compound is unnecessary. ## Entity references ```python from mcschemora import mob reference = region.entities.add(mob("sheep"), at=(2.5, 1.0, 2.5)) snapshot = region.entities.get(reference) region.entities.update(reference, position=(3.5, 1.0, 2.5)) print(snapshot.position, region.entities.get(reference).position) region.entities.remove(reference) ``` An `Entity` is an immutable snapshot, identified within the current schematic by a reference. These references are separate from Minecraft UUIDs and may change across exports. Iteration also snapshots the reference list, so later edits leave an existing iterator unchanged. To move an entity without replacing its NBT, use `update(position=...)` with coordinates local to its region. `update(nbt=...)` replaces the full compound, which must include the required ID. `scene.metadata` is also a full typed SNBT compound. Assigning it replaces all schematic metadata, and conversion may omit it. Preview data changes with a fresh inspection and [export report](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/#export-reports). ## Combined reports `inspect_schematics` preserves individual reports in `placements` and sums their resource counts. Counts use submitted IDs and include overlaps. Inputs retain their coordinates and versions, and the call leaves their schematics separate. `initial_items` adds existing inventory to stored item totals. Calculate remaining construction materials separately. The combined `complete` flag is false if any input inspection is incomplete. To audit containers, use the inventory paths and item quantities. To estimate construction, use [material_cost](https://tiltedlabs-ai.github.io/mcschemora/sdk/materials-and-costs/) instead. Browser WASM does not expose the native inventory/entity inspection managers; check the [binding support table](https://tiltedlabs-ai.github.io/mcschemora/reference/formats/#language-bindings) before porting a Python inspection workflow to the browser. ## Combine schematics ```python from mcschemora import inspect_schematics combined = inspect_schematics( [scene], initial_items=[("minecraft:stone", 64)], ) print(combined["blocks"], combined["items"], combined["entities"]) print(combined["placements"][0]["inventories"]) ``` Pass more loaded schematics in the list to combine their resource counts. `initial_items` adds existing inventory to the combined item totals. Inspection uses submitted IDs without converting versions. It does not infer items that could be created by commands or other privileged payloads. --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/materials-and-costs/ # Costs MCSchemora supports two ways to calculate a build's cost: material costs and valuation. ## Material cost ```python from mcschemora import Schematic scene = Schematic.load("output/workshop.schem") materials = scene.material_cost() print(materials["items"]) print(materials["raw_materials"]) ``` The workshop needs 49 stone bricks, 12 oak logs, 49 oak slabs, one red bed, one chest, one furnace, and one crafting table. The bed counts once despite occupying two cells, and the chest's stored 64 stone stay outside this construction bill. ## Recipe expansion Material costs use fractional recipes, dividing ingredient quantities by the number of items each recipe produces. For instance, five oak planks require 1.25 oak logs. Recipe expansion uses the first acyclic path through the recipe catalog to declared primitives. The pinned workshop report uses beetroot for red dye and cobbled deepslate for the furnace. A block or item with no available recipe counts as a primitive in the final cost list. ```python import csv import json from pathlib import Path destination = Path("output/materials") destination.mkdir(parents=True, exist_ok=True) (destination / "materials.json").write_text(json.dumps(materials, indent=2) + "\n") with (destination / "materials.csv").open("w", newline="") as output: writer = csv.writer(output) writer.writerow(("item", "quantity")) writer.writerows(sorted(materials["items"].items())) ``` For a complete script that exports both CSV views and valuation reports, use [export a material list](https://tiltedlabs-ai.github.io/mcschemora/examples/material-list/). The [raw-ingredient example](https://tiltedlabs-ai.github.io/mcschemora/examples/raw-materials/) explains the same report from a resource-planning perspective. ## Valuation Use a valuation profile to estimate a build's value from its raw ingredients. ```python for profile in ("emc", "essentialsx"): value = scene.value_cost(profile) print(profile, value["total"], value["unpriced"]) ``` We support `emc` and `essentialsx` valuations. See [valuation sources and derivation](https://github.com/tiltedlabs-ai/mcschemora/blob/main/data/cost/java/values/SOURCE.md) for more details. For the pinned workshop, EMC totals 1101 and prices every ingredient. EssentialsX totals 147 but leaves several ingredients unpriced. --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/ # Conversion Use `.schem` for WorldEdit builds and `.litematic` when you need named regions. MCSchemora also reads and writes Java structure files, Bedrock structures, and Minecraft Wiki blueprints. The [formats table](https://tiltedlabs-ai.github.io/mcschemora/reference/formats/) lists their limits. ## Load and save Start with the file from the [developer quickstart](https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/): ```python from mcschemora import Schematic scene = Schematic.load("output/workshop.schem") print(scene.edition, scene.version, scene.regions) scene.save("output/workshop.litematic") ``` The file extension selects the format. Loading preserves the file's Minecraft version; saving without `version=` keeps it. Explicit codec names are available through `format=`, for example `format="schem2"` for Sponge v2. ## Export reports ```python report = scene.check_export(format="litematic", version="1.20.4") print(report) if not report.errors and not report.losses: scene.save("output/workshop-1.20.4.litematic", version="1.20.4") ``` An export report distinguishes errors, which block writing, from losses, which describe information the target cannot store. Resolve the errors and review each omission before passing `allow_loss=True`. Version changes can also require intermediate catalogs; see [offline conversion](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/#conversion-routes). ## Named regions Save a multi-region build as `.litematic` to keep its regions. For a format with one region, inspect the flattening report: ```python report = scene.check_export(format="schem", flatten=True) print(report) ``` With `flatten=True`, nonoverlapping region bounds are combined into one region. The report records the loss of region names and boundaries, which also requires `allow_loss=True` to accept. Resolve overlapping region bounds before flattening. ## Bytes ```python content = scene.to_bytes(format="schem") restored = Schematic.from_bytes(content, format="schem") print(restored.region().bounds) ``` For binary NBT from an untrusted source, set `max_unpacked_bytes` when loading to cap decompressed input size. See [load](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#schematicload) and [from_bytes](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#schematicfrom_bytes). ## Import limits ```python scene = Schematic.load( "output/workshop.schem", max_unpacked_bytes=64 * 1024 * 1024, ) for diagnostic in scene.import_diagnostics: print(diagnostic) ``` The `max_unpacked_bytes` limit applies to decompressed binary NBT. An application accepting uploads also needs limits on file size and subsequent memory, CPU, text, rendering, and output workloads. Blueprint imports require an explicit version; `version`, `origin`, and symbol-palette overrides apply only to those imports. ## File writes `save()` encodes the schematic, then replaces the destination through a temporary file in the same directory. Create the parent directory first. If an ordinary write is incomplete, the previous destination stays intact. This protection applies to each schematic save; reports, PNGs, and other batch outputs are written separately. `check_export` and `to_bytes` leave the scene unchanged. To create an independent scene at the target version, review the export report, encode, and decode the result. Read the new scene's import notices. Keep source and destination paths separate when the original is needed for comparison. ## Retained data Some imported payloads are retained without support for every edit, so copying or resizing them can fail. Format conversion can also lose metadata, scheduled updates, origins, or region boundaries. Keep the export report with the output file so these omissions remain visible. Bedrock import and `.mcstructure` output retain supported Bedrock data. General Bedrock-to-Java block/entity mapping is not implemented, and Java-to-Bedrock export supports only a limited simple-block subset. Test Create and MineColonies integrations separately; exporting structure NBT alone does not establish compatibility with those mods. ## Conversion pipelines For each input, decode the file and read its import notices before choosing a target format and version. Check compatibility with `check_export`, resolve errors, and accept any losses before encoding. Keep the diagnostics with the output. The target extension selects the codec. `schem` exports Sponge v3; use explicit `format="schem2"` when the importer needs Sponge v2. `nbt` means Java structure NBT, not arbitrary NBT documents. `.schematic` is the legacy MCEdit format and is not an alias for `.schem` here. See the [format table](https://tiltedlabs-ai.github.io/mcschemora/reference/formats/) before selecting inputs. The [multi-region conversion example](https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-schem/) demonstrates two explicit losses when flattening the supplied file. The [NBT example](https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-nbt/) shows the separate Java structure route. For several inputs, [batch conversion](https://tiltedlabs-ai.github.io/mcschemora/examples/batch-conversion/) produces a report per file and leaves blocked files unsaved. ## Command line [Download convert.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/convert.py) to inspect and convert a file without writing your own script. Use the workshop from the quickstart: ```sh uv run --with mcschemora convert.py output/workshop.schem output/workshop.litematic ``` For this build, it prints: ```text Edition: java; version: 1.21.1 Regions: main No issues found. Saved workshop.litematic ``` Add `--version 1.20.4` to target that Java version. Use `--flatten` for multiple nonoverlapping regions, and add `--allow-loss` only after reviewing the reported omissions. The converter stops before writing if it finds an error or an unaccepted loss. ```python import argparse from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser(description="Inspect and convert a schematic.") parser.add_argument("source", type=Path) parser.add_argument("destination", type=Path) parser.add_argument("--version", help="Target Minecraft Java version") parser.add_argument("--flatten", action="store_true") parser.add_argument("--allow-loss", action="store_true") args = parser.parse_args() schematic = Schematic.load(args.source) print(f"Edition: {schematic.edition}; version: {schematic.version}") print(f"Regions: {', '.join(schematic.regions)}") format_name = ( "blueprint" if args.destination.suffix == ".wiki" else args.destination.suffix.lstrip(".") ) report = schematic.check_export(format=format_name, version=args.version, flatten=args.flatten) print(report) if report.errors or (report.losses and not args.allow_loss): raise SystemExit("Export blocked; resolve errors or explicitly accept the reported losses.") args.destination.parent.mkdir(parents=True, exist_ok=True) schematic.save( args.destination, version=args.version, flatten=args.flatten, allow_loss=args.allow_loss ) print(f"Saved {args.destination.name}") if __name__ == "__main__": main() ``` [Download the converted workshop](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.litematic) ## Minecraft import For WorldEdit, copy the `.schem` file into the WorldEdit configuration's `schematics` directory. On a Bukkit server this is normally `plugins/WorldEdit/schematics/`. Load it with `//schem load workshop`, then paste with `//paste` at the intended location. Pasting changes world blocks; `//undo` reverses the operation. See [WorldEdit's clipboard guide](https://worldedit.enginehub.org/en/latest/usage/clipboard/#loading-and-saving) for configuration paths, formats, and paste options. For Litematica, save `.litematic` and place it in your Minecraft instance's `schematics` directory. Open the mod menu with `M`, then choose **Load Schematics**. Litematica displays a build guide in the world; loading a file does not place its blocks. See the [Litematica guide](https://github.com/maruohon/litematica/wiki). Use a game and importer version compatible with the blocks in your exported file. Changing a file extension alone does not convert it. --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/rendering/ # Rendering Render a schematic as a textured image or 3D model, or use sprite layers and Wiki blueprints to make building guides. For a cutaway of the [quickstart workshop](https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/), load `output/workshop.schem` and hide the roof. ## Textured PNGs ```python from mcschemora import Schematic scene = Schematic.load("output/workshop.schem") diagnostics = scene.export_png("output/preview.png", size=(800, 600), y=(0, 3)) for diagnostic in diagnostics: print(diagnostic) ``` The default view is isometric, and `y=(0, 3)` shows the interior by hiding the roof at Y=4. Cropping affects the image and leaves the schematic unchanged. PNG and GLB rendering download visual assets on first use and temporarily convert the palette for the shared Java 1.21.6 visual bundle. Review the returned diagnostics for unsupported geometry and approximations, particularly with newer blocks. See [versions and offline use](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/#rendering-coverage). ## Views and layers ```python scene.export_png("output/top.png", view="top", grid=True, y=1) ``` Use `isometric`, `top`, `bottom`, `north`, `south`, `east`, or `west` for `view`. Axis filters `x`, `y`, and `z` use global coordinates. A single integer selects one layer; a pair includes both endpoints. Block selections use a cell count for `size`. ## 3D models ```python diagnostics = scene.export_glb("output/workshop.glb") print(diagnostics) ``` A compatible 3D viewer can open the GLB's model and textures. Keep the schematic file as well if you need editable Minecraft block data. ## Sprite layers ```python diagnostics = scene.export_sprites("output/layer.png", y=1, grid=True) print(diagnostics) ``` Sprite diagrams use bundled Minecraft Wiki icons without downloading visual assets. Because icons cannot represent every block state or attached field, check the returned diagnostics for omitted data. ## Wiki blueprints ```python diagnostics = scene.export_blueprint("output/workshop.wiki", name="Workshop") print(diagnostics) ``` This writes layered-blueprint markup for Minecraft Wiki pages. It stores sprite grids with less detail than a schematic. For input markup, provide an explicit Minecraft version and check inferred defaults: ```python from mcschemora import block template = "{{layered blueprint|A=BlockSprite:stone|----Floor|A}}" imported = Schematic.from_bytes( template.encode(), format="blueprint", version="1.21.1", palette={"A": block("stone")}, ) print(imported.import_diagnostics) ``` See [export_png](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#schematicexport_png), [export_sprites](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#schematicexport_sprites), and [from_bytes](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#schematicfrom_bytes) for all options. ## Coordinates and overlaps Axis filters use global schematic coordinates even when `region=` selects one named region. A tuple includes both endpoints. For a region at origin `(40, 0, 0)`, local X=2 is filtered with `x=42`. Cropping leaves stored blocks, bounds, inventories, and cost reports unchanged. Identical blocks and attached data at a shared global position render once. Conflicting overlapping content raises an error; select one region or resolve the conflicts before rendering. Material-cost and inspection reports count each region's stored placements, including overlaps. ## Image options PNGs have a transparent background and accept integer dimensions from 1 through 4096 on each axis. Isometric and cardinal views are framed automatically, with cardinal names describing the viewer's location. Use `threads=` to limit native rasterizer workers; catalog loading and geometry preparation have separate workloads. Use a region or axis crop for focused views of a large structure. Even a small image can require preparing a large amount of geometry. `grid=True` draws block outlines, with entities excluded from that outlined PNG mode. ## Layer guides The [layer-guide example](https://tiltedlabs-ai.github.io/mcschemora/examples/layer-diagrams/) calculates global Y bounds across regions, writes one sprite PNG per layer, and records each file's Y coordinate and diagnostics in a manifest. Empty gaps remain part of that global sequence. Sprites accept cardinal views, cell sizes from 1 to 128 pixels, grid lines, optional entity icons, and overrides by block ID or full state string: ```python diagnostics = scene.export_sprites( "output/stone-layer.png", y=0, grid=True, sprites={"minecraft:stone_bricks": "BlockSprite:stone"}, ) print(diagnostics) ``` An override changes the icon while keeping the build's material. Wiki import `palette` maps symbols to blocks, and export `sprites` maps blocks to icons. Use [normalization profiles](https://tiltedlabs-ai.github.io/mcschemora/sdk/palettes/) to change the materials themselves. ## Coverage Textured outputs use a temporary conversion to the shared Java 1.21.6 visual bundle. They do not change stored block states. Biome tints and unsupported geometry may be approximated; diagnostics should accompany shared previews. Sprite/Wiki outputs can omit orientations, attached inventories, entities, and other schematic data. Keep the schematic file when sharing those details. Native Python/Rust provide PNG, GLB, and sprite rendering. Browser WASM exposes authoring and conversion but not these native render methods. Preparing visual assets is separate from preparing ordinary catalogs and recipe data; see [offline use](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/#offline-use). ## Run the example [Download render.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/render.py) and run it on the file from the quickstart: ```sh uv run --with mcschemora render.py output/workshop.schem ``` It writes a textured cutaway, a Y=1 sprite layer, a GLB model, and a wiki blueprint into `output/`. It prints diagnostics for details the outputs cannot represent, including the inventory omitted by sprite and blueprint exports. ```python import argparse from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser(description="Render the workshop and export a wiki blueprint.") parser.add_argument("source", type=Path, help="Workshop schematic created by build.py") parser.add_argument("--output", type=Path, default=Path("output")) args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=True) schematic = Schematic.load(args.source) outputs = ( ("workshop.png", schematic.export_png, {"size": (800, 600), "y": (0, 3)}), ("workshop-layer.png", schematic.export_sprites, {"y": 1, "grid": True}), ("workshop.glb", schematic.export_glb, {}), ("workshop.wiki", schematic.export_blueprint, {"name": "Workshop"}), ) for name, export, options in outputs: diagnostics = export(args.output / name, **options) print(f"Saved {name}") for diagnostic in diagnostics: print(f" {diagnostic}") if __name__ == "__main__": main() ``` ## Result ![Workshop cutaway with the roof hidden](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.png) ![Workshop layer at Y=1](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop-layer.png) [Download the workshop model](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.glb). --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/validation/ # Validation Validation checks supported Java game rules, including paired blocks and neighbor-dependent connections. After generating or editing a build, run it to find structural problems and checks that need more context: ```python from mcschemora import Schematic scene = Schematic.load("output/workshop.schem") report = scene.validate() print(report) ``` With the workshop from the [developer quickstart](https://tiltedlabs-ai.github.io/mcschemora/quickstart/developers/), this prints `No issues found.` ## Reports | Field | Meaning | What to do | | --- | --- | --- | | `errors` | A supported rule found a structural problem. | Fix the reported blocks, then validate again. | | `warnings` | A state may be unstable in the game. | Check whether the behavior is intended. | | `unknown` | A check needs surroundings or game data that are unavailable. | Inspect the missing context before relying on that check. | | `ok` | No errors, losses, or unknown results; warnings are allowed. | Read warnings even when this is true. | The same `Report` type also carries export `losses`; those come from `check_export`, not game-rule validation. Validation leaves the schematic unchanged. Test farms and redstone machines in-game; these checks do not simulate ticks. ## Coverage There is no tick simulation, farm-output estimate, exploit detection, or general mod mechanic validation. A supported vanilla rule may require neighbors outside the schematic, and newer content can have incomplete check coverage. Keep the Minecraft version, diagnostics, and unresolved context with a delivered build. For agents, this report is one input to the [generate-and-review workflow](https://tiltedlabs-ai.github.io/mcschemora/quickstart/agents/), alongside visual review and a final importer/game check. ## Repairs The supported repair rules are `redstone`, `stairs`, `fences`, `panes`, and `walls`. Pass `None` to run them all or an empty list to run none; unknown names fail. Repair iterates the connection and shape rules until they converge. Invalid bounds, overlapping regions, or a result that cannot converge can cause the call to fail, leaving the scene unchanged. Neighbor checks use global positions and can cross region boundaries. Missing surroundings remain unknown instead of being assumed to be air. Power, facing, waterlogging, free entities, and attached data are preserved by repair. An isolated redstone dot stays a dot. The [repair reference](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#schematicrepair) lists supported rules and failure conditions. Use [export checks](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/#export-reports) separately before changing file format or Minecraft version. Use repair to recalculate supported neighbor-dependent states: ```python repairs = scene.repair(rules=["stairs", "fences", "panes", "walls", "redstone"]) print(repairs.changed) for change in repairs.changes: print(change.region, change.position, change.before, change.after) print(repairs.skipped) print(scene.validate()) ``` Repair updates the schematic in place. The returned `skipped` field explains properties left unchanged because their surroundings are unknown. Loading a schematic does not run repair automatically. ## Before export After a material or geometry edit, read the edit report and validate the build. If it needs repairs, review the changed states and skipped reasons before validating again. Then check the destination format and version and save to a new path if you need the original for comparison. Check both validation and export reports: repairs can leave export losses, and lossless exports can contain unstable blocks. `ok=True` allows warnings; if your application requires none, check `warnings` too. ```python scene.save("output/repaired.schem") ``` --- Source: https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/ # Minecraft data MCSchemora checks block IDs and states against a versioned Minecraft catalog. Pin the version when creating a build; the matching catalog is loaded on demand and cached for later runs. ## Versions ```python from mcschemora import MinecraftData, Schematic data = MinecraftData() print(data.versions) scene = Schematic.create(version="1.21.1", data=data) ``` `latest` selects the newest version in the pinned metadata. It does not query Mojang for a live release. A catalog may include a block that a conversion or renderer does not support. See the [formats and support table](https://tiltedlabs-ai.github.io/mcschemora/reference/formats/). Downloads begin when an operation needs data: creating a schematic or loading a Java file can fetch catalogs, and rendering can fetch visual assets. Importing the Python package alone does not download anything. ## Cache location The native Python and Rust bindings use these defaults: | Platform | Cache directory | | --- | --- | | Linux | `$XDG_CACHE_HOME/mcschemora` when the variable is absolute; otherwise `~/.cache/mcschemora` | | macOS | `~/Library/Caches/mcschemora` | | Windows | `%LOCALAPPDATA%/mcschemora` | The directory must be writable. To choose one explicitly, pass `MinecraftData(cache_dir="./minecraft-cache")` and use that provider when creating or loading schematics. ## Offline use Run this while you have network access: ```python from mcschemora import MinecraftData, Schematic, block data = MinecraftData(cache_dir="./minecraft-cache") data.prepare("1.21.1", visuals=True) offline = MinecraftData(cache_dir=data.cache_dir, offline=True) scene = Schematic.create(version="1.21.1", data=offline) scene.region().set((0, 0, 0), block("stone")) scene.export_png("offline.png") ``` `prepare` loads the core catalog, biomes, and bundled recipes. `visuals=True` adds the rendering catalog and visual assets. Omit it when you only need building, inspection, conversion, or sprite diagrams. Offline mode blocks downloads and raises an error for missing or invalid cached files, without substituting another version. Copy the prepared directory with your script when moving it to an offline machine. ## Conversion routes ```python data.prepare("1.21.1", target="1.20.4") ``` Conversion can use intermediate catalogs. Preparing the route downloads the catalogs and biomes it needs. Loading only the source and destination catalogs can leave required data missing. ## Rendering coverage Native PNG and GLB rendering use a shared Java 1.21.6 bundle for all versions. MCSchemora converts a temporary palette for the render; stored blocks stay unchanged. Read the returned diagnostics for approximations. A render from another Minecraft version can also print a fallback notice. Grass and supported foliage use default colormap colors. Renders do not evaluate per-position biomes. Sprite diagrams use bundled wiki sheets and need no visual download. ## Datasets ```python blocks = data.dataset("1.21.1", "blocks") items = data.dataset("1.21.1", "items") recipes = data.dataset("1.21.1", "recipes") ``` Use the same version's `items` dataset to resolve numeric recipe item IDs. `recipeDefinitions` contains original recipe definitions; `itemTags` resolves item tags to numeric IDs. Recipes are bundled from official Java server JARs; runtime use does not download or execute those JARs. Browser WASM fetches catalogs through the browser and caches them in memory per `MinecraftData` instance. It has no native filesystem cache. See the [browser guide](https://tiltedlabs-ai.github.io/mcschemora/languages/wasm/) and [MinecraftData reference](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#minecraftdata). ## Block schemas ```python print(scene.registry.describe("oak_stairs")) ``` The registry belongs to the schematic's selected version. Query it before generating unfamiliar state combinations or choosing a replacement target. Check the operation's support for that version as well as the block's presence in the dataset. ## Shared providers Scenes can share a `MinecraftData` provider to use the same cache location and offline policy. A second provider without those settings can send operations back to the default cache or online path. When moving prepared work to an offline machine, include the cache directory with the scripts. For a reproducible job, pin the package and Minecraft version, list every input version and target route, and prepare visual assets separately if rendering is required. If offline data is missing, prepare it before retrying with the pinned version. The WASM binding caches catalogs in memory for each provider instance. It has no `cache_dir` or native offline provider. See [browser setup](https://tiltedlabs-ai.github.io/mcschemora/languages/wasm/) for loading data in a web application. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/ # Examples Each example includes a runnable Python script and resulting files. You can also [download all example scripts](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/examples.zip). ## Existing builds [Importing a farm](https://tiltedlabs-ai.github.io/mcschemora/examples/import-farm/) uses a downloaded Litematica moss farm by OpenBagTwo, based on a design by maidofmoss. It includes attribution and a report of the farm's blocks, inventories, and render diagnostics. The other workflows use a supplied workshop so you can compare your results with the downloads. | Example | Outcome | | --- | --- | | [Importing a farm](https://tiltedlabs-ai.github.io/mcschemora/examples/import-farm/) | Inspect a real farm and render a preview. | | [Litematica to WorldEdit](https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-schem/) | Flatten regions and review losses before saving a Sponge schematic. | | [Litematica to structure NBT](https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-nbt/) | Export a Java structure and inspect retained contents. | | [Batch conversion](https://tiltedlabs-ai.github.io/mcschemora/examples/batch-conversion/) | Convert a directory with a result recorded for each file. | | [Rotate a schematic](https://tiltedlabs-ai.github.io/mcschemora/examples/rotate-schematic/) | Save rotated positions and directional states. | | [Layer diagrams](https://tiltedlabs-ai.github.io/mcschemora/examples/layer-diagrams/) | Export numbered sprite images with global Y coordinates. | ## Materials | Example | Outcome | | --- | --- | | [Replace blocks](https://tiltedlabs-ai.github.io/mcschemora/examples/replace-blocks/) | Change one material throughout a build. | | [Restyle a workshop](https://tiltedlabs-ai.github.io/mcschemora/examples/restyle-workshop/) | Apply a reusable JSON palette profile. | | [Material lists](https://tiltedlabs-ai.github.io/mcschemora/examples/material-list/) | Export construction quantities as CSV and JSON. | | [Raw ingredients](https://tiltedlabs-ai.github.io/mcschemora/examples/raw-materials/) | Expand construction items into crafting ingredients. | | [Palette costs](https://tiltedlabs-ai.github.io/mcschemora/examples/compare-palettes/) | Compare ingredient requirements and priced totals before and after a restyle. | ## Generated builds The Eiffel Tower follows a building brief through an agent-written Python generator. Run it to reproduce the tower, read its validation report, or change the geometry and palette. The other generators build scenes from block placement and sampled terrain or geometry. | Example | Outcome | | --- | --- | | [Eiffel Tower](https://tiltedlabs-ai.github.io/mcschemora/examples/eiffel-tower/) | Reproduce an agent-created tower and inspect its validation report. | | [Island banner](https://tiltedlabs-ai.github.io/mcschemora/examples/banner/) | Build an island around block lettering with structures and animals. | | [Jade mountain scroll](https://tiltedlabs-ai.github.io/mcschemora/examples/jade-scroll/) | Generate seeded mountains with trees, waterfalls, and a pavilion. | | [Rainbow reef](https://tiltedlabs-ai.github.io/mcschemora/examples/reef/) | Sample a gyroid surface and color its outer shell. | --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/import-farm/ # Importing a farm You can inspect and preview a downloaded build in MCSchemora without running Minecraft. This example uses AChromoss v0.4, a `.litematic` moss-based bonemeal farm by [OpenBagTwo](https://github.com/OpenBagTwo/Schematics), based on [Chromoss by maidofmoss](https://www.youtube.com/watch?v=eNYZiuVNBe0). Download [the original schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/imported-farm/achromoss-v0.4.litematic) and [import_farm.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/import_farm.py) into the same directory, then run: ```sh uv run --with mcschemora import_farm.py achromoss-v0.4.litematic ``` ## Load the farm Load the file with an unpacked-size limit, then inspect its version and regions: ```python from mcschemora import Schematic scene = Schematic.load("achromoss-v0.4.litematic", max_unpacked_bytes=64 * 1024 * 1024) print(scene.version) print(scene.inspect()["regions"]) ``` The file identifies itself as Java 1.21.4. Its single region is 15 × 14 × 15 blocks and contains 1,487 non-air blocks. Loading preserves the region origin, block states, inventories, and entity data. Choose the decompression limit for the files your application accepts. `scene.inspect()` separates placed blocks from stored inventory items. This farm has 157 hoppers and 44 composters; its inventories hold 3,632 bone meal. The report records inspection completeness and diagnostics to help identify unsupported payloads. For this file, `scene.validate()` found no structural errors or warnings. One sign-support check remains unknown because it needs surrounding blocks. These checks do not simulate redstone or measure farm output, so they cannot establish whether the farm will operate correctly. ## Preview Render the loaded scene and inspect the returned diagnostics: ```python diagnostics = scene.export_png("farm.png", size=(1400, 1200)) for diagnostic in diagnostics: print(diagnostic) ``` Rendering leaves the schematic unchanged and uses the shared Java 1.21.6 visual assets. This preview has four diagnostics: three grass states lack evaluated tint colors, and the item-frame entity is outside the renderer's supported entity coverage. Check the [complete report](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/imported-farm/report.json) for those diagnostics alongside inspection and validation results. ```python title="import_farm.py" import argparse import json from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser(description="Inspect and render a downloaded Litematica farm.") parser.add_argument("source", type=Path) parser.add_argument("--output", type=Path, default=Path("output/imported-farm")) args = parser.parse_args() scene = Schematic.load(args.source, max_unpacked_bytes=64 * 1024 * 1024) inspection = scene.inspect() validation = scene.validate() args.output.mkdir(parents=True, exist_ok=True) diagnostics = scene.export_png(args.output / "preview.png", size=(1400, 1200)) report = { "inspection": inspection, "import_diagnostics": scene.import_diagnostics, "validation": { "errors": validation.errors, "warnings": validation.warnings, "unknown": validation.unknown, }, "render_diagnostics": diagnostics, } (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(f"Loaded Java {scene.version}: {inspection['regions']}") print(f"Validation: {validation}") print(f"Render diagnostics: {diagnostics}") print(f"Saved preview and report to {args.output}") if __name__ == "__main__": main() ``` ![MCSchemora render of the imported AChromoss moss farm](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/imported-farm/preview.png) [Download the schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/imported-farm/achromoss-v0.4.litematic) [Download the PNG](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/imported-farm/preview.png) --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-schem/ # Litematica to WorldEdit Convert two workshops in a Java 1.21.1 Litematica file to one WorldEdit `.schem`. The input has `main` at the origin and `annex` offset by ten blocks. Flattening keeps their relative placement while discarding the region boundaries; the script asks you to accept that loss before saving. ## Check the export Download [convert.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/convert.py) and [workshop-regions.litematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop-regions.litematic) into the same directory. With [uv installed](https://docs.astral.sh/uv/getting-started/installation/), run: ```sh uv run --with mcschemora convert.py workshop-regions.litematic output/workshops.schem --flatten ``` The check reports two losses and stops before writing: ```text Edition: java; version: 1.21.1 Regions: annex, main Loss: Destination stores one region; region names and boundaries will be lost Loss: main: omitted structure cells become explicit air in schem Export blocked; resolve errors or explicitly accept the reported losses. ``` To accept the loss of region boundaries and the conversion of omitted cells to explicit air, rerun with the loss flag: ```sh uv run --with mcschemora convert.py workshop-regions.litematic output/workshops.schem --flatten --allow-loss ``` The command saves `output/workshops.schem`; compare it with the [verified output](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/conversion/workshops.schem). If region bounds overlap, resolve that error first. `--allow-loss` only accepts losses. Put the result in WorldEdit's configured schematics directory, load it with `//schem load workshops`, and paste at the intended location. See [Minecraft import instructions](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/#minecraft-import) for paths and importer compatibility. ## Export checks The script calls `check_export(format="schem", flatten=True)` before saving. Errors block writing, and losses require explicit acceptance. The output extension selects Sponge v3; legacy MCEdit `.schematic` conversion is unsupported. ```python title="convert.py" import argparse from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser(description="Inspect and convert a schematic.") parser.add_argument("source", type=Path) parser.add_argument("destination", type=Path) parser.add_argument("--version", help="Target Minecraft Java version") parser.add_argument("--flatten", action="store_true") parser.add_argument("--allow-loss", action="store_true") args = parser.parse_args() schematic = Schematic.load(args.source) print(f"Edition: {schematic.edition}; version: {schematic.version}") print(f"Regions: {', '.join(schematic.regions)}") format_name = ( "blueprint" if args.destination.suffix == ".wiki" else args.destination.suffix.lstrip(".") ) report = schematic.check_export(format=format_name, version=args.version, flatten=args.flatten) print(report) if report.errors or (report.losses and not args.allow_loss): raise SystemExit("Export blocked; resolve errors or explicitly accept the reported losses.") args.destination.parent.mkdir(parents=True, exist_ok=True) schematic.save( args.destination, version=args.version, flatten=args.flatten, allow_loss=args.allow_loss ) print(f"Saved {args.destination.name}") if __name__ == "__main__": main() ``` Use [files and conversion](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/) for version changes, retained payloads, and codec choices. To convert a directory with a report for each input, continue with [batch conversion](https://tiltedlabs-ai.github.io/mcschemora/examples/batch-conversion/). --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-nbt/ # Litematica to structure NBT Convert the supplied workshop to a Java structure `.nbt` file without opening Minecraft. Its single region contains a bed and a chest holding 64 stone. Structure NBT drops the Litematica metadata, so first inspect the loss report, then decide whether to write the file. ## Check the export Download [convert.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/convert.py) and [workshop.litematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.litematic) together, then run: ```sh uv run --with mcschemora convert.py workshop.litematic output/workshop.nbt ``` The script checks the destination format and stops before writing: ```text Edition: java; version: 1.21.1 Regions: main Loss: Destination does not retain schematic metadata Export blocked; resolve errors or explicitly accept the reported losses. ``` If losing schematic metadata is acceptable, repeat the command with the flag that accepts the reported loss: ```sh uv run --with mcschemora convert.py workshop.litematic output/workshop.nbt --allow-loss ``` The exported structure retains the workshop's supported blocks and chest contents. Compare it with [workshop.nbt](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/conversion/workshop.nbt), then reload and inspect your file before using it in a game or importer: ```python from mcschemora import Schematic scene = Schematic.load("output/workshop.nbt") print(scene.version, scene.inspect()["inventories"]) ``` This verifies vanilla Java structure NBT. Compatibility with Create's schematicannon, modded blocks, or MineColonies formats needs a separate test. The complete [conversion script](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/convert.py) is explained in [the WorldEdit example](https://tiltedlabs-ai.github.io/mcschemora/examples/litematic-to-schem/). See [files and conversion](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/) for supported formats and export behavior. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/material-list/ # Export a material list Export the workshop's construction items as CSV for a spreadsheet or JSON for another script. The bill includes 49 stone bricks, 49 oak slabs, 12 oak logs, one red bed, one chest, one furnace, and one crafting table. Placement quantities count the two-block bed as a single item and exclude the chest's stored 64 stone. Download [materials.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/materials.py) and [workshop.schem](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.schem) into one directory, then run: ```sh uv run --with mcschemora materials.py workshop.schem --output output/materials ``` Choose a separate output directory for another build, since rerunning replaces the reports. The four files provide construction counts, expanded ingredients, and value estimates: | File | Contents | | --- | --- | | [materials.csv](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/materials/materials.csv) | Seven construction item types and their quantities. | | [raw-materials.csv](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/materials/raw-materials.csv) | Fractional ingredients after recipe expansion. | | [materials.json](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/materials/materials.json) | Both views, keyed by canonical item ID. | | [values.json](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/materials/values.json) | EMC and EssentialsX totals, including unpriced materials. | ## Report files `material_cost()` returns `items` and `raw_materials` dictionaries, which the script writes with Python's standard `json` and `csv` modules. The example caps binary NBT decompression at 64 MiB and raises an error if catalogs or recipes are missing: ```python title="materials.py" import argparse import csv import json from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser(description="Export construction materials and values.") parser.add_argument("source", type=Path) parser.add_argument("--output", type=Path, default=Path("output/materials")) args = parser.parse_args() scene = Schematic.load(args.source, max_unpacked_bytes=64 * 1024 * 1024) materials = scene.material_cost() values = {profile: scene.value_cost(profile) for profile in ("emc", "essentialsx")} args.output.mkdir(parents=True, exist_ok=True) (args.output / "materials.json").write_text(json.dumps(materials, indent=2) + "\n") (args.output / "values.json").write_text(json.dumps(values, indent=2) + "\n") for field, filename in (("items", "materials.csv"), ("raw_materials", "raw-materials.csv")): with (args.output / filename).open("w", newline="") as output: writer = csv.writer(output) writer.writerow(("item", "quantity")) writer.writerows(sorted(materials[field].items())) for diagnostic in scene.import_diagnostics: print(diagnostic) print(f"Construction item types: {len(materials['items'])}") for profile, report in values.items(): print(f"{profile}: {report['total']}; unpriced: {report['unpriced']}") print(f"Saved material reports to {args.output}") if __name__ == "__main__": main() ``` Before using the expanded quantities for a gathering plan, [interpret the raw ingredients](https://tiltedlabs-ai.github.io/mcschemora/examples/raw-materials/). The [materials and costs chapter](https://tiltedlabs-ai.github.io/mcschemora/sdk/materials-and-costs/) explains construction counts, recipe expansion, and valuation. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/raw-materials/ # Raw ingredients Calculate the logs, stone, and other ingredients needed to craft the workshop's construction items. The report excludes its chest's stored 64 stone, so it gives crafting requirements without subtracting stock you already have. Download [materials.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/materials.py) and [workshop.schem](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.schem), then run: ```sh uv run --with mcschemora materials.py workshop.schem --output output/materials ``` For the supplied Java 1.21.1 workshop, `raw-materials.csv` contains: | Ingredient | Quantity | | --- | ---: | | Beetroot | 3 | | Cobbled deepslate | 8 | | Oak logs | 21.875 | | Stone | 49 | | White wool | 3 | Oak logs cover both the placed pillars and crafted wooden items. The fractional quantity comes from expanding recipes without rounding intermediate crafting batches. [Download the ingredient CSV](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/materials/raw-materials.csv) or [the JSON report](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/materials/materials.json) to inspect the full result. ## Recipe choices The selected recipes use beetroot for red dye and cobbled deepslate for the furnace. Selection prefers shaped recipes, then takes the first supported acyclic expansion; it does not account for your preferred recipes or the resources available in your world. Inventories, entities, fuel, tool wear, and fluid acquisition are excluded. The 64 stone in the chest therefore do not reduce the requirements. Calculating remaining stock needs an explicit inventory and crafting policy in your application. The [complete exporter](https://tiltedlabs-ai.github.io/mcschemora/examples/material-list/#report-files) writes both item and ingredient views. See [recipe expansion](https://tiltedlabs-ai.github.io/mcschemora/sdk/materials-and-costs/#recipe-expansion) for fractional quantities and how ingredients with no available recipe are counted. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/compare-palettes/ # Compare palette costs Compare the ingredient requirements and estimated value of the same workshop before and after changing oak and stone to birch and deepslate. Both reports use Java 1.21.1 with the same bundled recipes and valuation profiles, so you can trace a cost change back to the materials being replaced. Download [restyle.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/restyle.py), [workshop_palette.json](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/workshop_palette.json), and [workshop.schem](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.schem), then run: ```sh uv run --with mcschemora restyle.py workshop.schem workshop_palette.json --output output/comparison ``` ## Missing prices Read each priced total together with its unpriced ingredients. The EMC profile prices both raw-ingredient sets completely; EssentialsX leaves gaps in both: | Profile | Original priced total | Restyled priced total | Interpretation | | --- | ---: | ---: | --- | | EMC | 1101 | 1150 | Both raw-ingredient sets are fully priced by this profile. | | EssentialsX | 147 | 0 | Both have missing prices; the restyled total is not its full value. | The original EssentialsX report leaves beetroot, cobbled deepslate, oak logs, and white wool unpriced. The restyled report also contains unpriced birch logs and more cobbled deepslate. Check the `unpriced` dictionaries alongside the totals before using them to choose materials. The JSON keeps complete construction and raw-material reports under `before` and `after`, along with normalization and import/render diagnostics. It compares the supplied palettes without estimating gathering time or automatically optimizing materials. [Download comparison.json](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/restyled/comparison.json) to inspect those fields. See [restyle a workshop](https://tiltedlabs-ai.github.io/mcschemora/examples/restyle-workshop/#script) for the shared script. The [valuation documentation](https://tiltedlabs-ai.github.io/mcschemora/sdk/materials-and-costs/#valuation) explains the profiles used in these reports. Open `comparison.json` and compare the previews to confirm the palette change: | Original | Restyled | | --- | --- | | ![Original oak workshop](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/restyled/before.png) | ![Birch and deepslate workshop](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/restyled/after.png) | --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/restyle-workshop/ # Restyle a workshop Change the workshop's oak pillars and slabs to birch and its stone-brick floor to deepslate bricks with a reusable JSON profile. The supplied profile changes 110 blocks while keeping the bed, furnace, and inventory chest. Compatible states, including vertical log axes and bottom-slab placement, survive the restyle. ## Profile Save [restyle.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/restyle.py), [workshop_palette.json](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/workshop_palette.json), and [workshop.schem](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.schem) together. Review the profile before running it: ```json title="workshop_palette.json" { "edition": "java", "keep": ["minecraft:chest", "minecraft:furnace", "minecraft:red_bed"], "replacements": [ {"from": ["minecraft:oak_log"], "to": "minecraft:birch_log"}, {"from": ["minecraft:oak_slab"], "to": "minecraft:birch_slab"}, {"from": ["minecraft:stone_bricks"], "to": "minecraft:deepslate_bricks"} ] } ``` IDs listed in `keep` are protected. Each replacement group changes its source IDs to the target; with `fallback` omitted, every other material stays unchanged. Normalization retains compatible properties across orientations. Run the profile against the supplied workshop: ```sh uv run --with mcschemora restyle.py workshop.schem workshop_palette.json --output output/restyled ``` Validation prints `No issues found.` and the changed count is 110. The script leaves the source unchanged and writes `before.png`, `after.png`, `restyled.litematic`, and `comparison.json`. Compare the changed count and the before/after palette counts to find any skipped replacements. Rendering downloads visual assets on first use and uses the shared Java 1.21.6 visual bundle; check its diagnostics when trying other inputs. ## Script The script calculates the original costs and renders a cutaway before applying the profile. It then validates, calculates the new costs, and exports the separate build and preview. Adjust the Y=0..3 crop when using a build with a different roof height: ```python title="restyle.py" import argparse import json from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser( description="Apply a material profile and compare build costs." ) parser.add_argument("source", type=Path) parser.add_argument("profile", type=Path) parser.add_argument("--output", type=Path, default=Path("output/restyled")) args = parser.parse_args() if args.source.resolve().parent == args.output.resolve(): parser.error("Choose an output directory separate from the input file.") scene = Schematic.load(args.source, max_unpacked_bytes=64 * 1024 * 1024) before = { "materials": scene.material_cost(), "values": {profile: scene.value_cost(profile) for profile in ("emc", "essentialsx")}, } args.output.mkdir(parents=True, exist_ok=True) before_diagnostics = scene.export_png(args.output / "before.png", size=(800, 600), y=(0, 3)) changes = scene.normalize(args.profile) validation = scene.validate() print(validation) if validation.errors: raise SystemExit("Resolve validation errors before saving the restyled build.") after = { "materials": scene.material_cost(), "values": {profile: scene.value_cost(profile) for profile in ("emc", "essentialsx")}, } scene.save(args.output / "restyled.litematic") after_diagnostics = scene.export_png(args.output / "after.png", size=(800, 600), y=(0, 3)) report = { "before": before, "after": after, "changes": changes, "import_diagnostics": scene.import_diagnostics, "render_diagnostics": {"before": before_diagnostics, "after": after_diagnostics}, } (args.output / "comparison.json").write_text(json.dumps(report, indent=2) + "\n") print(f"Replaced {changes['changed']} blocks") for profile in ("emc", "essentialsx"): previous = before["values"][profile] current = after["values"][profile] print(f"{profile}: {previous['total']} -> {current['total']}") print(f"Unpriced before: {previous['unpriced']}; after: {current['unpriced']}") print(f"Render diagnostics: {report['render_diagnostics']}") print(f"Saved build, previews, and comparison to {args.output}") if __name__ == "__main__": main() ``` Continue with [compare palette costs](https://tiltedlabs-ai.github.io/mcschemora/examples/compare-palettes/) to interpret the report, or read about [custom profiles and rule precedence](https://tiltedlabs-ai.github.io/mcschemora/sdk/palettes/#profiles) to change how materials are selected. ![Restyled workshop with birch pillars and a deepslate floor](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/restyled/after.png) [Download the restyled schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/restyled/restyled.litematic) and [comparison report](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/restyled/comparison.json) to inspect the result. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/replace-blocks/ # Replace blocks Replace the workshop's 49 stone-brick floor cells with ordinary stone. A normalization profile matches block IDs throughout the build, so you can use it for unwanted blocks you cannot find in an in-game overlay. Download [restyle.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/restyle.py), [stone_palette.json](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/stone_palette.json), and [workshop.schem](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.schem). The profile changes only stone bricks; it has no fallback, so unlisted materials stay unchanged: ```json title="stone_palette.json" { "edition": "java", "replacements": [ {"from": ["minecraft:stone_bricks"], "to": "minecraft:stone"} ] } ``` Apply it to the workshop: ```sh uv run --with mcschemora restyle.py workshop.schem stone_palette.json --output output/replaced ``` The script reports 49 replacements, validates the result, and writes a separate Litematica file, before/after PNGs, and a cost comparison. Before adapting the shared [script](https://tiltedlabs-ai.github.io/mcschemora/examples/restyle-workshop/#script), adjust its cutaway crop for your build; the supplied crop fits this workshop. ## States and removal For another input, inspect [palette counts](https://tiltedlabs-ai.github.io/mcschemora/sdk/palettes/#count-block-states) to find the IDs and orientation variants. Normalization preserves compatible target properties, but an incompatible change such as chest to stone can be skipped. The report does not explain every skipped cell, so compare the counts and inspect the result. To clear ordinary blocks, select them and fill with air: ```python from mcschemora import Schematic, block scene = Schematic.load("workshop.schem") region = scene.region() region.select(start=(0, 0, 0), size=(7, 5, 7)).select(block="stone_bricks").fill(block("air")) ``` The snippet edits only the in-memory scene. Review it before saving; `delete()` additionally removes selected entities. See [selection semantics](https://tiltedlabs-ai.github.io/mcschemora/sdk/editing/#entities-and-deletion) when choosing between those operations. ![Workshop floor changed to stone](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/replaced/after.png) [Download the result](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/replaced/restyled.litematic) to inspect the floor. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/rotate-schematic/ # Rotate a schematic Rotate the supplied workshop by one quarter turn around Y and save its new block positions and states. The rotation remains when you load the file in another importer, and inventory data moves with its chest. Download [rotate.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/rotate.py) and [workshop.schem](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.schem), then run: ```sh uv run --with mcschemora rotate.py workshop.schem --output output/rotated ``` Validation prints `No issues found.` and the script writes `rotated.litematic` and `rotated.png`. Positive steps turn north toward west, so check that the workshop's west-facing furnace now faces south. The preview crops the workshop at global Y=0..3. ## Script The script selects the region's complete bounds and rotates about their geometric center. It accepts one region; an assembled multi-region build would need a shared pivot: ```python title="rotate.py" import argparse from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser( description="Rotate a single-region build and save its blocks." ) parser.add_argument("source", type=Path) parser.add_argument("--output", type=Path, default=Path("output/rotated")) args = parser.parse_args() scene = Schematic.load(args.source, max_unpacked_bytes=64 * 1024 * 1024) if len(scene.regions) != 1: parser.error("This example rotates one region; select a single-region input.") if args.source.resolve() == (args.output / "rotated.litematic").resolve(): parser.error("The output must differ from the input.") region = scene.region(scene.regions[0]) bounds = region.bounds if bounds is None: parser.error("The input region is empty.") area = region.select(start=bounds.start, size=bounds.size) area.rotate(steps=1) report = scene.validate() print(report) if report.errors: raise SystemExit("Resolve validation errors before saving the rotated build.") args.output.mkdir(parents=True, exist_ok=True) scene.save(args.output / "rotated.litematic") diagnostics = scene.export_png(args.output / "rotated.png", size=(800, 600), y=(0, 3)) print(f"Saved rotated blocks to {args.output}") for diagnostic in diagnostics: print(diagnostic) if __name__ == "__main__": main() ``` To mirror instead, use `area.flip(axis="x")` or `area.flip(axis="z")`, then inspect directional states and any diagnostics. See [transformation behavior](https://tiltedlabs-ai.github.io/mcschemora/sdk/editing/#collisions) for pivots, collision checks, selected air, and unsupported transforms. ![Workshop after a quarter turn](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/rotated/rotated.png) [Download rotated.litematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/rotated/rotated.litematic) to inspect the saved transformation. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/layer-diagrams/ # Layer diagrams Export the workshop as five numbered grids of block sprites, covering Y=0 through Y=4. A JSON manifest ties each image to its global Y coordinate and records its diagnostics, so you can follow the layers even when a build sits above or below zero. Download [layers.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/layers.py) and [workshop.schem](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/workshop.schem), then run: ```sh uv run --with mcschemora layers.py workshop.schem --output output/layers ``` The command confirms the number of layers and the manifest location: ```text Saved 5 layer diagrams and layers.json to output/layers ``` Sprite diagrams use bundled Wiki icons, so they do not download the native texture/model bundle. Imported Java blocks still need their catalogs. ## Layer coordinates Each region has local bounds. The script uses `to_global(bounds.start)` to find its bottom layer in the schematic, then walks from the lowest to the highest global Y coordinate. That includes empty gaps between regions, so check the vertical range before running it on a large build. Resolve conflicting region overlaps before rendering as well. ```python title="layers.py" import argparse import json from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser(description="Export every global Y layer as a sprite diagram.") parser.add_argument("source", type=Path) parser.add_argument("--output", type=Path, default=Path("output/layers")) args = parser.parse_args() scene = Schematic.load(args.source, max_unpacked_bytes=64 * 1024 * 1024) ranges = [] for name in scene.regions: region = scene.region(name) bounds = region.bounds if bounds is not None: start = region.to_global(bounds.start)[1] ranges.append((start, start + bounds.size[1])) if not ranges: parser.error("The schematic has no bounded regions.") args.output.mkdir(parents=True, exist_ok=True) layers = [] for index, y in enumerate( range(min(start for start, _ in ranges), max(end for _, end in ranges)) ): filename = f"layer-{index:03d}-y{y}.png" diagnostics = scene.export_sprites(args.output / filename, y=y, grid=True) layers.append({"y": y, "file": filename, "diagnostics": diagnostics}) (args.output / "layers.json").write_text(json.dumps(layers, indent=2) + "\n") print(f"Saved {len(layers)} layer diagrams and layers.json to {args.output}") if __name__ == "__main__": main() ``` Layer diagnostics describe omitted states and inventory details; retain the source schematic to preserve those fields. See [rendering and blueprints](https://tiltedlabs-ai.github.io/mcschemora/sdk/rendering/#layer-guides) for custom icons, cardinal views, and textured layer alternatives. ![Workshop floor diagram at Y=0](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/layers/layer-000-y0.png) [Download all five layers and the manifest](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/layers.zip) to inspect the guide. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/batch-conversion/ # Batch conversion Convert a folder of schematics into Litematica files, keeping a JSON result for each input. The script continues after a failed or blocked conversion, but exits with a failure status if any input could not be saved. Inspect the report even when some outputs were saved. Download [batch_convert.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/batch_convert.py) and [conversion-inputs.zip](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/conversion-inputs.zip). Extract the archive into an `incoming` directory; it contains `workshop.schem` and the two-region `workshop-regions.litematic`. Choose a separate output directory: ```sh uv run --with mcschemora batch_convert.py incoming output/converted ``` Both supplied inputs convert successfully: ```text workshop-regions.litematic: saved workshop.schem: saved ``` The output contains `workshop-regions.litematic.litematic`, `workshop.schem.litematic`, and `report.json`. Appending the new suffix to each full filename keeps outputs separate when input stems match across formats. [Download the successful sample report](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/conversion/batch-report.json) to compare the results. ## Blocked exports Converting the same inputs to WorldEdit requires flattening: ```sh uv run --with mcschemora batch_convert.py incoming output/worldedit --format schem --flatten ``` The multi-region input has flattening losses, so its result is `blocked`. Review `report.json` before rerunning with `--allow-loss`; that flag never permits an export error. Use `--version` to choose a supported target Java version, allowing for any intermediate catalogs that preparation needs. ## Error handling The script reads immediate directory children ending in `.schem`, `.litematic`, `.nbt`, or `.snbt`. It caps binary NBT decompression at 64 MiB per input and records failures in the report. Legacy `.schematic` and MineColonies `.blueprint` files are unsupported inputs. Rerunning replaces existing outputs. Each schematic save is atomic, but an interrupted batch can leave some converted files without a final report. Keep that possibility in mind when using the script in an automated pipeline: ```python title="batch_convert.py" import argparse import json from pathlib import Path from mcschemora import Schematic def main(): parser = argparse.ArgumentParser(description="Convert a directory and report every outcome.") parser.add_argument("source", type=Path) parser.add_argument("destination", type=Path) parser.add_argument("--format", choices=("schem", "litematic", "nbt"), default="litematic") parser.add_argument("--version") parser.add_argument("--flatten", action="store_true") parser.add_argument("--allow-loss", action="store_true") args = parser.parse_args() if not args.source.is_dir() or args.source.resolve() == args.destination.resolve(): parser.error("Use an input directory and a separate output directory.") sources = sorted( path for path in args.source.iterdir() if path.is_file() and path.suffix in {".schem", ".litematic", ".nbt", ".snbt"} ) if not sources: parser.error("No supported input files found.") args.destination.mkdir(parents=True, exist_ok=True) results = [] for source in sources: result = {"source": source.name} try: scene = Schematic.load(source, max_unpacked_bytes=64 * 1024 * 1024) report = scene.check_export( format=args.format, version=args.version, flatten=args.flatten ) result.update( import_diagnostics=scene.import_diagnostics, errors=report.errors, losses=report.losses, ) if report.errors or (report.losses and not args.allow_loss): result["status"] = "blocked" else: destination = args.destination / f"{source.name}.{args.format}" scene.save( destination, format=args.format, version=args.version, flatten=args.flatten, allow_loss=args.allow_loss, ) result.update(status="saved", output=destination.name) except (OSError, ValueError) as error: result.update(status="error", message=str(error)) results.append(result) print(f"{source.name}: {result['status']}") (args.destination / "report.json").write_text(json.dumps(results, indent=2) + "\n") if any(result["status"] != "saved" for result in results): raise SystemExit("Some files were not converted; read report.json.") if __name__ == "__main__": main() ``` See [files and conversion](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/#conversion-pipelines) for supported formats and handling retained imported data. --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/banner/ # Island banner Build the scene at the top of the documentation homepage: an island sized around a row of block letters, with paths, trees, a tower, and animals. The generator builds the terrain first, then places the lettering and details on top. With [uv](https://docs.astral.sh/uv/getting-started/installation/) installed, [download banner.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/banner.py) and run: ```sh uv run --with mcschemora banner.py ``` The script writes `output/banner.schem` and a 3840 × 960 `output/banner.png` for Java 1.21.1. Pass `--output another-folder` to keep a variant separately. ## Lettered island The generator stores placements in a `cells` dictionary, allowing later details to replace earlier blocks at the same position. The `put` helper converts layout depth into Z: ```python def put(x, y, depth, material, **states): cells[(x, y, depth - x)] = block(material, **states) ``` Grass over dirt forms the top of the island. Narrower stone and deepslate layers taper its underside, while a fixed random seed roughens the outline. A strip of clay and source water makes a channel through the top. ![Layered island before the letters and structures](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/stages/banner-terrain.png) The lettering determines the island's width. Each character in `GLYPHS` has seven rows of zeroes and ones, with a `1` marking a block; the generator measures the text, then advances a cursor as it places each glyph: ```python for row, pixels in enumerate(GLYPHS[character]): for column, pixel in enumerate(pixels): if pixel == "1": x, y = cursor + column, 9 - row face = ( "gold_block" if index < 2 else ("diamond_block" if row < 4 else "light_blue_concrete") ) put(x, y, 2, face) for depth in (0, 1): put(x, y, depth, "orange_concrete" if index < 2 else "dark_prismarine") ``` Gold faces with orange-concrete backs form the first two letters. The remaining letters have diamond or light-blue concrete faces and dark-prismarine backs. Two extra depth layers give them thickness, and a raised stone and deepslate platform supports them. ![Block letters placed on the island](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/stages/banner-letters.png) To change the text, choose characters already in `GLYPHS` or add a seven-row bitmap for each new character. The island width follows the new text width. ## Structures A path runs along one depth coordinate, with lanterns twelve blocks apart and small slab bridges over the water channel. Trees have log columns and several leaf layers; skipped corner blocks soften their outlines. The tower uses a local placement helper to build near the end of the lettering: ```python tower_x = width + 6 def tower_put(x, y, z, material, **states): put(tower_x + x, y, -1 + x + z, material, **states) ``` Its 5 × 5 footprint has cobblestone lower walls and logs at the upper corners. Stairs face inward from either side to form a pitched roof. A paired door, windows, a lantern, and a flag finish the building. When changing those materials, inspect their [block states](https://tiltedlabs-ai.github.io/mcschemora/sdk/schematics/#block-states) to keep directional pieces facing correctly. ## Rendering The script adds mobs through `region.entities.add(mob(...), at=...)`. Fractional entity positions let it center animals on blocks. Some perch on the letters, while a sheep and pig stand on the island. After writing the final block batch, the entry point saves the schematic and calls `export_png`. Check the render diagnostics when comparing the image with the build: the current visual bundle can report missing chicken and pig textures and sheep fur geometry. Those entities remain in the schematic. For a variant, replace the tower with your own building or change the lettering materials while keeping the layout fixed. ```python title="banner.py" import argparse import random from pathlib import Path from mcschemora import Schematic, block, mob GLYPHS = { "M": ("10001", "11011", "10101", "10101", "10001", "10001", "10001"), "C": ("0111", "1000", "1000", "1000", "1000", "1000", "0111"), "S": ("0111", "1000", "1000", "0110", "0001", "0001", "1110"), "c": ("0000", "0000", "0111", "1000", "1000", "1000", "0111"), "h": ("1000", "1000", "1010", "1101", "1001", "1001", "1001"), "e": ("0000", "0000", "0110", "1001", "1111", "1000", "0111"), "m": ("00000", "00000", "11010", "10101", "10101", "10101", "10101"), "o": ("0000", "0000", "0110", "1001", "1001", "1001", "0110"), "r": ("000", "000", "101", "110", "100", "100", "100"), "a": ("0000", "0000", "0110", "0001", "0111", "1001", "0111"), } def create_banner(): schematic = Schematic.create(version="1.21.1") region = schematic.region() rng = random.Random(42) cells = {} text = "MCSchemora" width = sum(len(GLYPHS[character][0]) + 1 for character in text) - 1 def put(x, y, depth, material, **states): cells[(x, y, depth - x)] = block(material, **states) for x in range(-11, width + 13): inset = max(0, 5 - min(x + 11, width + 12 - x)) edge = rng.randrange(3) for depth in range(-7 + inset + edge, 16 - inset - edge): put(x, 0, depth, "grass_block") put(x, -1, depth, "dirt") if -4 + inset < depth < 12 - inset: put(x, -2, depth, rng.choice(("stone", "andesite", "mossy_cobblestone"))) if -1 + inset < depth < 9 - inset and -8 < x < width + 10: put(x, -3, depth, "stone") if 2 < depth < 6 and x % 5 != 0 and -4 < x < width + 7: put(x, -4, depth, "deepslate") if 9 <= depth <= 10: put(x, -1, depth, "clay") put(x, 0, depth, "water", level=0) if depth == 6: put(x, 0, depth, rng.choice(("cobblestone", "stone_bricks"))) for x in range(-2, width + 3): for depth in range(-1, 4): put(x, 0, depth, "polished_deepslate") put(x, 1, depth, "stone_bricks") if depth in (0, 1, 2): put(x, 2, depth, "polished_deepslate") put(x, 1, 4, "waxed_oxidized_cut_copper") cursor = 0 perched_mobs = { "M": (0, "fox", 45), "C": (2, "chicken", 225), "S": (2, "creeper", 45), "m": (1, "wolf", 45), "a": (2, "bee", 225), } for index, character in enumerate(text): for row, pixels in enumerate(GLYPHS[character]): for column, pixel in enumerate(pixels): if pixel == "1": x, y = cursor + column, 9 - row face = ( "gold_block" if index < 2 else ("diamond_block" if row < 4 else "light_blue_concrete") ) put(x, y, 2, face) for depth in (0, 1): put(x, y, depth, "orange_concrete" if index < 2 else "dark_prismarine") if character in perched_mobs: column, identifier, yaw = perched_mobs[character] top_row = next( row for row, pixels in enumerate(GLYPHS[character]) if pixels[column] == "1" ) x = cursor + column region.entities.add( mob(identifier, nbt=f"{{Rotation:[{yaw}.0f,0.0f]}}"), at=(x + 0.5, 10.0 - top_row, 1.5 - x), ) if character == "o": region.entities.add( mob("cat", nbt="{Rotation:[225.0f,0.0f]}"), at=(cursor + 2.0, 4.0, -float(cursor)), ) cursor += len(GLYPHS[character][0]) + 1 for x in range(5, width, 12): put(x, 1, 6, "stone_brick_wall") put(x, 2, 6, "lantern") for x in (8, width // 2, width - 7): for bridge_x in (x, x + 1): for depth in range(8, 13): put(bridge_x, 1, depth, "oak_slab", type="bottom") for depth in (8, 12): put(x - 1, 1, depth, "oak_fence") put(x + 2, 1, depth, "oak_fence") for tree_x, tree_depth in ((-7, 1), (-5, -4), (width + 10, 7)): for y in range(1, 6): put(tree_x, y, tree_depth, "oak_log", axis="y") for y, radius in ((3, 2), (4, 2), (5, 1), (6, 1)): for x in range(tree_x - radius, tree_x + radius + 1): for z_offset in range(-radius, radius + 1): corner = abs(x - tree_x) == radius and abs(z_offset) == radius if corner and (y == 6 or rng.randrange(2) == 0): continue if x == tree_x and z_offset == 0 and y <= 5: continue depth = tree_depth + x - tree_x + z_offset put(x, y, depth, "oak_leaves", persistent=True) tower_x = width + 6 def tower_put(x, y, z, material, **states): put(tower_x + x, y, -1 + x + z, material, **states) for x in range(-2, 3): for z in range(-2, 3): tower_put(x, 1, z, "cobblestone") tower_put(x, 5, z, "spruce_planks") tower_put(x, 8, z, "spruce_planks") if abs(x) == 2 or abs(z) == 2: for y in range(1, 8): if abs(x) == 2 and abs(z) == 2 and y >= 3: tower_put(x, y, z, "stripped_spruce_log", axis="y") elif y <= 2: material = "mossy_cobblestone" if (x + z + y) % 3 == 0 else "cobblestone" tower_put(x, y, z, material) else: tower_put(x, y, z, "stone_bricks") for y in (4, 5): for side in (-2, 2): tower_put(side, y, 0, "light_blue_stained_glass") for x in (-1, 1): tower_put(x, y, 2, "light_blue_stained_glass") for y, half in ((1, "lower"), (2, "upper")): tower_put(0, y, 2, "spruce_door", facing="south", half=half, hinge="left") tower_put(0, 1, 3, "stone_brick_slab", type="bottom") tower_put(0, 6, 3, "spruce_planks") tower_put(0, 5, 3, "lantern", hanging=True) for z in range(-2, 3): for x in (-2, -1, 1, 2): tower_put( x, 11 - abs(x), z, "spruce_stairs", facing="east" if x < 0 else "west", half="bottom", shape="straight", ) tower_put(0, 11, z, "spruce_slab", type="bottom") for z in (-2, 2): tower_put(0, 9, z, "spruce_planks") tower_put(0, 10, z, "spruce_planks") tower_put(0, 12, 0, "spruce_fence", east=True) tower_put(1, 12, 0, "red_wool") for x in range(-8, width + 11, 4): for depth in (-5, 13): if cells.get((x, 0, depth - x)) == block("grass_block"): put(x, 1, depth, rng.choice(("poppy", "dandelion", "flowering_azalea"))) region.set_many(cells.items()) region.entities.add(mob("sheep"), at=(-2.5, 1.0, 15.5)) region.entities.add(mob("pig"), at=(width + 1.5, 1.0, 11.5 - width)) return schematic def main(): parser = argparse.ArgumentParser(description="Build and render the MCSchemora block banner.") parser.add_argument("--output", type=Path, default=Path("output")) args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=True) schematic = create_banner() schematic.save(args.output / "banner.schem") image_path = args.output / "banner.png" diagnostics = schematic.export_png(image_path, size=(3840, 960)) print(f"Saved banner.schem and banner.png ({image_path.stat().st_size / 1024:.0f} KiB)") for diagnostic in diagnostics: print(diagnostic) if __name__ == "__main__": main() ``` ![Finished island banner](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/banner.png) [Download the schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/banner.schem) [Download the PNG](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/banner.png) --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/reef/ # Rainbow reef Sample a gyroid surface inside a sphere, give it a dark core, and color its outer shell with a rainbow. The open channels expose the core behind the colors; a blackstone plinth supports the clipped lower edge. With [uv](https://docs.astral.sh/uv/getting-started/installation/) installed, [download reef.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/reef.py) and run: ```sh uv run --with mcschemora reef.py ``` The script writes `output/reef.schem` and a 1600 × 1600 `output/reef.png`. The default sphere is 64 blocks across with 2.5 surface repetitions and thickness 0.35. Edit the downloaded file to change its geometry or colors. ## Geometry `placements()` yields `(position, block)` pairs, starting with two layers of polished blackstone and a narrower black-concrete deck: ```python def placements(): for y, margin, material in ((0, 3, foundation), (1, 3, foundation), (2, 2, dark)): for x in range(-margin, diameter + margin): for z in range(-margin, diameter + margin): yield (x, y, z), material ``` At diameter 64, the blackstone extends from -3 through 66 on X and Z. The `margin` shrinks the top layer by one block on each side. ![Blackstone plinth before the reef is added](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/stages/reef-base.png) Above the plinth, a gyroid forms a repeating surface with channels passing through it. The script evaluates this field using scaled coordinates `u`, `v`, and `w`: ```text sin(u) × cos(w) + sin(v) × cos(u) + sin(w) × cos(v) ``` Positions close enough to zero belong to the surface. The `thickness` threshold controls that band: lower values leave thinner walls and wider channels. To fit `periods` repetitions across the diameter, the generator centers and scales the sampling grid. Each coordinate's square, sine, and cosine are calculated once for reuse in the inner loops: ```python center = (diameter - 1) / 2 radius = diameter / 2 radius_squared = radius * radius interior_radius_squared = (radius * 0.8) ** 2 scale = tau * periods / diameter samples = tuple( ( (coordinate - center) ** 2, sin((coordinate - center) * scale), cos((coordinate - center) * scale), ) for coordinate in range(diameter) ) ``` The loops clip the field to a sphere by comparing squared distance from the center with `radius_squared`, skipping positions outside it. Cutting off the lower part lets the reef sit on its plinth. ![Gyroid geometry with its colored exterior replaced by white concrete](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/stages/reef-surface.png) White concrete in place of the exterior colors makes the channels easier to inspect before choosing a palette. ## Color `atan2` gives the angle around the vertical axis. A height-dependent twist shifts the palette as the surface rises, and modulo wraps the result into a single cycle before conversion to a palette index: ```python interior_remaining = interior_radius_squared - x_squared - z_squared angle = atan2(z - center, x - center) / tau term = sx * cz for y in range(bottom, diameter): y_squared, sy, cy = samples[y] if y_squared <= remaining and abs(term + sy * cx + sz * cy) < thickness: index = int(((angle + twists[y]) % 1) * len(palette)) material = dark if y_squared <= interior_remaining else palette[index] yield (x, y - bottom + 3, z), material ``` Cells within 80% of the sphere's radius use black concrete. The palette colors the remaining shell, leaving dark channels behind it. Edit `COLORS` at the top of the downloaded file to use another set of concrete colors. After yielding the base and surface, the generator writes all placements in one batch: ```python schematic.region().set_many(placements()) return schematic ``` The entry point saves the schematic and calls `export_png`. See [building](https://tiltedlabs-ai.github.io/mcschemora/sdk/schematics/#batch-writes) for more on batches and palettes. ## Change the shape Try a smaller reef with thinner walls, saving it separately: ```sh uv run --with mcschemora reef.py --diameter 48 --periods 2 --thickness 0.25 --output small-reef ``` | Option | What changes | Accepted values | | --- | --- | --- | | `--diameter` | Sphere size in blocks. | 16 through 128 | | `--periods` | Surface repetitions across the diameter. | 1 through diameter / 8 | | `--thickness` | Width of the solid band around the surface. | Greater than 0 and less than 1 | ```python title="reef.py" import argparse from math import atan2, cos, sin, tau from pathlib import Path from mcschemora import Schematic, block COLORS = ( "purple", "blue", "light_blue", "cyan", "green", "lime", "yellow", "orange", "red", "magenta", ) def create_reef(diameter=64, periods=2.5, thickness=0.35): if not 16 <= diameter <= 128: raise ValueError("Diameter must be between 16 and 128 blocks.") if not 1 <= periods <= diameter / 8: raise ValueError("Periods must be between 1 and diameter / 8.") if not 0 < thickness < 1: raise ValueError("Thickness must be between 0 and 1, exclusive.") schematic = Schematic.create(version="1.21.1") palette = tuple(block(f"{color}_concrete") for color in COLORS) foundation = block("polished_blackstone") dark = block("black_concrete") center = (diameter - 1) / 2 radius = diameter / 2 radius_squared = radius * radius interior_radius_squared = (radius * 0.8) ** 2 scale = tau * periods / diameter samples = tuple( ( (coordinate - center) ** 2, sin((coordinate - center) * scale), cos((coordinate - center) * scale), ) for coordinate in range(diameter) ) bottom = diameter // 8 twists = tuple(0.9 * (y - center) / diameter for y in range(diameter)) def placements(): for y, margin, material in ((0, 3, foundation), (1, 3, foundation), (2, 2, dark)): for x in range(-margin, diameter + margin): for z in range(-margin, diameter + margin): yield (x, y, z), material for x, (x_squared, sx, cx) in enumerate(samples): for z, (z_squared, sz, cz) in enumerate(samples): remaining = radius_squared - x_squared - z_squared if remaining < 0: continue interior_remaining = interior_radius_squared - x_squared - z_squared angle = atan2(z - center, x - center) / tau term = sx * cz for y in range(bottom, diameter): y_squared, sy, cy = samples[y] if y_squared <= remaining and abs(term + sy * cx + sz * cy) < thickness: index = int(((angle + twists[y]) % 1) * len(palette)) material = dark if y_squared <= interior_remaining else palette[index] yield (x, y - bottom + 3, z), material schematic.region().set_many(placements()) return schematic def main(): parser = argparse.ArgumentParser(description="Build and render a rainbow gyroid reef.") parser.add_argument("--output", type=Path, default=Path("output")) parser.add_argument("--diameter", type=int, default=64) parser.add_argument("--periods", type=float, default=2.5) parser.add_argument("--thickness", type=float, default=0.35) args = parser.parse_args() try: schematic = create_reef(args.diameter, args.periods, args.thickness) except ValueError as error: parser.error(str(error)) args.output.mkdir(parents=True, exist_ok=True) schematic.save(args.output / "reef.schem") image_path = args.output / "reef.png" diagnostics = schematic.export_png(image_path, size=(1600, 1600)) print(f"Saved reef.schem and reef.png ({image_path.stat().st_size / 1024:.0f} KiB)") for diagnostic in diagnostics: print(diagnostic) if __name__ == "__main__": main() ``` ![Finished rainbow gyroid reef](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/reef.png) [Download the schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/reef.schem) [Download the PNG](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/reef.png) --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/jade-scroll/ # Jade mountain scroll Generate layered mountains above a long strip of water, then use their surface heights to place pine trees, waterfalls, and a small pavilion. Seeded noise breaks up the slopes. The composition draws on shan shui painting and [Lingdong Huang's generative landscapes](https://shan-shui-inf.lingdong.works/). With [uv](https://docs.astral.sh/uv/getting-started/installation/) installed, [download jade_scroll.py](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/jade_scroll.py) and run: ```sh uv run --with mcschemora jade_scroll.py ``` The script saves `output/jade-scroll.schem` and a 3840 × 1600 `output/jade-scroll.png`. The published build uses seed 42. Both the noise permutation and other random choices use `seed`, so hold it fixed to compare material or detail changes on the same terrain. To try a different layout with the same palette and details, save a second version: ```sh uv run --with mcschemora jade_scroll.py --seed 17 --output scroll-17 ``` ## Terrain The generator stores blocks by position in `cells`; writing a coordinate again replaces its earlier material. A helper maps layout coordinates to Minecraft: ```python def put(x, y, depth, name, **properties): cells[(x, y, depth - x)] = material(name, **properties) ``` The layout uses `depth` before the `depth - x` shift determines final Z. The `material` helper caches block descriptions by ID and properties, letting repeated placements reuse values. Construction starts with a long strip of water. A sine wave bends its center, noise roughens its tapered outline, and deepslate and cyan terracotta form two bed layers underneath: ```python for x in range(-10, 203): taper = sqrt(max(0, 1 - ((x - 96) / 108) ** 2)) bend = 4 * sin(x * 0.035) half = int(38 * taper + 3 * noise(x * 0.08, 0)) for depth in range(int(bend) - half, int(bend) + half + 1): put(x, -2, depth, "deepslate") put(x, -1, depth, "cyan_terracotta") put(x, 0, depth, "water", level=0) ``` Each island specifies a center, two radii, a base height, a peak height, and a depth layer. The generator checks an elliptical outline for each column, combines three peaks with noise, and fills from bottom to top. Recording `surfaces[(x, depth)] = top` gives the later details a height map to follow. The rock palettes separate the mountain layers: ```python palettes = { "far": ("light_gray_concrete", "diorite", "calcite"), "middle": ("waxed_oxidized_copper", "tuff", "mossy_cobblestone"), "near": ("tuff", "dark_prismarine", "mossy_cobblestone"), } ``` Pale calcite and diorite form distant peaks, copper and tuff fill the middle, and darker prismarine and mossy stone sit nearest the viewer. ![Mountains and water before trees, waterfalls, and the pavilion](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/stages/scroll-terrain.png) ## Trees The `pine` helper reads the terrain height to place a spruce trunk. Shifting the upper half one block gives it a lean; tapering tiers of azalea leaves form the canopy: ```python def pine(x, depth, height): ground = surfaces.get((x, depth)) if ground is None: return lean = rng.choice((-1, 1)) for y in range(1, height + 1): shift = lean if y > height // 2 else 0 put(x + shift, ground + y, depth, "spruce_log", axis="y") put(x + lean, ground + height + 1, depth, "azalea_leaves", persistent=True) for rise in range(3, height + 1, 2): radius = max(1, (height - rise) // 3 + 1) for dx in range(-radius, radius + 1): for dz in range(-radius, radius + 1): if abs(dx) + abs(dz) > radius + 1 or (dx == 0 and dz == 0): continue shift = lean if rise > height // 2 else 0 put(x + shift + dx, ground + rise, depth + dz, "azalea_leaves", persistent=True) ``` `persistent=True` keeps these generated leaves from depending on Minecraft's leaf-decay distance rules. Change the coordinate list below the function to move trees or alter their heights without changing the mountains. ![Pine trees added to the mountain surfaces](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/stages/scroll-trees.png) ## Finishing the scene The waterfall helper follows the surface map toward an island's edge. It chooses a level across the stream's width, fills gaps beneath it with mossy cobblestone, and places source water on top. At the edge, two falling-water columns extend toward the pool: ```python for px in (x, x + 1): for y in range(1, level + 2): put(px, y, edge + 1, "water", level=8) for px in range(x - 2, x + 4): put(px, -1, edge + 2, "prismarine") waterfall(30, 20) waterfall(113, 20) waterfall(165, 18) ``` `level=0` marks source water upstream, and `level=8` marks falling water in the columns. These are authored states; the script does not simulate fluid ticks. ![Three waterfalls added before the pavilion](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/stages/scroll-waterfalls.png) The pavilion sits above the highest ground in its 7 × 7 footprint, with mossy cobblestone filling the gaps underneath. Four dark-oak posts support a roof that falls with distance from its center. An extra block at the outer edge lifts the eaves. After adding three small stepping islands, the generator writes the completed dictionary with `schematic.region().set_many(cells.items())`. The entry point saves the schematic and renders the finished scroll. Try moving a tree, changing a rock palette, or adding a second pavilion. Use [render crops](https://tiltedlabs-ai.github.io/mcschemora/sdk/rendering/) to inspect details hidden behind the mountains. ```python title="jade_scroll.py" import argparse import random from math import floor, sin, sqrt from pathlib import Path from mcschemora import Schematic, block # inspired by shan shui https://shan-shui-inf.lingdong.works/ def make_noise(seed): permutation = list(range(256)) random.Random(seed).shuffle(permutation) permutation *= 2 gradients = ( (1, 0), (-1, 0), (0, 1), (0, -1), (0.7, 0.7), (-0.7, 0.7), (0.7, -0.7), (-0.7, -0.7), ) def noise(x, z): ix, iz = floor(x), floor(z) dx, dz = x - ix, z - iz fx = dx * dx * dx * (dx * (dx * 6 - 15) + 10) fz = dz * dz * dz * (dz * (dz * 6 - 15) + 10) values = [] for oz in (0, 1): for ox in (0, 1): gx, gz = gradients[ permutation[permutation[(ix + ox) & 255] + ((iz + oz) & 255)] & 7 ] values.append(gx * (dx - ox) + gz * (dz - oz)) near = values[0] + fx * (values[1] - values[0]) far = values[2] + fx * (values[3] - values[2]) return near + fz * (far - near) return noise def create_scroll(seed=42): schematic = Schematic.create(version="1.21.1") noise = make_noise(seed) rng = random.Random(seed) cells = {} surfaces = {} materials = {} def material(name, **properties): key = (name, tuple(properties.items())) if key not in materials: materials[key] = block(name, **properties) return materials[key] def put(x, y, depth, name, **properties): cells[(x, y, depth - x)] = material(name, **properties) for x in range(-10, 203): taper = sqrt(max(0, 1 - ((x - 96) / 108) ** 2)) bend = 4 * sin(x * 0.035) half = int(38 * taper + 3 * noise(x * 0.08, 0)) for depth in range(int(bend) - half, int(bend) + half + 1): put(x, -2, depth, "deepslate") put(x, -1, depth, "cyan_terracotta") put(x, 0, depth, "water", level=0) islands = ( (27, -22, 21, 10, 1, 34, "far"), (68, -8, 27, 13, 1, 67, "middle"), (137, -23, 25, 10, 1, 43, "far"), (185, -3, 12, 8, 1, 23, "middle"), (24, 20, 16, 9, 17, 8, "near"), (105, 19, 20, 11, 26, 10, "near"), (163, 16, 17, 10, 19, 17, "near"), (134, 32, 7, 5, 12, 4, "near"), ) palettes = { "far": ("light_gray_concrete", "diorite", "calcite"), "middle": ("waxed_oxidized_copper", "tuff", "mossy_cobblestone"), "near": ("tuff", "dark_prismarine", "mossy_cobblestone"), } for cx, cd, rx, rd, base, height, layer in islands: peaks = ( ( -rx * rng.uniform(0.15, 0.4), -rd * 0.14, rx * rng.uniform(0.28, 0.42), rd * rng.uniform(0.5, 0.75), 1, ), ( rx * rng.uniform(0.15, 0.4), rd * rng.uniform(-0.1, 0.3), rx * rng.uniform(0.2, 0.3), rd * 0.48, rng.uniform(0.45, 0.75), ), (rx * 0.58, -rd * rng.uniform(0.1, 0.45), rx * 0.23, rd * 0.38, rng.uniform(0.2, 0.5)), ) for x in range(cx - rx - 4, cx + rx + 5): for depth in range(cd - rd - 3, cd + rd + 4): u = x - cx + 4 * noise(x * 0.09, depth * 0.09) v = depth - cd + 2 * noise(x * 0.07 + 11, depth * 0.11) radial = (u / rx) ** 2 + (v / rd) ** 2 if radial >= 1: continue shelf = 3 + 3 * (1 - radial) + 2 * noise(x * 0.16, depth * 0.16) crest = max( amplitude * max(0, 1 - ((u - px) / sx) ** 2 - ((v - pd) / sd) ** 2) ** 0.85 for px, pd, sx, sd, amplitude in peaks ) top = int(base + shelf + height * crest * (1 + 0.16 * noise(x * 0.23, depth * 0.2))) bottom = 0 if base == 1 else max(5, int(base - 12 * (1 - radial) ** 0.7)) surfaces[(x, depth)] = top rocks = tuple( palettes[layer][ max( 0, min( 2, int( (0.5 + noise(x * 0.09 + y * 0.027, depth * 0.11 - y * 0.018)) * 3 ), ), ) ] for y in range(bottom, top + 1, 4) ) for y in range(bottom, top + 1): if y == top: rock = "moss_block" if layer != "far" or top < base + 8 else "calcite" elif y < base - 2: rock = "deepslate" if y < base - 6 else "dark_prismarine" else: rock = rocks[(y - bottom) // 4] put(x, y, depth, rock) def pine(x, depth, height): ground = surfaces.get((x, depth)) if ground is None: return lean = rng.choice((-1, 1)) for y in range(1, height + 1): shift = lean if y > height // 2 else 0 put(x + shift, ground + y, depth, "spruce_log", axis="y") put(x + lean, ground + height + 1, depth, "azalea_leaves", persistent=True) for rise in range(3, height + 1, 2): radius = max(1, (height - rise) // 3 + 1) for dx in range(-radius, radius + 1): for dz in range(-radius, radius + 1): if abs(dx) + abs(dz) > radius + 1 or (dx == 0 and dz == 0): continue shift = lean if rise > height // 2 else 0 put(x + shift + dx, ground + rise, depth + dz, "azalea_leaves", persistent=True) for x, depth, height in ( (18, 21, 10), (29, 17, 8), (15, 16, 6), (92, 20, 11), (111, 24, 8), (116, 16, 7), (158, 20, 10), (174, 17, 7), (131, 32, 5), (58, -2, 8), (78, -3, 7), (180, 1, 6), (37, -19, 5), ): pine(x, depth, height) def waterfall(x, depth): edge = depth while (x, edge + 1) in surfaces: edge += 1 level = max( surfaces.get((px, pd), 0) for px in range(x - 1, x + 2) for pd in range(edge - 4, edge + 1) ) for px in range(x - 1, x + 2): for pd in range(edge - 4, edge + 1): ground = surfaces.get((px, pd), level - 1) for y in range(ground + 1, level + 1): put(px, y, pd, "mossy_cobblestone") put(px, level + 1, pd, "water", level=0) for px in (x, x + 1): for y in range(1, level + 2): put(px, y, edge + 1, "water", level=8) for px in range(x - 2, x + 4): put(px, -1, edge + 2, "prismarine") waterfall(30, 20) waterfall(113, 20) waterfall(165, 18) pavilion_x, pavilion_d = 100, 18 floor_y = ( max( surfaces.get((x, depth), 0) for x in range(pavilion_x - 3, pavilion_x + 4) for depth in range(pavilion_d - 3, pavilion_d + 4) ) + 1 ) for x in range(pavilion_x - 3, pavilion_x + 4): for depth in range(pavilion_d - 3, pavilion_d + 4): ground = surfaces.get((x, depth), floor_y - 1) for y in range(ground + 1, floor_y): put(x, y, depth, "mossy_cobblestone") put(x, floor_y, depth, "dark_oak_planks") for dx in (-2, 2): for dd in (-2, 2): for y in range(floor_y + 1, floor_y + 6): put(pavilion_x + dx, y, pavilion_d + dd, "stripped_dark_oak_log", axis="y") for offset in range(-2, 3): for side in (-2, 2): put(pavilion_x + offset, floor_y + 6, pavilion_d + side, "dark_oak_planks") put(pavilion_x + side, floor_y + 6, pavilion_d + offset, "dark_oak_planks") for dx in range(-4, 5): for dd in range(-4, 5): distance = max(abs(dx), abs(dd)) y = floor_y + 9 - distance if distance == 4: y += 1 put(pavilion_x + dx, y, pavilion_d + dd, "dark_prismarine") put(pavilion_x, floor_y + 10, pavilion_d, "dark_prismarine") put(pavilion_x, floor_y + 4, pavilion_d, "lantern", hanging=True) put(pavilion_x, floor_y + 5, pavilion_d, "dark_oak_planks") for index in range(3): cx, cd = 86 + index * 4, 26 + index level = 11 + index * 2 for y in range(level - 4, level): put(cx, y, cd, "deepslate") for dx in range(-2, 3): for dd in range(-1, 2): put(cx + dx, level, cd + dd, "moss_block") schematic.region().set_many(cells.items()) return schematic def main(): parser = argparse.ArgumentParser( description="Build and render a jade mountain scroll with floating islands." ) parser.add_argument("--output", type=Path, default=Path("output")) parser.add_argument("--seed", type=int, default=42) args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=True) schematic = create_scroll(args.seed) schematic.save(args.output / "jade-scroll.schem") image_path = args.output / "jade-scroll.png" diagnostics = schematic.export_png(image_path, size=(3840, 1600)) print( f"Saved jade-scroll.schem and jade-scroll.png ({image_path.stat().st_size / 1024:.0f} KiB)" ) for diagnostic in diagnostics: print(diagnostic) if __name__ == "__main__": main() ``` ![Finished jade mountain scroll](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/jade-scroll.png) [Download the schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/jade-scroll.schem) [Download the PNG](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/jade-scroll.png) --- Source: https://tiltedlabs-ai.github.io/mcschemora/examples/eiffel-tower/ # Eiffel Tower Ask your agent to write the build for you: > Create a recognizable Minecraft Eiffel Tower with four splayed legs, arches > beneath the first platform, a tapering lattice shaft, observation platforms, > and an antenna. Place it on a stone plaza. Write a deterministic Python script > using MCSchemora, validate the result, save a WorldEdit schematic, and render > a transparent PNG. For your own generation loop, give your agent the [full SDK documentation](https://tiltedlabs-ai.github.io/mcschemora/llms.txt) and follow the [agent quickstart](https://tiltedlabs-ai.github.io/mcschemora/quickstart/agents/). ```python title="eiffel_tower.py" import argparse import json from math import ceil, sqrt from pathlib import Path from mcschemora import Schematic, block def create_tower(): cells = {} palette = { name: block(name) for name in ( "brown_concrete", "brown_terracotta", "dark_oak_planks", "dark_oak_fence", "smooth_stone", "stone_bricks", "grass_block", ) } profile = ((0, 30), (14, 27), (32, 20), (48, 15), (64, 11), (88, 7), (112, 4), (148, 1)) def width(y): for (bottom, wide), (top, narrow) in zip(profile, profile[1:], strict=False): if bottom <= y <= top: return wide + (narrow - wide) * (y - bottom) / (top - bottom) raise ValueError(f"Height outside tower profile: {y}") def line(start, end, material, radius=0): steps = max(1, ceil(max(abs(b - a) for a, b in zip(start, end, strict=True)) * 2)) for step in range(steps + 1): x, y, z = (round(a + (b - a) * step / steps) for a, b in zip(start, end, strict=True)) for dx in range(-radius, radius + 1): for dz in range(-radius, radius + 1): cells[(x + dx, y + 4, z + dz)] = palette[material] for x in range(-43, 44): for z in range(-43, 44): lawn = abs(x) > 33 and abs(z) > 33 border = max(abs(x), abs(z)) in (32, 43) or min(abs(x), abs(z)) == 3 material = "grass_block" if lawn else "stone_bricks" if border else "smooth_stone" cells[(x, 0, z)] = palette[material] for sx in (-1, 1): for sz in (-1, 1): for x in range(sx * 30 - 4, sx * 30 + 5): for z in range(sz * 30 - 4, sz * 30 + 5): for y in range(1, 4): cells[(x, y, z)] = palette["stone_bricks"] for y in range(148): line( (sx * width(y), y, sz * width(y)), (sx * width(y + 1), y + 1, sz * width(y + 1)), "brown_concrete", radius=1 if y < 64 else 0, ) for swap in (False, True): for side in (-1, 1): for x in range(-28, 28): y = 10 + 17 * sqrt(1 - (x / 28) ** 2) next_y = 10 + 17 * sqrt(1 - ((x + 1) / 28) ** 2) start = (side * width(y), y, x) if swap else (x, y, side * width(y)) end = ( (side * width(next_y), next_y, x + 1) if swap else (x + 1, next_y, side * width(next_y)) ) line(start, end, "brown_terracotta", radius=1) for bottom in range(32, 144, 8): top = min(bottom + 8, 148) for direction in (-1, 1): start = (direction * width(bottom), bottom, side * width(bottom)) end = (-direction * width(top), top, side * width(top)) if swap: start, end = (start[2], start[1], start[0]), (end[2], end[1], end[0]) line(start, end, "brown_terracotta") start = (-width(bottom), bottom, side * width(bottom)) end = (width(bottom), bottom, side * width(bottom)) if swap: start, end = (start[2], start[1], start[0]), (end[2], end[1], end[0]) line(start, end, "brown_concrete") for y, outer, inner in ((32, 23, 16), (64, 14, 7), (136, 4, 0)): for x in range(-outer, outer + 1): for z in range(-outer, outer + 1): distance = max(abs(x), abs(z)) if distance >= inner: for layer in (y - 1, y): cells[(x, layer + 4, z)] = palette["dark_oak_planks"] if distance == outer or (inner and distance == inner): cells[(x, y + 5, z)] = palette["dark_oak_fence"] for y in range(149, 169): line((0, y, 0), (0, y + 1, 0), "brown_concrete") scene = Schematic.create(version="1.21.1") scene.region().set_many(cells) scene.repair(rules=["fences"]) return scene def main(): parser = argparse.ArgumentParser( description="Generate a Minecraft Eiffel Tower interpretation." ) parser.add_argument("--output", type=Path, default=Path("output/eiffel-tower")) args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=True) scene = create_tower() validation = scene.validate() export = scene.check_export(format="schem") if validation.errors or export.errors or export.losses: raise SystemExit(f"Validation: {validation}\nExport: {export}") scene.save(args.output / "eiffel-tower.schem") diagnostics = scene.export_png(args.output / "preview.png", size=(1600, 2000)) report = { "inspection": scene.inspect(), "validation": { "errors": validation.errors, "warnings": validation.warnings, "unknown": validation.unknown, }, "render_diagnostics": diagnostics, } (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") print(f"Saved tower, preview, and report to {args.output}") if __name__ == "__main__": main() ``` ![Agent-generated Eiffel Tower with four splayed legs, observation platforms, and a lattice shaft](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/eiffel-tower/preview.png) [Download the schematic](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/eiffel-tower/eiffel-tower.schem) [Download the PNG](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/eiffel-tower/preview.png) --- Source: https://tiltedlabs-ai.github.io/mcschemora/reference/python/ # Python API Generated from Python signatures and docstrings by `make docs`. Arguments after `*` are keyword-only. Types and properties are documented below. - [inspect_schematics](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-inspect_schematics) - [Schematic](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#schematic) - [MinecraftData](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#minecraftdata) - [Region](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#region) - [ScheduledTick](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#scheduledtick) - [Selection](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#selection) - [Block](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#block) - [Bounds](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#bounds) - [Fragment](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#fragment) - [Report](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#report) - [RepairChange](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#repairchange) - [RepairReport](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#repairreport) - [block](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-block) - [water_source](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-water_source) - [bed](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-bed) - [door](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-door) - [sign](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-sign) - [chest](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-chest) - [item](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-item) - [mob](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#function-mob) - [Registry](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#registry) - [Entity](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#entity) - [Entities](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#entities) - [BlockEntities](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#blockentities) - [Type aliases](https://tiltedlabs-ai.github.io/mcschemora/reference/python/#type-aliases) ## Function inspect_schematics [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1494) ```python inspect_schematics( schematics: Sequence[Schematic], *, initial_items: Sequence[tuple[str, int]] = (), ) -> dict ``` Combines resource counts and inspection details for multiple schematics. **Args:** - `schematics`: Schematics whose contents contribute to the totals. - `initial_items`: Item identifiers and counts to add to the stored item totals. **Returns:** Combined counts and individual reports in placements. The complete flag is false when any report contains incomplete inspection diagnostics. ## Schematic [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L371) A versioned schematic containing named regions and metadata. Obtain a schematic with create(), load(), or from_bytes(). Its region handles and selections edit the same schematic. ### Schematic.create ```python Schematic.create( *, edition: str = 'java', version: str = 'latest', data: MinecraftData | None = None, ) -> Schematic ``` Creates an empty schematic with a main region and a loaded catalog. **Args:** - `edition`: Minecraft edition; new authoring currently supports java. - `version`: Java version, or latest for the newest supported release. - `data`: Catalog provider; None uses the shared default provider. **Returns:** A new Schematic. **Raises:** `ValueError`: If the edition or version is unsupported or loading fails. ### Schematic.load ```python Schematic.load( path: _Path, *, format: str | None = None, data: MinecraftData | None = None, version: str | None = None, origin: Position | None = None, palette: Mapping[str, Block] | None = None, max_unpacked_bytes: int | None = None, ) -> Schematic ``` Reads a schematic file, preserving its edition and Minecraft version. **Args:** - `path`: Input file path. - `format`: Codec name; None infers it from the extension, with .wiki selecting blueprint. - `data`: Catalog provider; None uses the shared default provider. - `version`: Explicit Java version for blueprint import only. - `origin`: Schematic-global origin for blueprint import only. - `palette`: Blueprint symbols mapped to explicit Block descriptions. **Returns:** A Schematic with any import notices in import_diagnostics. **Raises:** - `OSError`: If the file cannot be read. - `ValueError`: If decoding fails or import options are unsupported. ### Schematic.from_bytes ```python Schematic.from_bytes( content: bytes, *, format: str, data: MinecraftData | None = None, version: str | None = None, origin: Position | None = None, palette: Mapping[str, Block] | None = None, max_unpacked_bytes: int | None = None, ) -> Schematic ``` Decodes schematic bytes without changing their Minecraft version. **Args:** - `content`: Encoded schematic, or UTF-8 text for snbt and blueprint. - `format`: schem (v3), schem2 (v2), litematic, nbt, snbt, mcstructure, or blueprint. - `data`: Catalog provider; None uses the shared default provider. - `version`: Explicit Java version required for blueprint import only. - `origin`: Schematic-global origin for blueprint import only; defaults to (0, 0, 0). - `palette`: Blueprint symbols mapped to explicit Block descriptions. **Returns:** A Schematic with any import notices in import_diagnostics. **Raises:** `ValueError`: If decoding fails or import options are unsupported. ### Schematic.to_bytes ```python Schematic.to_bytes( *, format: str, version: str | None = None, allow_loss: bool = False, flatten: bool = False, ) -> bytes ``` Encodes the schematic, requiring explicit acceptance of reported losses. **Args:** - `format`: schem (v3), schem2 (v2), litematic, nbt, snbt, mcstructure, or blueprint. - `version`: Target Minecraft Java version; None preserves the current version. - `allow_loss`: Whether to accept omissions reported by check_export(). Blocking errors still prevent export. - `flatten`: Whether to merge regions for a single-region format. Overlapping bounds are rejected, and loss of region boundaries is reported. **Returns:** The encoded bytes. **Raises:** `ValueError`: If export has blocking errors or unaccepted losses. ### Schematic.save ```python Schematic.save( path: _Path, *, format: str | None = None, version: str | None = None, allow_loss: bool = False, flatten: bool = False, ) -> None ``` Encodes the schematic and atomically replaces the destination file. **Args:** - `path`: Output file path. - `format`: Codec name; None infers it from the extension, with .wiki selecting blueprint. - `version`: Target Minecraft Java version; None preserves the current version. - `allow_loss`: Whether to accept reported data omissions. Blocking errors still prevent export. - `flatten`: Whether to merge regions for a single-region format. **Raises:** - `OSError`: If the output file cannot be written. - `ValueError`: If export has blocking errors or unaccepted losses. ### Schematic.region `Schematic.region(name: str = 'main') -> Region` Returns an editing handle for an existing named region. **Args:** `name`: Region name. **Raises:** `ValueError`: If the region does not exist. ### Schematic.export_glb ```python Schematic.export_glb( path: _Path, *, region: str | None = None, x: AxisRange = None, y: AxisRange = None, z: AxisRange = None, ) -> tuple[str, ...] ``` Writes textured geometry to a binary glTF file. Identical blocks and attached data at shared global positions render once. Palette states are converted once to 1.21.6 for rendering; stored blocks stay unchanged. **Args:** - `path`: Output file path, replaced if it exists. - `region`: Region name; None selects all regions. - `x`: Global X coordinate or inclusive (minimum, maximum) pair; None keeps all. - `y`: Global Y coordinate or inclusive (minimum, maximum) pair; None keeps all. - `z`: Global Z coordinate or inclusive (minimum, maximum) pair; None keeps all. **Returns:** Diagnostics describing visual approximations. **Raises:** `ValueError`: If overlapping regions contain conflicting blocks or attached data. ### Schematic.export_blueprint ```python Schematic.export_blueprint( path: _Path, *, name: str = 'Blueprint', region: str | None = None, y: AxisRange = None, rotation: int = 0, sprites: Mapping[str, str] | None = None, ) -> tuple[str, ...] ``` Writes Minecraft Wiki layered-blueprint markup using block sprites. **Args:** - `path`: Output UTF-8 file path, replaced if it exists. - `name`: Blueprint title. - `region`: Region name; None selects all regions. - `y`: Global Y coordinate or inclusive pair; None keeps all layers. - `rotation`: Number of quarter turns about Y. - `sprites`: Block IDs or full state strings mapped to wiki sprite identifiers. **Returns:** Diagnostics for state properties, attached data, and other omissions. ### Schematic.export_sprites ```python Schematic.export_sprites( path: _Path, *, view: str = 'top', cell_size: int = 32, grid: bool = False, entities: bool = True, region: str | None = None, x: AxisRange = None, y: AxisRange = None, z: AxisRange = None, sprites: Mapping[str, str] | None = None, ) -> tuple[str, ...] ``` Writes a flat PNG diagram using bundled Minecraft Wiki sprites. **Args:** - `path`: Output file path, replaced if it exists. - `view`: top, bottom, north, south, east, or west. - `cell_size`: Pixels per grid cell, from 1 through 128. - `grid`: Whether to draw grid lines. - `entities`: Whether to include free-entity icons. - `region`: Region name; None selects all regions. - `x`: Global X coordinate or inclusive pair; None keeps all. - `y`: Global Y coordinate or inclusive pair; None keeps all. - `z`: Global Z coordinate or inclusive pair; None keeps all. - `sprites`: Block IDs or full state strings mapped to wiki sprite identifiers. **Returns:** Diagnostics describing omitted state details and sprite approximations. ### Schematic.export_png ```python Schematic.export_png( path: _Path, *, size: tuple[int, int] | list[int] = (1024, 1024), view: str = 'isometric', grid: bool = False, threads: int = 8, region: str | None = None, x: AxisRange = None, y: AxisRange = None, z: AxisRange = None, ) -> tuple[str, ...] ``` Writes an automatically framed textured PNG with a transparent background. Identical blocks and attached data at shared global positions render once. Palette states are converted once to 1.21.6 for rendering; stored blocks stay unchanged. **Args:** - `path`: Output file path, replaced if it exists. - `size`: (width, height), each from 1 through 4096 pixels. - `view`: isometric, top, bottom, north, south, east, or west. Cardinal names describe the viewer's location; side views keep Y-up vertical. - `grid`: Whether to draw outlined block edges; entities are excluded. - `threads`: Maximum rasterizer worker threads; a positive integer, default 8. - `region`: Region name; None selects all regions. - `x`: Global X coordinate or inclusive pair; None keeps all. - `y`: Global Y coordinate or inclusive pair; None keeps all. - `z`: Global Z coordinate or inclusive pair; None keeps all. **Returns:** Diagnostics describing visual approximations. Rendering uses the shared Java 1.21.6 visual bundle. **Raises:** `ValueError`: If overlapping regions contain conflicting blocks or attached data. ### Schematic.add_region `Schematic.add_region(name: str, *, origin: Position = (0, 0, 0)) -> Region` Adds an empty region and returns its editing handle. **Args:** - `name`: Nonempty, unique region name. - `origin`: Region origin in schematic-global coordinates. **Raises:** `ValueError`: If the name is empty or already exists. ### Schematic.regions `Schematic.regions: tuple[str, ...]` The names of the schematic's regions. ### Schematic.import_diagnostics `Schematic.import_diagnostics: tuple[str, ...]` Notices about assumptions or omissions made while importing. ### Schematic.edition `Schematic.edition: str` The schematic's Minecraft edition. ### Schematic.version `Schematic.version: str` The schematic's Minecraft version string. ### Schematic.data_version `Schematic.data_version: int` The numeric Minecraft data version stored in the schematic. ### Schematic.metadata `Schematic.metadata: str` Schematic metadata as typed SNBT; assigning replaces the whole compound. Writable property. Replaces schematic metadata with a typed SNBT compound. ### Schematic.registry `Schematic.registry: Registry` Block schema access for the schematic's Minecraft version. ### Schematic.inspect `Schematic.inspect() -> dict` Returns resource counts, inventories, payload details, and inspection diagnostics. **Returns:** A dictionary whose complete flag is false when text could not be inspected. ### Schematic.material_cost `Schematic.material_cost() -> dict` Returns fractional primitive-material costs for placed blocks without editing them. Recipe costs are compiled once per catalog version and shared between schematics. Shaped crafting recipes take priority; other candidates retain catalog order. The first recipe that expands to declared primitives without a cycle is used. The built-in Java primitive policy defines gathering boundaries, including logs, minerals, natural blocks, drops, and plants. World-block primitives such as bedrock and portals count once per occupied block without requiring inventory items. Water and lava count only source blocks (level=0); flowing and falling fluids are excluded. Any block or item without a recipe expansion counts as one unit of itself. This does not find the cheapest recipe. Doors, beds, and tall plants count once per pair; orphan halves count once. Double slabs and stacked candles, eggs, snow layers, and plants use item quantities. Wall-mounted variants resolve to their inventory items. Regions contribute their stored placements, including overlaps. Inventories and entities are excluded. **Returns:** A dictionary containing items (placed item or primitive block counts) and raw_materials (fractional primitive quantities). Fuel, tool wear, fluid acquisition, and component-dependent recipes are outside this estimate. Filled-container primitives count gross inputs; returned empty containers are not credited. **Raises:** `ValueError`: If the schematic is not Java, its catalog or recipes are unavailable, recipe data is invalid, or counts overflow. ### Schematic.value_cost `Schematic.value_cost(profile: str) -> dict` Values primitive material quantities using a bundled price profile. Calls material_cost() and sums primitive quantity times unit price. Missing prices contribute nothing and are returned with their primitive quantities. A price of zero is priced. No normalization or schematic editing is performed. Profiles are fixed snapshots shared across Minecraft versions. **Args:** `profile`: emc for ProjectE-based values or essentialsx for server sell prices. **Returns:** A dictionary containing total (the priced sum) and unpriced (primitive IDs and quantities missing a price). The total is partial when unpriced is nonempty. **Raises:** `ValueError`: If the profile is unknown, prices are invalid, material costs cannot be computed, or the total overflows. ### Schematic.normalize ```python Schematic.normalize( profile: _Path | None = None, *, keep: Sequence[str] = (), replace: Mapping[str, str] | None = None, fallback: str | None = None, ) -> dict ``` Normalizes all regions using inline rules and an optional profile. Explicit keep wins over replace, which overrides profile keeps and replacements. An explicit fallback overrides the profile fallback. Without a fallback, unlisted blocks remain unchanged. Override targets remain canonical; chained mappings are skipped, so reapplying the same rules changes nothing. Profiles must match the schematic's edition; block IDs are checked against its version. Non-air replacements retain properties supported by the target, discard unsupported properties, and use target defaults for new properties. Shared property values must be valid for the target. Both blocks must use the same block-entity type, and compatible attached data is preserved unchanged. Attached-data IDs must match when present; an omitted ID uses the known owning block-entity type. Invalid or incompatible replacements are skipped silently. **Args:** - `profile`: Optional bundled profile name (redstone), or a path to a UTF-8 JSON file with edition and optional keep, replacements, and fallback. keep is a list of block IDs; fallback is a block ID. Each replacement has a from list and a to block ID. - `keep`: Block IDs to preserve for this call, including all states and attached data. - `replace`: Mapping of source block IDs to target block IDs for this call. Invalid overrides leave their source blocks unchanged. - `fallback`: Block ID for remaining eligible blocks. None uses the profile's fallback, if any. A fallback that is itself replaced is skipped. **Returns:** A dictionary with changed (total replaced blocks) and replacements (from, to, and count records, sorted by source block ID). **Raises:** - `OSError`: If the profile file cannot be read. - `ValueError`: If the profile JSON is malformed, the edition differs, or the schematic has no catalog. No changes are committed. - `TypeError`: If keep is a string, replace is not a mapping, or block IDs are not strings. ### Schematic.validate `Schematic.validate() -> Report` Checks Java game rules without changing the schematic or simulating ticks. **Returns:** A Report with structural errors, unstable-state warnings, and unknown checks requiring surrounding blocks or unavailable game data. ### Schematic.repair `Schematic.repair(*, rules: Sequence[str] | None = None) -> RepairReport` Repairs neighbor-dependent connections and shapes in place. Uses the same expected-state calculations as validate(). All supported rules run by default. Neighbor lookups cross regions in schematic-global coordinates; known connections are repaired even when other sides are unknown. Properties requiring unknown surroundings remain unchanged. Isolated redstone dots remain dots. Power, facing, waterlogging, entities, and attached data are preserved. Loading never invokes repair automatically. **Args:** `rules`: Any subset of redstone, stairs, fences, panes, and walls. None enables all rules; an empty sequence changes nothing. **Returns:** A RepairReport containing before/after states and skipped reasons. **Raises:** - `ValueError`: If a rule is unsupported, regions overlap, bounds are invalid, or repairs cannot converge. No changes are committed. - `TypeError`: If rules is a string rather than a sequence of rule names. ### Schematic.check_export `Schematic.check_export(*, format: str, version: str | None = None, flatten: bool = False) -> Report` Checks conversion errors and losses without writing or changing the schematic. **Args:** - `format`: Target codec name. - `version`: Target Minecraft Java version; None preserves the current version. - `flatten`: Whether to evaluate merging regions for a single-region format. **Returns:** A Report whose errors block export and whose losses need allow_loss=True. ## MinecraftData [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L232) Shared access to pinned Java catalogs and cached rendering assets. ### MinecraftData.__init__ `MinecraftData(cache_dir: _Path | None = None, *, offline: bool = False) -> None` Creates a catalog provider without preloading catalogs or visuals. **Args:** - `cache_dir`: Cache directory; None uses the platform default. - `offline`: Whether to require cached data and disable downloads. ### MinecraftData.cache_dir `MinecraftData.cache_dir: Path` The resolved directory used for cached catalogs and rendering assets. ### MinecraftData.versions `MinecraftData.versions: tuple[str, ...]` Available Java catalog versions at or above the 1.13 minimum. ### MinecraftData.load `MinecraftData.load(version: str = 'latest') -> str` Loads a catalog and returns its resolved Java version string. **Args:** `version`: Java version, or latest for the newest supported release. **Raises:** `ValueError`: If the version is unsupported or its catalog cannot be loaded. ### MinecraftData.prepare ```python MinecraftData.prepare( version: str = 'latest', *, target: str | None = None, visuals: bool = False, ) -> str ``` Prepares a Minecraft version for later offline use. **Args:** - `version`: Java version, or latest for the newest supported release. - `target`: Optional explicit conversion target. Also prepares intermediate catalogs and biomes used by that conversion route. - `visuals`: Whether to also prepare textured rendering assets and the shared rendering catalog. Sprite diagrams do not need these assets. **Returns:** The resolved Java version. Downloads use the configured cache directory. **Raises:** `ValueError`: If required data is unavailable, invalid, or missing while offline. A fresh cache requires a network connection. ### MinecraftData.dataset `MinecraftData.dataset(version: str, kind: str) -> JsonValue` Loads and caches a parsed catalog dataset for a Java version. **Args:** - `version`: Java version, or latest for the newest supported release. - `kind`: blocks, items, entities, blockCollisionShapes, biomes, recipes, recipeDefinitions, or itemTags. A shared tracker stores official server-JAR recipes and maps them to the requested version's item IDs. recipeDefinitions preserves original JSON; itemTags contains resolved numeric item IDs. Optional datasets load on demand. **Returns:** The dataset's JSON value. **Raises:** `ValueError`: If the dataset is unavailable, uncached in offline mode, invalid, or its kind is unsupported. No other version is substituted. ### MinecraftData.load_visuals `MinecraftData.load_visuals(version: str = 'latest') -> Path` Prepares rendering assets and returns their cache directory. Loads the requested and shared rendering catalogs for offline rendering. **Args:** `version`: Java version, or latest. All versions use the 1.21.6 visual bundle. **Raises:** `ValueError`: If the version is unsupported or the assets cannot be prepared. ## Region [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L960) An editing handle for a named region within a schematic. Cell coordinates are local to this region. Its origin locates those coordinates in schematic-global coordinates. Obtain a handle through Schematic.region() or add_region(). ### Region.bounds `Region.bounds: Bounds` The region's stored bounding box in local coordinates. ### Region.origin `Region.origin: Position` The schematic-global coordinates corresponding to this region's local (0, 0, 0). ### Region.to_global `Region.to_global(local: Position) -> Position` Converts a region-local position to schematic-global coordinates by adding the origin. **Args:** `local`: Integer coordinates relative to this region's origin. **Raises:** `ValueError`: If the result exceeds signed 32-bit coordinates. ### Region.to_local `Region.to_local(global_position: Position) -> Position` Converts a schematic-global position to region-local coordinates by subtracting the origin. **Args:** `global_position`: Integer coordinates in the schematic's shared coordinate space. **Raises:** `ValueError`: If the result exceeds signed 32-bit coordinates. ### Region.get `Region.get(at: Position) -> Block` Returns the block at a position in this region. **Args:** `at`: Integer coordinates relative to the region's origin. **Returns:** The block at the position, or air if the cell is absent. ### Region.get_all `Region.get_all() -> dict[Position, Block]` Returns a snapshot of non-air blocks keyed by region-local coordinates. Identical states share immutable Block objects. Changes to the returned dictionary do not edit the schematic. Block entities and entities are excluded. ### Region.set `Region.set(at: Position, content: Block | Fragment) -> None` Writes a block or pastes a fragment, replacing destination cells. **Args:** - `at`: Local cell coordinates; fragments are anchored at their minimum corner. - `content`: Block description or independent Fragment. Fragments require matching editions and versions and preserve unrelated entities. ### Region.set_many ```python Region.set_many( placements: Mapping[Position, Block] | Iterable[tuple[Position, Block]], ) -> None ``` Validates and writes a batch of blocks atomically. **Args:** `placements`: Mapping of local positions to Blocks, or an iterable of (local position, Block) pairs. Later writes to the same position take precedence. Omitted positions are unchanged; write air to clear cells. **Raises:** `ValueError`: If a block, coordinate, or region-bound change is unsupported. No blocks are written when validation fails. ### Region.delete `Region.delete() -> None` Clears blocks, attached data, and entities within this region's bounds. The named region, origin, and bounds remain in the schematic. ### Region.patch `Region.patch(at: Position, **properties: PropertyValue) -> None` Changes supplied properties of the block at a local cell position. **Args:** - `at`: Local cell coordinates. - `**properties`: Minecraft properties to replace; other properties are preserved. ### Region.select `Region.select(*, start: Position, size: Position) -> Selection` Returns a box selection that edits this region's current content. **Args:** - `start`: Inclusive minimum local coordinates; negative values are allowed. - `size`: Nonnegative cell counts along X, Y, and Z. Upper bounds are exclusive. **Returns:** A Selection including cells and entities within the box. ### Region.place `Region.place(placement: _Placement, *, at: Position, replace: bool = False) -> None` Validates and commits a placement recipe atomically. **Args:** - `placement`: Placement returned by bed(), door(), sign(), or chest(). - `at`: Local anchor cell: the foot of a bed, lower half of a door, or the sign or chest block. - `replace`: Whether to overwrite non-air blocks at recipe targets. **Raises:** `ValueError`: If the recipe is invalid for this version or targets are occupied with replace=False. ### Region.scheduled_ticks `Region.scheduled_ticks: tuple[ScheduledTick, ...]` Scheduled block and fluid updates in local coordinates, ordered by tick order. ### Region.entities `Region.entities: Entities` The manager for entities in this region. ### Region.block_entities `Region.block_entities: BlockEntities` The manager for NBT attached to this region's blocks. ## ScheduledTick [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1373) A scheduled update retained from an imported Litematic region. **Attributes:** - `position`: Region-local cell coordinates. - `identifier`: Namespaced block or fluid identifier. - `fluid`: Whether this update belongs to the fluid tick list. - `delay`: Delay in game ticks. - `priority`: Minecraft tick priority, from -3 through 3. - `order`: Ordering value within the scheduled updates. ```python ScheduledTick.position: Position ScheduledTick.identifier: str ScheduledTick.fluid: bool ScheduledTick.delay: int ScheduledTick.priority: int ScheduledTick.order: int ``` ## Selection [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1135) A set of region-local cells and entities that reads current content. Filters resolve membership once. Transforms update this selection's coordinates; other selections retain theirs. Block filters exclude entities. ### Selection.bounds `Selection.bounds: Bounds` The selection's local bounding box. ### Selection.get_all `Selection.get_all() -> dict[Position, Block]` Returns current non-air blocks at selected region-local coordinates. The dictionary is an independent snapshot, with identical states sharing immutable Block objects. Block entities and entities are excluded. ### Selection.select ```python Selection.select( *, block: str | None = None, properties: Mapping[str, PropertyValue] | None = None, ) -> Selection ``` Returns a new selection filtered by current block IDs and properties. **Args:** - `block`: Minecraft block identifier; None accepts any block ID. - `properties`: Required property values; None leaves properties unrestricted. **Returns:** A selection with fixed cell membership and no entities. **Raises:** `ValueError`: If neither a block ID nor a property filter is supplied. ### Selection.fill `Selection.fill(value: Block) -> Selection` Fills selected cells with a block and returns self; entities are unchanged. ### Selection.replace `Selection.replace(identifier: str, value: Block) -> Selection` Replaces selected blocks matching an identifier and returns self. **Args:** - `identifier`: Minecraft block ID to match, regardless of properties. - `value`: Replacement block description. ### Selection.patch `Selection.patch(**properties: PropertyValue) -> Selection` Changes supplied properties on selected blocks and returns self. **Args:** `**properties`: Properties to replace; other properties and entities remain. ### Selection.delete `Selection.delete() -> Selection` Clears selected blocks, attached data, and selected entities; returns self. ### Selection.move `Selection.move(*, offset: Position, replace: bool = False) -> Selection` Moves selected content atomically, updates membership, and returns self. **Args:** - `offset`: Local X, Y, and Z displacement. - `replace`: Whether to overwrite occupied targets outside the source selection. **Raises:** `ValueError`: If a target is occupied with replace=False or movement is unsupported. Self-overlap is allowed; selected air clears targets. ### Selection.rotate ```python Selection.rotate( *, axis: str = 'y', steps: int = 1, pivot: FloatPosition | None = None, replace: bool = False, ) -> Selection ``` Rotates content atomically, updates membership, and returns self. **Args:** - `axis`: Rotation axis; currently only y is supported. - `steps`: Number of quarter turns. Positive steps turn north toward west. - `pivot`: Local coordinates; None uses the bounding box's geometric center. - `replace`: Whether to overwrite occupied targets outside the source selection. **Raises:** `ValueError`: If cells end off-grid, a target is occupied with replace=False, or block states or attached data cannot be transformed. ### Selection.flip `Selection.flip(*, axis: str, center: float | None = None, replace: bool = False) -> Selection` Reflects content atomically, updates membership, and returns self. **Args:** - `axis`: Reflection axis, x or z. - `center`: Local plane coordinate; None uses the bounding box's center. - `replace`: Whether to overwrite occupied targets outside the source selection. **Raises:** `ValueError`: If cells end off-grid, a target is occupied with replace=False, or block states or attached data cannot be transformed. ### Selection.duplicate `Selection.duplicate(*, offset: Position, replace: bool = False) -> Selection` Copies content at an offset and returns a new destination selection. **Args:** - `offset`: Local X, Y, and Z displacement. - `replace`: Whether to overwrite occupied targets. Selected air clears targets. **Returns:** The copied selection. The source selection retains its coordinates; copied entities receive new references. ### Selection.copy `Selection.copy() -> Fragment` Returns an independent fragment anchored at the selection's minimum corner. Selected air and attached data are included; unselected cells are omitted. **Raises:** `ValueError`: If retained format data prevents copying the region. ### Selection.counts `Selection.counts() -> dict[str, int]` Returns counts by full block-state string, excluding all air block types. ### Selection.describe_layer `Selection.describe_layer(*, y: int) -> str` Returns a local Y layer as a text grid followed by a block-state legend. **Args:** `y`: Local Y coordinate. Z increases down the grid; . means air and - means unselected. An empty layer returns a descriptive message. **Raises:** `ValueError`: If the selection's X/Z area exceeds 65,536 cells. ## Block [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L76) Immutable block description. Use block() to normalize an identifier and its properties. **Attributes:** - `id`: Namespaced Minecraft block identifier. - `properties`: Read-only Minecraft property names and values. ```python Block.id: str ``` ### Block.properties `Block.properties: Mapping[str, str]` The read-only mapping of Minecraft property names to string values. ### Block.__str__ `Block.__str__() -> str` Returns the full block-state string with properties in sorted order. ## Bounds [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L138) A box with an inclusive start and exclusive upper bounds. **Attributes:** - `start`: Minimum local cell coordinates. - `size`: Cell counts along X, Y, and Z. ```python Bounds.start: Position Bounds.size: Position ``` ## Fragment [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1316) An independent copy of selected cells, attached data, and entities. Obtain one through Selection.copy() and paste it with Region.set(). Pasting requires matching Minecraft editions and versions. ### Fragment.size `Fragment.size: Position` Cell counts along X, Y, and Z in the copied bounding box. ## Report [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L191) Issues found during game-rule validation or export preflight. **Attributes:** - `errors`: Problems that prevent validation or export. - `losses`: Data omissions requiring explicit acceptance for export. - `warnings`: Unstable states or other advisory messages. - `unknown`: Checks that lack surrounding blocks or required game data. ```python Report.errors: tuple[str, ...] Report.losses: tuple[str, ...] Report.warnings: tuple[str, ...] Report.unknown: tuple[str, ...] ``` ### Report.issues `Report.issues: tuple[str, ...]` All messages in error, loss, warning, then unknown order. ### Report.ok `Report.ok: bool` Whether errors, losses, and unknown results are absent; warnings are allowed. ### Report.__str__ `Report.__str__() -> str` Returns labeled issues, or "No issues found." for an empty report. ## RepairChange [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L156) A repaired block, identified by region and local position. **Attributes:** - `region`: Name of the containing region. - `position`: Region-local cell coordinates. - `before`: Block state before repair. - `after`: Block state after repair. ```python RepairChange.region: str RepairChange.position: Position RepairChange.before: Block RepairChange.after: Block ``` ## RepairReport [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L173) Changes applied by repair and cases skipped because their context is unknown. **Attributes:** - `changes`: Immutable snapshots of changed blocks. - `skipped`: Reasons why individual properties could not be repaired. ```python RepairReport.changes: tuple[RepairChange, ...] RepairReport.skipped: tuple[str, ...] ``` ### RepairReport.changed `RepairReport.changed: int` The number of blocks changed. ## Function block [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L115) `block(identifier: str, **properties: PropertyValue) -> Block` Creates a block description, adding the minecraft namespace if omitted. **Args:** - `identifier`: Minecraft block identifier. - `**properties`: Minecraft properties as strings, integers, or booleans. **Returns:** An immutable Block. Catalog validation occurs when it is placed. ## Function water_source [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L132) `water_source() -> Block` Returns a water block with level=0. ## Function bed [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/src/lib.rs#L727) `bed(*, color: str = 'red', head_toward: str = 'north') -> Placement` Creates a bed placement anchored at the foot block when placed. **Args:** - `color`: Minecraft bed color. - `head_toward`: Direction from the foot to the head: north, south, east, or west. **Returns:** A two-block placement for Region.place. Validated when placed. ## Function door [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/src/lib.rs#L748) ```python door( *, material: str = 'oak', facing: str = 'north', hinge: str = 'left', open: bool = False, powered: bool = False, ) -> Placement ``` Creates a door placement anchored at the lower block when placed. **Args:** - `material`: Minecraft door material, such as oak or iron. - `facing`: Horizontal facing direction. - `hinge`: Hinge side, left or right. - `open`: Whether the door is open. - `powered`: Whether the door is powered. **Returns:** A two-block placement for Region.place. Validated when placed. ## Function sign [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/src/lib.rs#L789) ```python sign( lines: Sequence[str], *, material: str = 'oak', rotation: int = 0, color: str = 'black', ) -> Placement ``` Creates a standing-sign placement with plain text on its front face. **Args:** - `lines`: Up to four text lines; omitted lines are blank. - `material`: Minecraft sign material, such as oak. - `rotation`: Minecraft rotation value, 0 through 15. - `color`: Minecraft text color. **Returns:** A placement for Region.place, with text encoded for the target version. ## Function chest [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/src/lib.rs#L769) ```python chest( *, facing: str = 'north', items: Mapping[int, _Item] | None = None, ) -> Placement ``` Creates a single-chest placement with optional inventory contents. **Args:** - `facing`: Horizontal facing direction. - `items`: Slots 0 through 26 mapped to item() values; None leaves it empty. **Returns:** A placement for Region.place. Items and states are validated when placed. ## Function item [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1332) `item(identifier: str, *, count: int = 1, components: str | None = None) -> _Item` Creates an inventory item value for chest(). **Args:** - `identifier`: Minecraft item identifier. - `count`: Item count, from 1 through 99 when placed. - `components`: Optional typed SNBT compound; requires Java 1.20.5 or newer. **Returns:** An (identifier, count, components) tuple, validated on chest placement. ## Function mob [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1355) `mob(identifier: str, *, persistent: bool = True, nbt: str | None = None) -> _Mob` Creates a free-entity description for Region.entities.add(). **Args:** - `identifier`: Living-mob identifier supported by the target catalog. - `persistent`: Whether to set the entity's PersistenceRequired flag. - `nbt`: Optional typed SNBT compound; id and persistence are set from the supplied arguments when the entity is added. **Returns:** An entity description, validated against the target catalog when added. ## Registry [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L331) Block schemas for a schematic's version, obtained through its registry. ### Registry.describe `Registry.describe(identifier: str) -> dict[str, JsonValue]` Returns a block schema for this schematic's Minecraft version. **Args:** `identifier`: Minecraft block identifier, with an optional namespace. **Returns:** A dictionary with id, properties, version, and numeric_id. **Raises:** `ValueError`: If the block is unknown or the schematic has no catalog. ## Entity [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1394) An immutable snapshot of an entity returned by Entities.get(). **Attributes:** - `reference`: Schematic-local integer used to address the stored entity. - `position`: Floating-point coordinates local to its region. - `nbt`: The entity's full typed SNBT compound. ```python Entity.reference: int Entity.position: FloatPosition Entity.nbt: str ``` ## Entities [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1408) Access to a region's entities through schematic-local integer references. ### Entities.add `Entities.add(value: _Mob, *, at: FloatPosition) -> int` Adds an entity and returns its schematic-local reference. **Args:** - `value`: Entity description returned by mob(). - `at`: Floating-point coordinates local to the region. ### Entities.get `Entities.get(reference: int) -> Entity` Returns an immutable snapshot of the entity with the given reference. **Args:** `reference`: Schematic-local reference of an entity in this region. **Raises:** `ValueError`: If the reference does not identify an entity in this region. ### Entities.update ```python Entities.update( reference: int, *, position: FloatPosition | None = None, nbt: str | None = None, ) -> None ``` Replaces supplied fields of an entity; omitted fields are preserved. **Args:** - `reference`: Schematic-local reference of an entity in this region. - `position`: New floating-point local coordinates; None preserves the position. - `nbt`: Full typed SNBT compound including id; None preserves attached data. ### Entities.remove `Entities.remove(reference: int) -> None` Removes the entity identified by a schematic-local reference. **Args:** `reference`: Schematic-local reference of an entity in this region. **Raises:** `ValueError`: If the reference does not identify an entity in this region. ### Entities.__iter__ `Entities.__iter__() -> Iterator[int]` Iterates a snapshot of this region's entity references. **Yields:** Schematic-local integer references accepted by this manager. ## BlockEntities [Source](https://github.com/tiltedlabs-ai/mcschemora/blob/main/bindings/python/python/mcschemora/__init__.py#L1467) Access to typed NBT attached to blocks at region-local cell coordinates. ### BlockEntities.get `BlockEntities.get(at: Position) -> str | None` Returns typed SNBT at a local cell position, or None if no data is attached. ### BlockEntities.set `BlockEntities.set(at: Position, nbt: str) -> None` Replaces the NBT attached to a block at a local cell position. **Args:** - `at`: Local coordinates of the owning block. - `nbt`: Full typed SNBT compound with an id compatible with that block. **Raises:** `ValueError`: If parsing fails or id is missing or incompatible. ### BlockEntities.remove `BlockEntities.remove(at: Position) -> None` Removes attached NBT at a local cell position; the owning block remains. ## Type aliases ```python Position = tuple[int, int, int] FloatPosition = tuple[float, float, float] PropertyValue = str | int | bool AxisRange = int | tuple[int, int] | list[int] | None JsonValue = bool | int | float | str | list['JsonValue'] | dict[str, 'JsonValue'] | None _Path = str | PathLike[str] _Item = tuple[str, int, str | None] ``` `Placement` (`_Placement` in facade annotations) is the opaque recipe returned by `bed`, `door`, `chest`, and `sign`. `_Mob` is the entity description returned by `mob`. --- Source: https://tiltedlabs-ai.github.io/mcschemora/reference/wasm/ # Browser WASM API Generated from wasm-bindgen declarations by `make docs`. See the [browser quickstart](https://tiltedlabs-ai.github.io/mcschemora/languages/wasm/) for initialization, file import, and resource cleanup. The complete declarations, including initialization types, are generated at `bindings/wasm/pkg/mcschemora.d.ts` during the browser build. ```typescript /** * JavaScript MinecraftData: shared Minecraft Java catalogs fetched and cached in memory. */ export class MinecraftData { free(): void; [Symbol.dispose](): void; /** * Loads a catalog and fulfills with an empty Java Schematic containing a main region. */ create(version: string): Promise; /** * Loads and caches a JSON dataset: blocks, items, entities, blockCollisionShapes, * biomes, recipes, recipeDefinitions, or itemTags. A shared tracker stores official * server-JAR recipes with version-specific item IDs. Optional datasets load on demand. */ dataset(version: string, kind: string): Promise; /** * JavaScript fromBytes: decodes a Uint8Array and fulfills with a Schematic. * * format selects the codec. options may contain blueprint-only version, origin, and palette; * version must be explicit for blueprints. */ fromBytes(bytes: Uint8Array, format: string, options: any): Promise; /** * Resolves a Java version, loads its catalog, and fulfills with the resolved version. */ load(version: string): Promise; /** * Creates a catalog provider. */ constructor(); /** * Fetches metadata and fulfills with supported Java version strings. */ versions(): Promise; } /** * JavaScript Schematic: a versioned schematic with named regions. */ export class Schematic { private constructor(); free(): void; [Symbol.dispose](): void; checkExport(format: string, flatten: boolean, version?: string | null): Promise; /** * JavaScript getBlock: returns a full state string at local integer coordinates. * * Absent cells read as air; an unknown region throws an Error. */ getBlock(region: string, x: number, y: number, z: number): string; /** * Returns items and fractional raw_materials. Blocks and items without a recipe * expansion count as one primitive unit of themselves. * Water and lava count only source blocks (level=0); flowing and falling fluids are excluded. * Costs are cached by catalog version. Shaped recipes precede other catalog recipes; * the first acyclic expansion to declared primitives wins. Paired structures count once, * orphan halves once, and double slabs/stacked items use their item quantities. * Regions are summed, including overlaps. Inventories, entities, fuel, tool wear, * fluid acquisition, and component-dependent recipes are excluded. No blocks are edited. * Filled-container primitives count gross inputs; returned containers are not credited. */ materialCost(): Promise; /** * Applies inline options and an optional bundled profile name or JSON profile object. * * Edition must match; block IDs are checked against the schematic's version. * Non-air replacements retain supported properties, discard unsupported ones, and use * target defaults for new properties. Shared values must be valid. Both blocks require * the same block-entity type. Compatible attached data is preserved. Invalid replacements are * skipped silently. Options contain keep (block IDs), replace (source-to-target object), * and fallback (block ID). Explicit keep wins over replace, then profile rules. * Invalid overrides leave their sources unchanged. Override targets remain canonical. * A fallback that is itself replaced is skipped. Malformed profiles or options throw an Error. */ normalize(profile?: any | null, options?: any | null): any; /** * Returns region descriptions with name, schematic-global origin, local start, and size. */ regions(): any; repair(rules?: string[] | null): any; scheduledTicks(region: string): any; /** * JavaScript setBlock: validates and writes a state string at local coordinates. */ setBlock(region: string, x: number, y: number, z: number, state: string): void; /** * JavaScript toBytes: encodes the schematic as a Uint8Array. * * allow_loss accepts reported omissions; flatten merges regions when required. * Blocking errors and unaccepted losses throw an Error. */ toBytes(format: string, allow_loss: boolean, flatten: boolean, version?: string | null): Promise; toGlobal(region: string, x: number, y: number, z: number): Int32Array; toLocal(region: string, x: number, y: number, z: number): Int32Array; /** * Returns errors, warnings, and unknown arrays without changing the schematic. */ validate(): any; /** * Values primitive quantities with the bundled emc or essentialsx profile. * Returns total and unpriced primitive quantities. Missing prices contribute nothing; * zero prices are priced. Uses materialCost without normalizing or editing blocks. * Profiles are fixed across versions. Unknown profiles, invalid data, and overflow reject. */ valueCost(profile: string): Promise; /** * JavaScript importDiagnostics: notices about import assumptions and omissions. */ readonly importDiagnostics: string[]; /** * The schematic Minecraft version string. */ readonly version: string; } ``` --- Source: https://tiltedlabs-ai.github.io/mcschemora/reference/formats/ # Formats MCSchemora creates new builds against Java catalogs. It also imports Bedrock structures, retaining data for export back to `.mcstructure`. Operation support depends on the edition, catalog, and destination format. ## File formats | File | Codec | Read/write | Named regions | Use and limits | | --- | --- | --- | --- | --- | | `.schem` | `schem` | Both | One | Sponge v3, used by WorldEdit. Multiple regions require flattening and acceptance of boundary loss. | | `.schem` | `schem2` | Both | One | Sponge v2. Choose this codec explicitly; the extension alone selects v3 for export. | | `.litematic` | `litematic` | Both | Multiple | Keeps region names and boundaries, including retained scheduled ticks when representable. | | `.nbt` | `nbt` | Both | One | Java structure NBT. Placement origin and schematic metadata can be lost. | | `.snbt` | `snbt` | Both | One | Text form of Java structure NBT, with the same structure limits. | | `.mcstructure` | `mcstructure` | Both | One | Bedrock structure. General Java-to-Bedrock mapping is unavailable; only supported simple Java blocks can be exported. | | `.wiki` | `blueprint` | Both | Sprite layers | Minecraft Wiki markup. Import needs an explicit Java version and can infer defaults; export omits full block states and other schematic data. | Java file import supports 1.13 and later. Some files can be retained without an available authoring catalog; operations that need that catalog can then fail. Inspect `import_diagnostics` after loading. Conversion support depends on the content of the build as well as the format. Run `check_export` for your build and target to find blocking errors and losses that need explicit acceptance. See [conversion](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/). ## Editions Java catalogs support authoring, validation, inspection, material estimates, and version conversion within the implemented data rules. Use a pinned version and read conversion reports for blocks, entities, or item data that cannot be represented at the destination. Imported Bedrock secondary layers and palette data can be retained for `.mcstructure` output, but a structure with retained secondary layers cannot be resized. Bedrock-to-Java state and entity mapping is not implemented, so `.mcstructure` support does not provide general conversion between editions. ## Language bindings | Capability | Python | Rust | Browser WASM | | --- | --- | --- | --- | | Author, edit, and validate Java blocks | Yes | Yes | Yes | | Import/export and conversion reports | Yes | Yes | Yes | | Inspect blocks and estimate materials | Yes | Yes | Yes | | Inventory and entity inspection helpers | Yes | Yes | No | | Native PNG, GLB, and sprite rendering | Yes | Yes | No | | Filesystem cache and offline provider | Yes | Yes | No; catalogs are fetched and cached in memory | Rendering uses Java 1.21.6 visual assets, including for builds from other versions. Check [rendering coverage](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/#rendering-coverage) for approximation and biome limits. Use the [Python](https://tiltedlabs-ai.github.io/mcschemora/reference/python/), [browser WASM](https://tiltedlabs-ai.github.io/mcschemora/reference/wasm/), and [Rust](https://tiltedlabs-ai.github.io/mcschemora/languages/rust/) documentation for the methods each binding exposes. --- Source: https://tiltedlabs-ai.github.io/mcschemora/reference/sources/ # Data sources MCSchemora ships some datasets with the package and downloads others when an operation needs them. See [versions and offline use](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/) for download and cache behavior. The website emblem uses the [Minecraft Wiki crafter inventory icon](https://minecraft.wiki/w/File:Invicon_Crafter.png), copied unchanged to `docs/assets/crafter.png`. Minecraft artwork belongs to Mojang and Microsoft. | Data | Delivery | Source record | | --- | --- | --- | | Version metadata and Java catalogs | Downloaded from pinned PrismarineJS data; selected registries use bundled snapshots | [Catalogs and visual assets](https://github.com/tiltedlabs-ai/mcschemora/blob/main/src/catalog/storage/native/SOURCE.md) | | Official registry snapshots | Bundled for selected versions | [Java snapshots](https://github.com/tiltedlabs-ai/mcschemora/blob/main/src/catalog/data/SOURCE.md) | | Vanilla recipes and item tags | Bundled versioned tracker from official Java server JARs | [Recipe tracker](https://github.com/tiltedlabs-ai/mcschemora/blob/main/src/catalog/recipes/SOURCE.md) | | Block models and textures for native rendering | Downloaded and prepared from pinned PrismarineJS assets | [Catalogs and visual assets](https://github.com/tiltedlabs-ai/mcschemora/blob/main/src/catalog/storage/native/SOURCE.md) | | Special block geometry | Bundled overrides from block-model-renderer | [Block models](https://github.com/tiltedlabs-ai/mcschemora/blob/main/data/block-models/SOURCE.md) | | Static entity geometry and texture bindings | Bundled adaptations of Mojang and PrismarineJS data | [Entity models](https://github.com/tiltedlabs-ai/mcschemora/blob/main/data/entity-models/SOURCE.md) | | Wiki sprite sheets | Bundled Minecraft Wiki images and metadata | [Wiki sprites](https://github.com/tiltedlabs-ai/mcschemora/blob/main/data/wiki-sprites/SOURCE.md) | | Material unit values | Bundled ProjectE EMC and EssentialsX profiles | [Valuation profiles](https://github.com/tiltedlabs-ai/mcschemora/blob/main/data/cost/java/values/SOURCE.md) | The [farm import example](https://tiltedlabs-ai.github.io/mcschemora/examples/import-farm/) uses AChromoss v0.4 by [OpenBagTwo](https://github.com/OpenBagTwo/Schematics/tree/fd78e34645f7147b7b3a1a5033239f52a4803063), based on [Chromoss by maidofmoss](https://www.youtube.com/watch?v=eNYZiuVNBe0). The third-party schematic and its derived previews are licensed under [AGPL-3.0](https://tiltedlabs-ai.github.io/mcschemora/assets/examples/imported-farm/LICENSE.txt). --- Source: https://tiltedlabs-ai.github.io/mcschemora/languages/rust/ # Rust The Rust examples run without Python and need Rust 1.88 or later. This checkout pins Rust 1.88.0 in `rust-toolchain.toml`. ## Run the example From the repository root: ```sh cargo run --example build ``` The [complete example](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/build.rs) loads a catalog, builds a floor, validates it, and writes a schematic. For a larger generated structure, see the [Eiffel Tower example](https://tiltedlabs-ai.github.io/mcschemora/examples/eiffel-tower/). Catalogs download on first use. The cache must be writable; see [catalogs and offline setup](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/#offline-use). ## Dependencies Add these dependencies to your application's `Cargo.toml`, replacing the path with the location of this checkout: ```toml [dependencies] mcschemora = { path = "/path/to/mcschemora" } pollster = "0.4" ``` Copy [examples/build.rs](https://tiltedlabs-ai.github.io/mcschemora/examples/downloads/build.rs) to your application's `src/main.rs` and run `cargo run`. The example writes `examples/output/floor.schem` relative to the working directory. ## Rendering In the example's async block, after the output directory is created, add: ```rust let assets = data.geometry_assets(&schematic.version)?; let prepared = assets.prepare(&schematic, &mcschemora::render::SceneOptions::default())?; let png = mcschemora::render::png::encode(&prepared, &mcschemora::render::png::Options::default())?; fs::write(output.join("floor.png"), png)?; println!("Visual diagnostics: {:?}", prepared.diagnostics); ``` Geometry preparation downloads visual assets on first use. Inspect its diagnostics for approximations and check the [rendering coverage](https://tiltedlabs-ai.github.io/mcschemora/sdk/minecraft-data/#rendering-coverage). Build the Rust API reference locally with `cargo doc -p mcschemora --no-deps --open`. ## Complete example ```rust use mcschemora::{ catalog::MinecraftData, formats, model::{Block, Bounds, Schematic, Selection}, }; use std::{error::Error, fs, path::Path, sync::Arc}; fn main() -> Result<(), Box> { pollster::block_on(async { let data = Arc::new(MinecraftData::new(None, false)?); data.load("1.21.1").await?; let mut schematic = Schematic::new("java", "1.21.1", data.clone())?; let floor = Selection::new( schematic.region("main")?, Bounds::new([0, 0, 0], [7, 1, 7])?, ); schematic.fill("main", &floor, &Block::parse("stone_bricks")?)?; println!("Validation: {:?}", schematic.validate()); let output = Path::new("examples/output"); fs::create_dir_all(output)?; fs::write( output.join("floor.schem"), formats::encode(&schematic, "schem", None, false, false).await?, )?; println!("Saved floor.schem"); Ok(()) }) } ``` --- Source: https://tiltedlabs-ai.github.io/mcschemora/languages/wasm/ # Browser WASM The WASM bindings let a browser application build, validate, and convert schematics. Each `MinecraftData` instance fetches catalogs on demand and keeps them in memory. The native filesystem cache and PNG/GLB rendering are unavailable in the browser. ## Build With Rust and npm installed, run from the repository root: ```sh rustup target add wasm32-unknown-unknown cargo install wasm-bindgen-cli --version 0.2.129 --locked npm --prefix bindings/wasm run build ``` The build writes JavaScript, WebAssembly, and TypeScript declarations to `bindings/wasm/pkg/`. ## Create a schematic Import the generated module from your browser application. Adjust the import path to match where you serve `bindings/wasm/pkg/`: ```javascript import init, { MinecraftData } from "./pkg/mcschemora.js"; await init(); const data = new MinecraftData(); try { const schematic = await data.create("1.21.1"); try { schematic.setBlock("main", 0, 0, 0, "minecraft:stone_bricks"); console.log(schematic.getBlock("main", 0, 0, 0)); console.log(schematic.validate().errors); const bytes = await schematic.toBytes("schem", false, false); const file = new Blob([bytes], { type: "application/octet-stream" }); console.log(file.size > 0); } finally { schematic.free(); } } finally { data.free(); } ``` ```text minecraft:stone_bricks [] true ``` ## File import Pass file bytes and a codec name to `fromBytes()`. For ordinary file import, pass `undefined` as the options argument: ```javascript const schematic = await data.fromBytes(new Uint8Array(buffer), "litematic", undefined); try { console.log(schematic.version); } finally { schematic.free(); } ``` Here the `ArrayBuffer` comes from your application's file input, and the `MinecraftData` instance must stay live while loading. For blueprint imports, provide an explicit version in the options object. The [API reference](https://tiltedlabs-ai.github.io/mcschemora/reference/wasm/) lists methods and arguments, and the [conversion guide](https://tiltedlabs-ai.github.io/mcschemora/sdk/conversion/#export-reports) explains export reports. --- Source: https://tiltedlabs-ai.github.io/mcschemora/contributing/ # Contributing Library changes, examples, and data updates use the repository checkout. If you are only editing documentation, you can skip the Rust build and follow the website setup below. ## Setup Install [uv](https://docs.astral.sh/uv/) and [Rust](https://rustup.rs/), then run: ```sh git clone https://github.com/tiltedlabs-ai/mcschemora.git cd mcschemora make setup ``` The checkout pins Python 3.12 and Rust 1.88.0. `make setup` installs the Python package in editable mode. Changes to the Python facade take effect immediately. After changing Rust code, rebuild the extension with `make rebuild`. ## Repository layout | Area | Location | | --- | --- | | Python public API and type stubs | `bindings/python/python/mcschemora/` | | Native Python bindings | `bindings/python/src/` | | Rust implementation | `src/` | | Browser bindings | `bindings/wasm/` | | Runnable examples | `examples/` | | Documentation | `docs/` | | Data import and verification scripts | `scripts/` | Keep public signatures, type stubs, docstrings, and examples consistent when changing an API. Fix every caller affected by the change. ## Checks ```sh make lint make verify ``` `make lint` checks Rust formatting and Clippy, plus Python formatting and Ruff. `make verify` checks the installed package, fresh-cache preparation, offline use, and the conversion corpus. It downloads pinned catalogs. For textured rendering, also run: ```sh uv run --locked scripts/verify_package.py --visuals ``` To build and check distributions, use `make build` and `make check-dist`. Install the resulting wheel into a clean environment outside the checkout and run the relevant examples there. ## Documentation Install uv and Python 3.12, then run from the checkout: ```sh make docs-serve ``` Open `http://localhost:8000`. The command installs the docs dependency group, publishes example source downloads, and starts Zensical. Stop it with Ctrl+C. Use `make docs-build` to write the static site into `site/`. Example code blocks include files from `examples/`, so edit the source file to change the code readers see. During a running preview, rerun `make docs-prepare` after editing an example to refresh its download. Regenerate published artifacts in `docs/assets/examples/` with the script's default parameters, and check its diagnostics before replacing an image or schematic. Preparation also generates `docs/llms.txt` from the Markdown pages in `zensical.toml` navigation order. It expands source snippets, removes frontmatter and layout wrappers, and turns relative links into website URLs. This generated file is ignored by Git and copied into the site. To update it during a preview, edit the original pages or scripts and run `make docs-prepare`. `make docs-build` refreshes it before each build, and `make docs-serve` refreshes it at startup. The API reference has a separate generation command below. The documentation workflow builds pull requests and deploys pushes to `main` on GitHub Pages. For initial setup, choose **GitHub Actions** as the repository's Pages publishing source. Example changes also trigger that workflow. ## API reference Python reference pages come from signatures and docstrings. The browser reference comes from wasm-bindgen declarations. Install the [browser build prerequisites](https://tiltedlabs-ai.github.io/mcschemora/languages/wasm/#build), then run: ```sh make docs make docs-check ``` Commit the generated Markdown with the code change. A normal website build uses those checked-in pages and does not compile the package or WASM. ## Data sources Keep source records and notices with imported data. The [source overview](https://tiltedlabs-ai.github.io/mcschemora/reference/sources/) links to the pinned revisions, regeneration commands, and asset terms. Regenerate affected outputs and check that the package still includes its attribution files. Open an [issue](https://github.com/tiltedlabs-ai/mcschemora/issues) for a bug or proposed change, or submit a [pull request](https://github.com/tiltedlabs-ai/mcschemora/pulls) with the change and the checks you ran. ## Pull requests and release notes The PR template is copied unchanged from [Steve Mao's simple template](https://github.com/stevemao/github-issue-templates/blob/master/simple/PULL_REQUEST_TEMPLATE.md), whose author has [waived copyright](https://github.com/stevemao/github-issue-templates/blob/master/LICENSE.md). GitHub fills new PR descriptions from it once it is merged into the default branch. The release-note configuration in `.github/release.yml` uses [GitHub's documented example](https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes). When drafting a release, choose the tag and click **Generate release notes**. PRs labeled `dependencies` appear separately; other PRs appear under Features. Review the generated notes before publishing. For the first release, add a description of the initial features even if there are no merged PRs to list.