Scan and render#

Render a region of a Minecraft world to an image, so that you (or an AI agent) can see what a build looks like without joining the game.

First read the blocks with scan(), then draw them with render():

from mciwb.imports import Iwb, Vec3, Volume, get_client, render, scan

world = Iwb()
vol = Volume.from_corners(Vec3(0, 64, 0), Vec3(31, 90, 31))
grid = scan(vol, world.world_folder, get_client())
render(grid, views=["top", "iso", "south"]).save("build.png")

scan() and render() do the same in one call each: world.render(Vec3(0, 64, 0), Vec3(31, 90, 31), "build.png").

The views are:

  • top: a plan, north up, showing the highest block of each column. Higher blocks are lighter, and a block higher than its northern neighbour has a light edge (a lower one a dark edge).

  • north, south, east, west: elevations, the region seen from that side, e.g. south looks north at the south face. Nearer blocks are lighter.

  • iso: a 3D isometric view from the south east, with shaded faces. iso_ne, iso_nw and iso_sw look from the other corners.

Translucent blocks (glass, water, ice) and small ones (torches, flowers, fences) let the blocks behind them show through. Empty space is a pale sky blue, unlike any common block. Each view has axis labels with world coordinates, unless you ask for none.

Each block is drawn in one flat colour, from a Palette.

mciwb.render.scan

Read the blocks in a region of the world, by the fastest means available.

mciwb.render.render

Draw one or more views of a region side by side in one image.

mciwb.render.render_view

Draw one view of a region.

mciwb.render.auto_scale

Choose the pixels per block that make a view about 512 pixels across.

BlockGrid

The blocks of a cuboid region of the world.

Palette

The colour that each block is drawn in by mciwb.render.render().

set_colour

Set the colour of a block for every render in this process.

Reading and drawing#

mciwb.render.scan(vol, world_folder=None, client=None, dimension='overworld', max_rcon_blocks=MAX_RCON_BLOCKS)[source]#

Read the blocks in a region of the world, by the fastest means available.

If world_folder is a world (it contains level.dat), its region files are read directly with read_world_blocks(), after asking the server (if client is given) to save its changes to disk. Otherwise the blocks are read over RCON with client, one at a time, with grab_blocks().

Parameters:
  • vol (Volume) -- The region to read.

  • world_folder (Path | None) -- The server’s world folder, for example ~/mciwb-server/world for the server of mciwb start. It must be on this machine.

  • client (Client | None) -- An RCON client for the running server, see get_client().

  • dimension (str) -- "overworld", "the_nether" or "the_end". Only used when reading the world files.

  • max_rcon_blocks (int) -- Refuse to read regions of more blocks than this over RCON. Defaults to MAX_RCON_BLOCKS.

Returns:

The blocks of the region.

Raises:

ValueError -- If there is no world in world_folder and no client, or the region is too large to read over RCON, or the world files cannot be read (see read_world_blocks()).

Return type:

BlockGrid

Example:

from pathlib import Path

from mciwb.imports import Vec3, Volume, scan

# a stopped server: read its files, with no client
vol = Volume.from_corners(Vec3(0, 64, 0), Vec3(31, 90, 31))
grid = scan(vol, Path.home() / "mciwb-server" / "world")
print(grid.counts())
mciwb.render.render(grid, views=('top', 'iso'), scale=None, labels=True, palette=None)[source]#

Draw one or more views of a region side by side in one image.

The views are:

  • top: a plan, north up, showing the highest block of each column. Higher blocks are lighter, and a block higher than its northern neighbour has a light edge (a lower one a dark edge).

  • north, south, east, west: elevations, the region seen from that side: south looks north at the south face. Nearer blocks are lighter.

  • iso: a 3D isometric view from the south east, with shaded faces. iso_ne, iso_nw and iso_sw look from the other corners.

Up to three views go in one row, four make two rows of two, and more make rows of three.

Parameters:
  • grid (BlockGrid) -- The blocks, from scan() or scan().

  • views (Sequence[str]) -- The views to draw: names from VIEWS, or the name of one view.

  • scale (int | None) -- Pixels per block for every view. By default each view gets its own scale (see auto_scale()), chosen to make it about 512 pixels across, or smaller if needed to keep the image no more than 1500 pixels wide.

  • labels (bool) -- Add a header with the region’s coordinates and size, and give each view a title, axis labels and grid lines with world coordinates.

  • palette (Palette | None) -- The block colours. Defaults to default_palette.

Returns:

A Pillow image. Call its save("file.png") method to save it.

Raises:

ValueError -- If views is empty or has a name that is not in VIEWS, or scale is less than 1.

Return type:

Image

Example:

from mciwb import Palette
from mciwb.imports import render

# grid is from scan. Draw gold blocks in a brighter yellow
palette = Palette({"gold_block": (255, 215, 0)})
image = render(grid, ["iso", "iso_nw"], labels=False, palette=palette)
image.save("build.png")
mciwb.render.render_view(grid, view, scale=None, labels=True, palette=None)[source]#

Draw one view of a region.

Parameters:
Returns:

A Pillow image of the view.

Raises:

ValueError -- If view is not one of VIEWS, or scale is less than 1.

Return type:

Image

Example:

from mciwb.render import render_view

render_view(grid, "south", scale=8).save("south.png")
mciwb.render.auto_scale(grid, view=None)[source]#

Choose the pixels per block that make a view about 512 pixels across.

Parameters:
  • grid (BlockGrid) -- The blocks to be drawn.

  • view (str | None) -- The name of the view, one of VIEWS. If None, the scale suits every view of the region.

Returns:

The largest whole number of pixels per block, from 1 to 16, that keeps the view (without its labels) within 512 pixels in width and height. A view of more than 512 blocks gets 1, so is larger.

Raises:

ValueError -- If view is not one of VIEWS.

Return type:

int

>>> import numpy as np
>>> from mciwb.imports import BlockGrid, Vec3
>>> ids = np.zeros((32, 8, 32), dtype=int)
>>> grid = BlockGrid(Vec3(0, 64, 0), ids, ["minecraft:stone"])
>>> auto_scale(grid, "top")
16
>>> auto_scale(grid, "iso")
8
>>> auto_scale(grid)
8
mciwb.render.VIEWS = ('top', 'south', 'north', 'east', 'west', 'iso', 'iso_se', 'iso_ne', 'iso_nw', 'iso_sw')#

The names of the views that render() can draw. "iso_se" is another name for "iso".

mciwb.render.MAX_RCON_BLOCKS = 32768#

The largest region, in blocks, that scan() reads over RCON by default: reading is one block at a time, so this takes minutes.

Block grids#

A compact 3D array of the blocks in a cuboid region of a Minecraft world.

BlockGrid is what the readers return (read_world_blocks() reads the world’s region files, grab_blocks() asks the server over RCON) and what mciwb.render.render() draws.

class mciwb.BlockGrid(origin, ids, names)[source]#

The blocks of a cuboid region of the world.

Each block is stored as an index into a list of block names, which keeps large regions small and makes per-block lookups (such as colours) cheap. Only block names are held, not block states: stairs do not know which way they face.

A grid usually comes from scan() or mciwb.render.scan(). To make one directly, pass the three fields below in order, or use from_blocks().

Index a grid with a world position to get the name of the block there: grid[Vec3(10, 64, 21)]. A position outside the region raises IndexError.

Raises:

ValueError -- If ids is not a 3 dimensional array.

>>> from mciwb.imports import BlockGrid, Vec3
>>> grid = BlockGrid.from_blocks([[["stone", "air"]]], Vec3(10, 64, 20))
>>> grid[Vec3(10, 64, 21)]
'minecraft:air'
>>> grid.end
Vec3(x=10, y=64, z=21)
>>> grid.counts()
{'minecraft:stone': 1}
origin: Vec3#

The world position of the block at index [0][0][0], which is the lowest (north west bottom) corner of the region. It is rounded down to whole blocks.

ids: ndarray#

An integer array of shape (size x, size y, size z), indexed ids[x][y][z] like a Cuboid. Each value is an index into names.

names: list[str]#

The namespaced block id for each index in ids, for example "minecraft:stone".

classmethod from_blocks(blocks, origin)[source]#

Make a grid from a 3D array of blocks.

Parameters:
  • blocks (Iterable) -- A nested list or numpy array, indexed [x][y][z], of block names or Item: for example the cuboid that grab() returns. Each entry is normalised with block_name().

  • origin (Vec3) -- The world position of blocks[0][0][0].

Returns:

The new grid.

Raises:

ValueError -- If blocks is not 3 dimensional, for example because its rows differ in length.

Return type:

BlockGrid

Example:

from mciwb.imports import BlockGrid, Item, Vec3

# one block wide (x), two high (y), one deep (z)
column = [[[Item.STONE], [Item.OAK_PLANKS]]]
grid = BlockGrid.from_blocks(column, Vec3(0, 64, 0))
property size: Vec3#

The size of the region in blocks, as (x, y, z).

property end: Vec3#

The world position of the highest (south east top) corner block.

property volume: Volume#

The region as a Volume.

counts(include_air=False)[source]#

Count the blocks of each type.

This is a quick way to check that a build contains what it should.

Parameters:

include_air (bool) -- Also count air. By default every block whose name ends in air (air, cave air and void air) is left out.

Returns:

The number of blocks for each namespaced block id that is in the region, most common first.

Return type:

dict[str, int]

Example:

grid = world.scan(Vec3(0, 64, 0), Vec3(9, 70, 9))
print(grid.counts())  # {'minecraft:stone_bricks': 240, ...}
to_names()[source]#

Expand the grid into an array of block names.

Returns:

A 3D numpy array of namespaced block ids, indexed [x][y][z] and the same shape as ids.

Return type:

ndarray

mciwb.blockgrid.grab_blocks(client, vol)[source]#

Read a region of the world one block at a time over RCON.

This works with any server, local or remote, but makes one RCON command per block: use read_world_blocks() for regions of more than a few thousand blocks when the world’s files are on this machine. mciwb.render.scan() chooses between the two for you.

Parameters:
Returns:

The blocks of the region, with vol’s start as the origin.

Return type:

BlockGrid

Example:

from mciwb.blockgrid import grab_blocks
from mciwb.imports import Vec3, Volume, get_client

vol = Volume.from_corners(Vec3(0, 64, 0), Vec3(4, 68, 4))
grid = grab_blocks(get_client(), vol)
mciwb.blockgrid.block_name(name)[source]#

Normalise a block name to its namespaced id, without block states.

Parameters:

name (object) -- A block, as an Item or as text. Any block states ([...]) or NBT data ({...}) after the name are dropped.

Returns:

The block id with its namespace. minecraft: is added to a name that has none.

Return type:

str

>>> from mciwb.imports import Item
>>> block_name(Item.STONE)
'minecraft:stone'
>>> block_name("stone")
'minecraft:stone'
>>> block_name("minecraft:oak_stairs[facing=east]")
'minecraft:oak_stairs'

Colours#

Colours for rendering blocks: a map from block name to an RGBA colour.

mciwb does not ship Minecraft’s textures. Instead each block gets a single colour, close to the average colour of its texture, from:

  1. a curated table of common blocks (BLOCK_COLOURS),

  2. rules for families of blocks: the 16 dye colours (red_wool, blue_concrete, lime_stained_glass …), the wood types (spruce_planks, cherry_log, birch_leaves …), shapes made from another block (stone_brick_stairs is coloured like stone_bricks), ores, and waxed or weathered copper,

  3. keywords in the name (glass, sapling, coral …),

  4. otherwise a muted colour made from a hash of the name, so that unknown blocks (e.g. from mods) still differ from each other.

The alpha channel says how much light a block stops: 0 for air, 255 for a solid block. Translucent blocks such as glass and water, and small blocks such as torches, flowers and fences, are partly transparent, so the blocks behind them show through.

Add or change colours for one render with a Palette, or for every render with set_colour():

from mciwb.palette import set_colour
set_colour("minecraft:gold_block", (255, 215, 0))
class mciwb.Palette(colours=None)[source]#

The colour that each block is drawn in by mciwb.render.render().

mciwb does not ship Minecraft’s textures. Each block gets one colour, close to the average colour of its texture, from the first of these that knows the block:

  1. the colours given to this palette,

  2. a curated table of common blocks (BLOCK_COLOURS),

  3. rules for families of blocks: the 16 dye colours (red_wool, blue_concrete, lime_stained_glass), the wood types (spruce_planks, cherry_log, birch_leaves), shapes made from another block (stone_brick_stairs is coloured like stone_bricks), ores, and waxed or weathered copper,

  4. keywords in the name (glass, sapling, coral),

  5. a muted colour made from a hash of the name, so that unknown blocks (from mods, say) still differ from each other.

The alpha value says how much light a block stops: 0 for air and the other blocks that are never drawn, 255 for a solid block. Translucent blocks such as glass (80) and water (150), and small blocks such as torches, flowers and fences (170), are partly transparent, so the blocks behind them show through.

Pass a palette to mciwb.render.render() to use it for one render. To change a colour for every render, use set_colour().

Parameters:

colours (Mapping[str, tuple[int, int, int] | tuple[int, int, int, int]] | None) -- Colours that take precedence over the defaults, keyed by block name (with or without the minecraft: namespace), as (r, g, b) or (r, g, b, a) with values from 0 to 255.

Raises:

ValueError -- If a colour is not 3 or 4 values from 0 to 255.

>>> palette = Palette({"gold_block": (255, 215, 0)})
>>> palette.colour("minecraft:gold_block")
(255, 215, 0, 255)
>>> palette.colour("minecraft:stone")
(125, 125, 125, 255)
>>> palette.colour("glass")
(200, 220, 230, 80)
set(name, colour)[source]#

Set the colour of a block in this palette.

Shapes made from the block follow it: setting "stone_bricks" also colours stone_brick_stairs and stone_brick_slab.

Parameters:
  • name (str) -- The block name, with or without the namespace: "minecraft:stone" or "stone".

  • colour (tuple[int, int, int] | tuple[int, int, int, int]) -- (r, g, b) or (r, g, b, a), with values from 0 to 255. Without an alpha the block is solid (255).

Raises:

ValueError -- If colour is not 3 or 4 values from 0 to 255.

colour(name)[source]#

Return the colour of a block.

Parameters:

name (str) -- The block name, with or without the namespace, such as "minecraft:red_wool". Any block states, such as [facing=north], are ignored.

Returns:

(r, g, b, a) with values from 0 to 255. The alpha is 0 for blocks that are not drawn, and 255 for solid blocks.

Return type:

tuple[int, int, int, int]

mciwb.palette.set_colour(name, colour)[source]#

Set the colour of a block for every render in this process.

This changes default_palette, which is used by every render that is not given a Palette of its own.

Parameters:
  • name (str) -- The block name, with or without the namespace: "minecraft:stone" or "stone".

  • colour (tuple[int, int, int] | tuple[int, int, int, int]) -- (r, g, b) or (r, g, b, a), with values from 0 to 255. Without an alpha the block is solid (255).

Raises:

ValueError -- If colour is not 3 or 4 values from 0 to 255.

Example:

from mciwb.palette import set_colour

set_colour("minecraft:gold_block", (255, 215, 0))
world.render(Vec3(0, 64, 0), Vec3(9, 75, 9), "gold.png")
mciwb.palette.default_palette#

The Palette that mciwb.render.render() uses when it is not given one. Change its colours with set_colour().

mciwb.palette.BLOCK_COLOURS: dict[str, tuple[int, int, int] | tuple[int, int, int, int]]#

The curated colours of about 250 common blocks, close to the average colour of each block’s texture. The keys are block names without the minecraft: namespace, such as "stone". The values are (r, g, b) or (r, g, b, a) tuples of 0 to 255: alpha is 255 (solid) when it is left out. To change a colour, use set_colour() or a Palette.

World files#

Read blocks straight from the region (.mca) files of a Minecraft world.

This is much faster than asking the server for one block at a time over RCON (see grab_blocks()): it needs the world folder to be on this machine, as it is for the server that mciwb start runs. A running server keeps recent changes in memory, so ask it to write them out first with save-all flush (mciwb.render.scan() does this for you).

The readers here are small, read-only and use numpy for the bulky parts. They support the chunk format of Minecraft 1.18 and later, including the dimensions/<namespace>/<name> world layout of Minecraft 26.1 and later. See https://minecraft.wiki/w/Region_file_format and https://minecraft.wiki/w/Chunk_format.

mciwb.anvil.read_world_blocks(world_folder, vol, dimension='overworld')[source]#

Read a region of a world from its region files.

Chunks that have not been generated read as air, with a warning in the log. Block states (such as which way stairs face) are not read, just the block names.

The files hold what the server last saved: for a running server, use mciwb.render.scan(), which asks it to save first.

Parameters:
  • world_folder (Path) -- The world folder (containing level.dat).

  • vol (Volume) -- The region to read.

  • dimension (str) -- "overworld", "the_nether" or "the_end".

Returns:

The blocks of the region, with vol’s start as the origin.

Raises:

ValueError -- If the world folder has no region files for dimension, or they are in a format that this reader does not support: chunks from before Minecraft 1.18, or LZ4 compression.

Return type:

BlockGrid

Example:

from pathlib import Path

from mciwb.anvil import read_world_blocks
from mciwb.imports import Vec3, Volume

vol = Volume.from_corners(Vec3(0, 64, 0), Vec3(31, 90, 31))
grid = read_world_blocks(Path.home() / "mciwb-server" / "world", vol)
mciwb.anvil.region_folder(world_folder, dimension='overworld')[source]#

Find the folder of a dimension’s region files in a world folder.

The layout of Minecraft 26.1 and later (dimensions/minecraft/<dimension>/region) is tried first, then the older one (region, DIM-1/region and DIM1/region).

Parameters:
  • world_folder (Path) -- The world folder (containing level.dat).

  • dimension (str) -- "overworld", "the_nether" or "the_end".

Returns:

The folder that holds the dimension’s .mca files.

Raises:

ValueError -- If dimension is not one of those three, or the world folder has no region folder for it.

Return type:

Path

class mciwb.anvil.RegionFile(path)[source]#

One region (.mca) file: the chunks of a 32 x 32 chunk area.

The whole file is read into memory when the object is made. A file that does not exist is treated as a region with no chunks.

Parameters:

path (Path) -- The path of the file, r.<region x>.<region z>.mca, where the region coordinates are the chunk coordinates divided by 32, rounded down.

Example:

from pathlib import Path

from mciwb.anvil import RegionFile, region_folder

folder = region_folder(Path.home() / "mciwb-server" / "world")
# the chunk that holds the block at x=40, z=-20
chunk = RegionFile(folder / "r.0.-1.mca").chunk(40 // 16, -20 // 16)
path#

The path of the region file.

data#

The bytes of the file, empty if the file does not exist.

chunk(cx, cz)[source]#

Read the NBT data of one chunk.

Parameters:
  • cx (int) -- The chunk’s x coordinate in the world (block x // 16). It must be a chunk of this region: only its position within the region is used.

  • cz (int) -- The chunk’s z coordinate in the world (block z // 16).

Returns:

The chunk’s NBT as decoded by read_nbt(), or None if the chunk has not been generated.

Raises:

ValueError -- If the chunk is compressed with LZ4 (the region-file-compression=lz4 server property), which is not supported.

Return type:

dict[str, Any] | None

mciwb.anvil.read_nbt(data)[source]#

Decode uncompressed binary NBT into Python objects.

Compounds become dicts, lists become lists, byte, int and long arrays become numpy arrays, and numbers and strings become int, float and str.

This is the small reader that chunks are read with. It differs from mciwb.builders.nbtfile.read_nbt(), which also reads gzip compressed data, keeps the NBT type of each value so that the data can be written back, and returns (name, value): this one drops the name of the root tag and returns the value alone.

Parameters:

data (bytes) -- The NBT document, not compressed. Its root must be a compound.

Returns:

The value of the root compound.

Raises:

ValueError -- If the root is not a compound, or the data has an unknown tag type.

Return type:

dict[str, Any]