spring-nbt-library 3.0.1__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.
@@ -0,0 +1,24 @@
1
+ """SpringNBTLibraryは、Minecraft Java版のNBT / Anvilワールドデータを読み書きするライブラリ
2
+
3
+ 対象は1.13以降のワールド形式 (DataVersion 1519以降)
4
+ """
5
+
6
+ from .errors import ErrorCode, SpringNbtError
7
+
8
+ #: このライブラリが扱えるワールド形式の下限となるDataVersion (1.13)
9
+ #:
10
+ #: 1.13でブロックの持ち方が数値のIDからパレットへ変わった
11
+ #: 1519は1.13の正式版のDataVersion
12
+ #: これ以降のチャンクは、読んだときの形式のまま読み書きできる
13
+ #: 1.16(DataVersion 2529)でビット詰めが値を64bitの境目でまたがない形に変わり、
14
+ #: 1.18(DataVersion 2844)でチャンクの本体が``Level``の外へ出て、
15
+ #: 26.3(DataVersion 5006)でパレットの要素の形が変わったが、どの形式も扱う
16
+ #: これより古いチャンクと、DataVersionの無いチャンク(1.9より前)は形式が違う
17
+ #: そうしたチャンクは、読み込み時は既定で警告を出し、書き戻しは既定でUNSUPPORTED_DATA_VERSIONにする
18
+ MIN_SUPPORTED_DATA_VERSION = 1519
19
+
20
+ #: 動作を確かめたMinecraft Java版のDataVersion (26.3)
21
+ TARGET_DATA_VERSION = 5023
22
+
23
+ __all__ = ["MIN_SUPPORTED_DATA_VERSION", "TARGET_DATA_VERSION",
24
+ "ErrorCode", "SpringNbtError"]
@@ -0,0 +1,24 @@
1
+ """Anvilのリージョンファイル(.mca)の読み書き
2
+ """
3
+
4
+ from .folder import RegionFolder
5
+ from .region import (
6
+ SECTOR_SIZE,
7
+ ChunkCompression,
8
+ ChunkPos,
9
+ RawChunk,
10
+ RegionFile,
11
+ RegionFileMode,
12
+ RegionPos,
13
+ )
14
+
15
+ __all__ = [
16
+ "SECTOR_SIZE",
17
+ "ChunkCompression",
18
+ "ChunkPos",
19
+ "RawChunk",
20
+ "RegionFile",
21
+ "RegionFileMode",
22
+ "RegionFolder",
23
+ "RegionPos",
24
+ ]
@@ -0,0 +1,216 @@
1
+ """リージョンファイルが並ぶディレクトリ1つ分
2
+
3
+ ``region/``、``entities/``、``poi/``のいずれかを表す
4
+ 開いたリージョンファイルはキャッシュし、:meth:`RegionFolder.close`でまとめて閉じる
5
+ チャンク座標からリージョンを解決するので、利用側はリージョンの存在を意識しなくてよい
6
+
7
+ :class:`RegionFile`はファイル全体をメモリへ載せるため、キャッシュには``max_cached_regions``件の上限がある
8
+ 上限を超えると、最も長く使われていないものから書き出して閉じる
9
+ 大きなワールドを端から走査してもメモリを使い切らない
10
+
11
+ このため:meth:`RegionFolder.region`が返した参照は、**別のリージョンへアクセスすると閉じられている場合がある**
12
+ 参照を保持せず、必要なたびに取得すること
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ from collections import OrderedDict
19
+ from typing import Dict, List, Optional
20
+
21
+ from ..errors import ErrorCode, SpringNbtError
22
+ from ..nbt import NbtCompound
23
+ from .region import ChunkPos, RegionFile, RegionFileMode, RegionPos
24
+
25
+ __all__ = ["DEFAULT_MAX_CACHED_REGIONS", "RegionFolder"]
26
+
27
+ #: 同時に開いておくリージョンファイル数の既定の上限
28
+ #:
29
+ #: 1リージョンは最大255セクタ × 1024チャンク=理論上1GiBになりうる
30
+ #: 実データでは数MBから数十MB程度
31
+ #: 8件なら通常のワールドで数百MBに収まる
32
+ DEFAULT_MAX_CACHED_REGIONS = 8
33
+
34
+
35
+ class RegionFolder:
36
+ """リージョンフォルダ1つ分"""
37
+
38
+ def __init__(self, directory: str, mode: RegionFileMode,
39
+ max_cached_regions: int = DEFAULT_MAX_CACHED_REGIONS) -> None:
40
+ self.directory = directory
41
+ #: 同時に開いておくリージョンファイル数の上限
42
+ self.max_cached_regions = max_cached_regions
43
+ self._mode = mode
44
+ # 最近使った順を保つので、先頭がいちばん長く使っていないもの
45
+ self._cache: "OrderedDict[RegionPos, RegionFile]" = OrderedDict()
46
+ self._closed = False
47
+
48
+ @property
49
+ def cached_region_count(self) -> int:
50
+ """いま開いているリージョンファイル数"""
51
+ return len(self._cache)
52
+
53
+ @staticmethod
54
+ def open(directory: str,
55
+ mode: RegionFileMode = RegionFileMode.READ_ONLY,
56
+ max_cached_regions: int = DEFAULT_MAX_CACHED_REGIONS) -> "RegionFolder":
57
+ """リージョンフォルダを開く
58
+
59
+ :raises SpringNbtError: 読み取り専用でディレクトリが存在しない場合、または上限が1未満の場合
60
+ """
61
+ if max_cached_regions < 1:
62
+ raise SpringNbtError.invalid_argument(
63
+ "max_cached_regions は 1 以上でなければならない: %d" % max_cached_regions)
64
+
65
+ if not os.path.isdir(directory) and mode == RegionFileMode.READ_ONLY:
66
+ raise SpringNbtError(
67
+ ErrorCode.IO, "リージョンフォルダが存在しない: %s" % directory)
68
+
69
+ return RegionFolder(directory, mode, max_cached_regions)
70
+
71
+ def __enter__(self) -> "RegionFolder":
72
+ return self
73
+
74
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
75
+ self.close()
76
+
77
+ def region_positions(self) -> List[RegionPos]:
78
+ """このフォルダに存在するリージョンの座標を返す"""
79
+ self._ensure_open()
80
+
81
+ if not os.path.isdir(self.directory):
82
+ return []
83
+
84
+ found = []
85
+
86
+ # r.X.Z.mcaとして解釈できるファイルだけを拾う
87
+ for name in os.listdir(self.directory):
88
+ position = RegionPos.from_file_name(name)
89
+
90
+ # r.X.Z.mcaとして解釈できるファイルだけを拾う
91
+ if position is not None:
92
+ found.append(position)
93
+
94
+ # 走査順がファイルシステム依存にならないよう、座標で並べる
95
+ found.sort(key=lambda position: (position.z, position.x))
96
+ return found
97
+
98
+ def region(self, region_x: int, region_z: int) -> Optional[RegionFile]:
99
+ """リージョンファイルを取得する
100
+ 読み取り専用で存在しなければNone
101
+ """
102
+ self._ensure_open()
103
+ position = RegionPos(region_x, region_z)
104
+ cached = self._cache.get(position)
105
+
106
+ if cached is not None:
107
+ # 使ったものを末尾へ移して、最近使った順を保つ
108
+ self._cache.move_to_end(position)
109
+ return cached
110
+
111
+ path = os.path.join(self.directory, position.file_name())
112
+
113
+ # 読み取り専用では、存在しないリージョンは「チャンクが無い」としてNoneを返す
114
+ if not os.path.exists(path) and self._mode == RegionFileMode.READ_ONLY:
115
+ return None
116
+
117
+ # 開く前に空きを作る
118
+ # 開いてからだと一瞬だけ上限を超える
119
+ self._evict_until_below_limit()
120
+
121
+ opened = RegionFile.open(path, self._mode)
122
+ self._cache[position] = opened
123
+ return opened
124
+
125
+ def _evict_until_below_limit(self) -> None:
126
+ """新しく1件開けるよう、上限を下回るまで古いものを閉じる"""
127
+ # 上限に達している間、いちばん長く使っていないものから閉じる
128
+ while len(self._cache) >= self.max_cached_regions:
129
+ _, oldest = self._cache.popitem(last=False)
130
+ # 閉じる前に必ず書き出す
131
+ # 捨てると変更が失われる
132
+ oldest.close()
133
+
134
+ def has_chunk(self, chunk_x: int, chunk_z: int) -> bool:
135
+ """チャンクが存在するか"""
136
+ file = self._region_for(chunk_x, chunk_z)
137
+
138
+ if file is None:
139
+ return False
140
+
141
+ return file.has_chunk(chunk_x, chunk_z)
142
+
143
+ def read_chunk(self, chunk_x: int, chunk_z: int) -> Optional[NbtCompound]:
144
+ """チャンクをNBTとして読む
145
+ 存在しなければNone
146
+ """
147
+ file = self._region_for(chunk_x, chunk_z)
148
+
149
+ if file is None:
150
+ return None
151
+
152
+ return file.read_chunk(chunk_x, chunk_z)
153
+
154
+ def write_chunk(self, chunk_x: int, chunk_z: int, tag: NbtCompound) -> None:
155
+ """チャンクをNBTとして書き込む"""
156
+ file = self._region_for(chunk_x, chunk_z)
157
+
158
+ if file is None:
159
+ raise SpringNbtError.invalid_argument(
160
+ "読み取り専用のフォルダには書き込めない: %s" % self.directory)
161
+
162
+ file.write_chunk(chunk_x, chunk_z, tag)
163
+
164
+ def delete_chunk(self, chunk_x: int, chunk_z: int) -> bool:
165
+ """チャンクを削除する
166
+ 削除できたらTrue
167
+ """
168
+ file = self._region_for(chunk_x, chunk_z)
169
+
170
+ if file is None:
171
+ return False
172
+
173
+ return file.delete_chunk(chunk_x, chunk_z)
174
+
175
+ def chunk_positions(self) -> List[ChunkPos]:
176
+ """このフォルダに存在する全チャンクの座標を返す"""
177
+ result = []
178
+
179
+ # リージョンごとに、その中のチャンクを順に集める
180
+ for position in self.region_positions():
181
+ file = self.region(position.x, position.z)
182
+
183
+ if file is None:
184
+ continue
185
+
186
+ result.extend(file.chunk_positions())
187
+
188
+ return result
189
+
190
+ def flush(self) -> None:
191
+ """開いている全リージョンの変更を書き出す"""
192
+ self._ensure_open()
193
+
194
+ # 開いているリージョンをすべて書き出す
195
+ for file in self._cache.values():
196
+ file.flush()
197
+
198
+ def close(self) -> None:
199
+ """開いている全リージョンを閉じる"""
200
+ if self._closed:
201
+ return
202
+
203
+ # 開いているリージョンをすべて閉じる
204
+ for file in self._cache.values():
205
+ file.close()
206
+
207
+ self._cache.clear()
208
+ self._closed = True
209
+
210
+ def _region_for(self, chunk_x: int, chunk_z: int) -> Optional[RegionFile]:
211
+ position = ChunkPos(chunk_x, chunk_z).region()
212
+ return self.region(position.x, position.z)
213
+
214
+ def _ensure_open(self) -> None:
215
+ if self._closed:
216
+ raise SpringNbtError.invalid_argument("既に閉じられたリージョンフォルダ")
@@ -0,0 +1,188 @@
1
+ """圧縮方式ID 4(LZ4)のチャンクを展開する
2
+
3
+ 素のLZ4ブロックでもLZ4フレーム形式でもなく、独自ヘッダを持つブロックの連結である
4
+
5
+ 書き込みには対応しない
6
+ NBTとして書き戻すときは既定でZlibになり、生バイトのまま書き戻すとLZ4のまま残る
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import struct
12
+
13
+ from ..errors import SpringNbtError
14
+
15
+ __all__ = ["decompress_lz4"]
16
+
17
+ #: ブロックの先頭に必ず置かれる8バイト
18
+ MAGIC = b"LZ4Block"
19
+
20
+ #: ブロックヘッダの長さ
21
+ HEADER_LENGTH = 21
22
+
23
+ #: トークン上位4ビット: 本体が無圧縮
24
+ METHOD_STORED = 0x10
25
+
26
+ #: トークン上位4ビット: 本体がLZ4圧縮
27
+ METHOD_COMPRESSED = 0x20
28
+
29
+ #: マッチの最小長
30
+ MIN_MATCH = 4
31
+
32
+
33
+ def decompress_lz4(payload: bytes) -> bytes:
34
+ """LZ4Blockの連結を展開する
35
+
36
+ :raises SpringNbtError: 形式に反する入力の場合(MALFORMED_DATA)
37
+ """
38
+ blocks = []
39
+ position = 0
40
+
41
+ # 入力を使い切るまでブロックを読み続ける
42
+ while position < len(payload):
43
+ data, position = _decompress_block(payload, position)
44
+ blocks.append(data)
45
+
46
+ return b"".join(blocks)
47
+
48
+
49
+ def _decompress_block(payload: bytes, position: int):
50
+ """ブロックを1つ展開し、中身と次のブロックの開始位置を返す"""
51
+ if position + HEADER_LENGTH > len(payload):
52
+ raise SpringNbtError.malformed(
53
+ "LZ4: ブロックヘッダが足りない(%d バイト)" % (len(payload) - position))
54
+
55
+ # マジックが違えばそもそもLZ4Blockではない
56
+ if payload[position:position + len(MAGIC)] != MAGIC:
57
+ raise SpringNbtError.malformed("LZ4: ブロックが LZ4Block で始まっていない")
58
+
59
+ method = payload[position + 8] & 0xF0
60
+ compressed_length = struct.unpack_from("<i", payload, position + 9)[0]
61
+ original_length = struct.unpack_from("<i", payload, position + 13)[0]
62
+ body = position + HEADER_LENGTH
63
+
64
+ _validate_lengths(compressed_length, original_length)
65
+
66
+ if body + compressed_length > len(payload):
67
+ raise SpringNbtError.malformed("LZ4: ブロック本体が入力からはみ出している")
68
+
69
+ if method == METHOD_STORED:
70
+ # 無圧縮なら2つの長さは一致していなければならない
71
+ if compressed_length != original_length:
72
+ raise SpringNbtError.malformed(
73
+ "LZ4: 無圧縮ブロックの長さが食い違う(%d と %d)"
74
+ % (compressed_length, original_length))
75
+
76
+ return payload[body:body + compressed_length], body + compressed_length
77
+
78
+ # 圧縮されているなら素のLZ4ブロックとして展開する
79
+ if method == METHOD_COMPRESSED:
80
+ data = _decompress_raw_block(
81
+ payload[body:body + compressed_length], original_length)
82
+ return data, body + compressed_length
83
+
84
+ raise SpringNbtError.malformed("LZ4: 未知の圧縮方式 0x%02X" % method)
85
+
86
+
87
+ def _validate_lengths(compressed_length: int, original_length: int) -> None:
88
+ """ヘッダに書かれた2つの長さが妥当か調べる"""
89
+ if compressed_length < 0 or original_length < 0:
90
+ raise SpringNbtError.malformed("LZ4: ブロックの長さが負値")
91
+
92
+ # 片方だけが0になることはない
93
+ if (compressed_length == 0) != (original_length == 0):
94
+ raise SpringNbtError.malformed("LZ4: ブロックの長さが片方だけ 0")
95
+
96
+
97
+ def _decompress_raw_block(source: bytes, original_length: int) -> bytes:
98
+ """素のLZ4ブロックを展開する"""
99
+ output = bytearray(original_length)
100
+ position = 0
101
+ written = 0
102
+
103
+ # シーケンスを順に読む
104
+ while position < len(source):
105
+ token = source[position]
106
+ position += 1
107
+
108
+ literal_length = token >> 4
109
+
110
+ # 15なら追加バイトで長さが続く
111
+ if literal_length == 15:
112
+ extra, position = _read_length(source, position)
113
+ literal_length += extra
114
+
115
+ written, position = _copy_literals(
116
+ source, position, output, written, literal_length)
117
+
118
+ # リテラルを出し切って入力が尽きたら、そこで終わり
119
+ if position >= len(source):
120
+ break
121
+
122
+ if position + 2 > len(source):
123
+ raise SpringNbtError.malformed("LZ4: オフセットが入力からはみ出している")
124
+
125
+ offset = source[position] | (source[position + 1] << 8)
126
+ position += 2
127
+
128
+ if offset == 0 or offset > written:
129
+ raise SpringNbtError.malformed("LZ4: マッチのオフセットが不正: %d" % offset)
130
+
131
+ match_length = (token & 0x0F) + MIN_MATCH
132
+
133
+ # 下位4ビットが15なら追加バイトで長さが続く
134
+ if (token & 0x0F) == 15:
135
+ extra, position = _read_length(source, position)
136
+ match_length += extra
137
+
138
+ written = _copy_match(output, written, offset, match_length)
139
+
140
+ if written != original_length:
141
+ raise SpringNbtError.malformed(
142
+ "LZ4: 展開後の長さが合わない(%d と %d)" % (written, original_length))
143
+
144
+ return bytes(output)
145
+
146
+
147
+ def _read_length(source: bytes, position: int):
148
+ """255が続く形式の追加長さを読む"""
149
+ total = 0
150
+
151
+ # 255未満のバイトが出るまで足し続ける
152
+ while True:
153
+ if position >= len(source):
154
+ raise SpringNbtError.malformed("LZ4: 長さの追加バイトが途中で切れた")
155
+
156
+ value = source[position]
157
+ position += 1
158
+ total += value
159
+
160
+ if value != 255:
161
+ return total, position
162
+
163
+
164
+ def _copy_literals(source: bytes, position: int, output: bytearray,
165
+ written: int, length: int):
166
+ """リテラルをそのまま出力へ写す"""
167
+ if position + length > len(source):
168
+ raise SpringNbtError.malformed("LZ4: リテラルが入力からはみ出している")
169
+
170
+ if written + length > len(output):
171
+ raise SpringNbtError.malformed("LZ4: 展開後の長さを超えた")
172
+
173
+ output[written:written + length] = source[position:position + length]
174
+ return written + length, position + length
175
+
176
+
177
+ def _copy_match(output: bytearray, written: int, offset: int, length: int) -> int:
178
+ """出力済みのバイト列からマッチを写す"""
179
+ if written + length > len(output):
180
+ raise SpringNbtError.malformed("LZ4: 展開後の長さを超えた")
181
+
182
+ start = written - offset
183
+
184
+ # コピー元と先は重なりうるので1バイトずつ写す
185
+ for index in range(length):
186
+ output[written + index] = output[start + index]
187
+
188
+ return written + length