litematica-render 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
litematic/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """litematic - read-only parser for Minecraft Litematica .litematic schematics.
2
+
3
+ Instances are not thread-safe: parse and query a Litematic from a single
4
+ thread or asyncio task at a time.
5
+ """
6
+
7
+ from litematic.parse.errors import LitematicError, LitematicFormatError, NbtError
8
+ from litematic.parse.model import (
9
+ BlockEntity,
10
+ BlockState,
11
+ Entity,
12
+ Litematic,
13
+ LitematicMetadata,
14
+ Region,
15
+ Vec3i,
16
+ )
17
+ from litematic.parse.parser import load, loads
18
+
19
+ __version__ = "0.1.0"
20
+
21
+ __all__ = [
22
+ "BlockEntity",
23
+ "BlockState",
24
+ "Entity",
25
+ "Litematic",
26
+ "LitematicError",
27
+ "LitematicFormatError",
28
+ "LitematicMetadata",
29
+ "NbtError",
30
+ "Region",
31
+ "Vec3i",
32
+ "load",
33
+ "loads",
34
+ ]
@@ -0,0 +1 @@
1
+ """Parsing core: NBT reading, data model, and .litematic decoding."""
@@ -0,0 +1,13 @@
1
+ """Public exception tree for litematic."""
2
+
3
+
4
+ class LitematicError(Exception):
5
+ """Base class for all exceptions raised by this library."""
6
+
7
+
8
+ class NbtError(LitematicError):
9
+ """Input is not valid Java NBT: bad tag type, truncated stream, bad compression."""
10
+
11
+
12
+ class LitematicFormatError(LitematicError):
13
+ """Input is valid NBT but violates the .litematic structure constraints."""
@@ -0,0 +1,225 @@
1
+ """Read-only data model: metadata, block states, and lazily materialized regions."""
2
+
3
+ from dataclasses import dataclass, field
4
+ from types import MappingProxyType
5
+ from typing import Callable, Mapping, NamedTuple, Optional, Sequence
6
+
7
+ import numpy as np
8
+
9
+
10
+ class Vec3i(NamedTuple):
11
+ """A 3D integer vector (x, y, z)."""
12
+
13
+ x: int
14
+ y: int
15
+ z: int
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class BlockState:
20
+ """A palette entry: block id plus blockstate properties."""
21
+
22
+ name: str
23
+ properties: Mapping[str, str] = field(default_factory=dict)
24
+
25
+ def __post_init__(self) -> None:
26
+ object.__setattr__(
27
+ self, "properties", MappingProxyType(dict(self.properties))
28
+ )
29
+
30
+ def __hash__(self) -> int:
31
+ return hash((self.name, frozenset(self.properties.items())))
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class LitematicMetadata:
36
+ """Schematic-level metadata from the Metadata compound."""
37
+
38
+ name: str
39
+ author: str
40
+ description: str
41
+ enclosing_size: Vec3i
42
+ total_blocks: int
43
+ total_volume: int
44
+ time_created: int
45
+ time_modified: int
46
+ MinecraftDataVersion: int
47
+ LitematicVersion: int
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class BlockEntity:
52
+ """A tile entity: position, id, and its raw NBT payload as a plain mapping.
53
+
54
+ The mapping is read-only at the top level only; nested compounds
55
+ (a chest's items, for example) stay mutable dicts.
56
+ """
57
+
58
+ pos: tuple[int, int, int]
59
+ id: str
60
+ data: Mapping[str, object]
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Entity:
65
+ """An entity: id, position, and its raw NBT payload as a plain mapping.
66
+
67
+ The mapping is read-only at the top level only; nested compounds
68
+ stay mutable dicts.
69
+ """
70
+
71
+ id: str
72
+ pos: tuple[float, float, float]
73
+ data: Mapping[str, object]
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class Litematic:
78
+ """A parsed schematic: metadata plus named regions.
79
+
80
+ `regions` is exposed as a read-only mapping.
81
+ """
82
+
83
+ metadata: LitematicMetadata
84
+ regions: Mapping[str, "Region"]
85
+
86
+ def __post_init__(self) -> None:
87
+ object.__setattr__(self, "regions", MappingProxyType(self.regions))
88
+
89
+
90
+ class Region:
91
+ """One schematic region.
92
+
93
+ Block data is kept in packed form; `block_indices` materializes it on
94
+ first access and caches the result until `release()`.
95
+ `pending_block_ticks`/`pending_fluid_ticks` are sequences of scheduled-tick
96
+ compounds ({x, y, z, Time, Priority, Block or Fluid, SubTick}), retained
97
+ verbatim (semantics defined by the writing Litematica version).
98
+ Not thread-safe.
99
+ """
100
+
101
+ def __init__(
102
+ self,
103
+ name: str,
104
+ position: Vec3i,
105
+ size: Vec3i,
106
+ palette: Sequence[BlockState],
107
+ block_entities: tuple[BlockEntity, ...],
108
+ entities: tuple[Entity, ...],
109
+ pending_block_ticks: Optional[tuple[Mapping[str, object], ...]],
110
+ pending_fluid_ticks: Optional[tuple[Mapping[str, object], ...]],
111
+ packed_indices: np.ndarray,
112
+ _unpack: Callable[[], np.ndarray],
113
+ _unpack_slab: Optional[Callable[[int, int], np.ndarray]] = None,
114
+ ) -> None:
115
+ self._name = name
116
+ self._position = position
117
+ self._size = size
118
+ self._palette = tuple(palette)
119
+ self._block_entities = block_entities
120
+ self._entities = entities
121
+ self._pending_block_ticks = pending_block_ticks
122
+ self._pending_fluid_ticks = pending_fluid_ticks
123
+ # Read-only view: the caller keeps ownership of the array it passed.
124
+ packed = packed_indices.view()
125
+ packed.flags.writeable = False
126
+ self._packed_indices = packed
127
+ self._unpack = _unpack
128
+ self._unpack_slab = _unpack_slab
129
+ self._indices: Optional[np.ndarray] = None
130
+
131
+ @property
132
+ def name(self) -> str:
133
+ """Region name as written in the file."""
134
+ return self._name
135
+
136
+ @property
137
+ def position(self) -> Vec3i:
138
+ """Min corner in schematic coordinates (negative sizes normalized)."""
139
+ return self._position
140
+
141
+ @property
142
+ def size(self) -> Vec3i:
143
+ """Region extents along x, y, z; always positive."""
144
+ return self._size
145
+
146
+ @property
147
+ def palette(self) -> tuple[BlockState, ...]:
148
+ """Block states addressable by the values in `block_indices`."""
149
+ return self._palette
150
+
151
+ @property
152
+ def block_entities(self) -> tuple[BlockEntity, ...]:
153
+ """Tile entities (chests, signs, spawners, ...) in this region."""
154
+ return self._block_entities
155
+
156
+ @property
157
+ def entities(self) -> tuple[Entity, ...]:
158
+ """Entities (mobs, items, item frames, ...) in this region."""
159
+ return self._entities
160
+
161
+ @property
162
+ def pending_block_ticks(self) -> Optional[tuple[Mapping[str, object], ...]]:
163
+ """Scheduled block ticks, one compound per tick; None if absent."""
164
+ return self._pending_block_ticks
165
+
166
+ @property
167
+ def pending_fluid_ticks(self) -> Optional[tuple[Mapping[str, object], ...]]:
168
+ """Scheduled fluid ticks, one compound per tick; None if absent."""
169
+ return self._pending_fluid_ticks
170
+
171
+ @property
172
+ def packed_indices(self) -> np.ndarray:
173
+ """The raw packed BlockStates long array, read-only."""
174
+ return self._packed_indices
175
+
176
+ @property
177
+ def is_unpacked(self) -> bool:
178
+ """Whether `block_indices` is currently materialized."""
179
+ return self._indices is not None
180
+
181
+ @property
182
+ def block_indices(self) -> np.ndarray:
183
+ """Palette indices as a read-only (x, y, z) array; materializes lazily."""
184
+ if self._indices is None:
185
+ indices = self._unpack()
186
+ indices.flags.writeable = False
187
+ self._indices = indices
188
+ return self._indices
189
+
190
+ def slab_indices(self, y0: int, y1: int) -> np.ndarray:
191
+ """Palette indices for rows [y0, y1), shape (x, y1-y0, z); not cached.
192
+
193
+ Unpacks only the slab's contiguous entry span of the packed stream
194
+ when the parser injected a slab unpacker, so callers can stream a
195
+ region without ever materializing `block_indices`.
196
+ """
197
+ if not (0 <= y0 < y1 <= self._size.y):
198
+ raise IndexError(
199
+ f"Slab rows out of range: [{y0}, {y1}) for size {self._size}"
200
+ )
201
+ if self._unpack_slab is not None:
202
+ arr = self._unpack_slab(y0, y1)
203
+ else:
204
+ arr = np.ascontiguousarray(self.block_indices[:, y0:y1, :])
205
+ arr.flags.writeable = False
206
+ return arr
207
+
208
+ def get_block(self, x: int, y: int, z: int) -> BlockState:
209
+ """Return the block state at local coordinates (x, y, z).
210
+
211
+ Out-of-range coordinates are a caller bug and raise IndexError;
212
+ file corruption raises LitematicFormatError on first unpack.
213
+ """
214
+ size_x, size_y, size_z = self._size
215
+ if not (0 <= x < size_x and 0 <= y < size_y and 0 <= z < size_z):
216
+ raise IndexError(
217
+ f"Block coordinates out of range: ({x}, {y}, {z})"
218
+ f" for size {self._size}"
219
+ )
220
+ index = int(self.block_indices[x, y, z])
221
+ return self._palette[index]
222
+
223
+ def release(self) -> None:
224
+ """Drop the materialized `block_indices` cache to reclaim memory."""
225
+ self._indices = None
litematic/parse/nbt.py ADDED
@@ -0,0 +1,167 @@
1
+ """Minimal Java NBT reader: streaming gzip, big-endian, arrays decoded to numpy."""
2
+
3
+ import gzip
4
+ import io
5
+ import struct
6
+ import zlib
7
+ from typing import Protocol
8
+
9
+ import numpy as np
10
+
11
+ from litematic.parse.errors import NbtError
12
+
13
+ _GZIP_MAGIC = b"\x1f\x8b"
14
+
15
+ # 256 levels is far beyond any real schematic and costs 2 stack frames per
16
+ # level, staying safely under CPython's default recursion limit of 1000
17
+ _MAX_DEPTH = 256
18
+
19
+ _TAG_END = 0
20
+ _TAG_BYTE = 1
21
+ _TAG_SHORT = 2
22
+ _TAG_INT = 3
23
+ _TAG_LONG = 4
24
+ _TAG_FLOAT = 5
25
+ _TAG_DOUBLE = 6
26
+ _TAG_BYTE_ARRAY = 7
27
+ _TAG_STRING = 8
28
+ _TAG_LIST = 9
29
+ _TAG_COMPOUND = 10
30
+ _TAG_INT_ARRAY = 11
31
+ _TAG_LONG_ARRAY = 12
32
+
33
+ _ARRAY_DTYPES = {
34
+ _TAG_BYTE_ARRAY: (">i1", 1, np.int8),
35
+ _TAG_INT_ARRAY: (">i4", 4, np.int32),
36
+ _TAG_LONG_ARRAY: (">i8", 8, np.int64),
37
+ }
38
+
39
+ _SCALARS = {
40
+ _TAG_BYTE: (">b", 1),
41
+ _TAG_SHORT: (">h", 2),
42
+ _TAG_INT: (">i", 4),
43
+ _TAG_LONG: (">q", 8),
44
+ _TAG_FLOAT: (">f", 4),
45
+ _TAG_DOUBLE: (">d", 8),
46
+ }
47
+
48
+
49
+ def _decode_java_utf8(data: bytes) -> str:
50
+ """Decode Java's modified UTF-8 (DataOutput.writeUTF): U+0000 as the
51
+ overlong sequence C0 80, supplementary characters as CESU-8 surrogate pairs."""
52
+ if b"\xc0\x80" in data:
53
+ data = data.replace(b"\xc0\x80", b"\x00")
54
+ try:
55
+ text = data.decode("utf-8", errors="surrogatepass")
56
+ if any("\ud800" <= ch <= "\udfff" for ch in text):
57
+ text = text.encode("utf-16", "surrogatepass").decode("utf-16")
58
+ return text
59
+ except UnicodeDecodeError as exc:
60
+ raise NbtError(f"Invalid UTF-8 in NBT string: {exc}") from exc
61
+
62
+
63
+ class _Readable(Protocol):
64
+ """The only stream capability the reader relies on."""
65
+
66
+ def read(self, size: int = -1) -> bytes: ...
67
+
68
+
69
+ class _Reader:
70
+ """Reads an NBT stream sequentially. Any short read raises NbtError."""
71
+
72
+ __slots__ = ("_stream",)
73
+
74
+ def __init__(self, stream: _Readable) -> None:
75
+ self._stream = stream
76
+
77
+ def read_root(self) -> dict:
78
+ root_tag = self.u8()
79
+ if root_tag != _TAG_COMPOUND:
80
+ raise NbtError(f"Root tag must be TAG_Compound, got type {root_tag}")
81
+ self.string() # root tag name is discarded
82
+ return self._compound(0)
83
+
84
+ def _read(self, size: int) -> bytes:
85
+ data = self._stream.read(size)
86
+ if len(data) != size:
87
+ raise NbtError(
88
+ f"NBT stream truncated: needed {size} bytes, got {len(data)}"
89
+ )
90
+ return data
91
+
92
+ def u8(self) -> int:
93
+ return self._read(1)[0]
94
+
95
+ def string(self) -> str:
96
+ length = struct.unpack(">H", self._read(2))[0]
97
+ return _decode_java_utf8(self._read(length))
98
+
99
+ def payload(self, tag: int, depth: int = 0) -> object:
100
+ scalar = _SCALARS.get(tag)
101
+ if scalar is not None:
102
+ fmt, size = scalar
103
+ return struct.unpack(fmt, self._read(size))[0]
104
+ if tag == _TAG_STRING:
105
+ return self.string()
106
+ array = _ARRAY_DTYPES.get(tag)
107
+ if array is not None:
108
+ return self._array(*array)
109
+ if tag == _TAG_LIST:
110
+ return self._list(depth)
111
+ if tag == _TAG_COMPOUND:
112
+ return self._compound(depth)
113
+ raise NbtError(f"Unknown tag type {tag}")
114
+
115
+ def _array(self, endian_dtype: str, item_size: int, native: type) -> np.ndarray:
116
+ length = self._i32()
117
+ if length < 0:
118
+ raise NbtError(f"Negative array length: {length}")
119
+ buf = self._read(length * item_size)
120
+ return np.frombuffer(buf, dtype=endian_dtype).astype(native)
121
+
122
+ def _list(self, depth: int) -> list:
123
+ self._check_depth(depth)
124
+ element_tag = self.u8()
125
+ length = self._i32()
126
+ if length < 0:
127
+ raise NbtError(f"Negative list length: {length}")
128
+ if element_tag == _TAG_END:
129
+ if length:
130
+ raise NbtError("TAG_List element type is End but length is non-zero")
131
+ return []
132
+ return [self.payload(element_tag, depth + 1) for _ in range(length)]
133
+
134
+ def _compound(self, depth: int) -> dict:
135
+ self._check_depth(depth)
136
+ out: dict = {}
137
+ while True:
138
+ tag = self.u8()
139
+ if tag == _TAG_END:
140
+ return out
141
+ name = self.string()
142
+ out[name] = self.payload(tag, depth + 1)
143
+
144
+ def _check_depth(self, depth: int) -> None:
145
+ if depth >= _MAX_DEPTH:
146
+ raise NbtError(f"NBT nesting deeper than {_MAX_DEPTH} levels")
147
+
148
+ def _i32(self) -> int:
149
+ return struct.unpack(">i", self._read(4))[0]
150
+
151
+
152
+ def read_nbt(data: bytes) -> dict:
153
+ """Parse gzip-compressed or raw Java NBT and return the root compound payload.
154
+
155
+ Compound -> dict, List -> list, string -> str, scalars -> int/float;
156
+ the three array kinds -> native-endian numpy arrays owning their memory.
157
+ """
158
+ stream: _Readable
159
+ if data[:2] == _GZIP_MAGIC:
160
+ stream = gzip.GzipFile(fileobj=io.BytesIO(data))
161
+ else:
162
+ stream = io.BytesIO(data)
163
+ reader = _Reader(stream)
164
+ try:
165
+ return reader.read_root()
166
+ except (OSError, EOFError, zlib.error) as exc:
167
+ raise NbtError(f"Failed to decompress NBT: {exc}") from exc