pz-unpacker 1.0.0__tar.gz

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,47 @@
1
+ Metadata-Version: 2.3
2
+ Name: pz-unpacker
3
+ Version: 1.0.0
4
+ Summary: PZ Unpacker provides a utility tool to unpack Project Zomboid texture packs. Original script from pzmap2dzi, modified for simplicity.
5
+ Author: SimKDT
6
+ Requires-Dist: pillow>=10.4.0
7
+ Requires-Dist: pyyaml>=6.0.4
8
+ Requires-Python: >=3.12.3
9
+ Description-Content-Type: text/markdown
10
+
11
+ # PZ Unpacker
12
+
13
+ PZ Unpacker provides a utility tool to unpack Project Zomboid texture packs.
14
+
15
+ ## Installation
16
+
17
+ You can install PZ Unpacker using `pip`:
18
+
19
+ <details open>
20
+ <summary>PyPI</summary>
21
+
22
+ ```bash
23
+ pip install pz-unpacker
24
+ ```
25
+ </details>
26
+
27
+ <details>
28
+ <summary>Git</summary>
29
+
30
+ ```bash
31
+ pip install git+https://github.com/PZ-Wiki-Modding/Unpacker.git
32
+ ```
33
+ </details>
34
+
35
+ <details>
36
+ <summary>Dev</summary>
37
+
38
+ ```bash
39
+ pip install -e .
40
+ ```
41
+ </details>
42
+
43
+ ## License
44
+
45
+ The initial Python script to unpack files came from [pzmap2dzi](https://github.com/cff29546/pzmap2dzi) which was made standalone and improved to newer Python versions and stricter type definitions, while simplifying the whole process to the bare essentials.
46
+
47
+ This project is licensed under the MIT License.
@@ -0,0 +1,37 @@
1
+ # PZ Unpacker
2
+
3
+ PZ Unpacker provides a utility tool to unpack Project Zomboid texture packs.
4
+
5
+ ## Installation
6
+
7
+ You can install PZ Unpacker using `pip`:
8
+
9
+ <details open>
10
+ <summary>PyPI</summary>
11
+
12
+ ```bash
13
+ pip install pz-unpacker
14
+ ```
15
+ </details>
16
+
17
+ <details>
18
+ <summary>Git</summary>
19
+
20
+ ```bash
21
+ pip install git+https://github.com/PZ-Wiki-Modding/Unpacker.git
22
+ ```
23
+ </details>
24
+
25
+ <details>
26
+ <summary>Dev</summary>
27
+
28
+ ```bash
29
+ pip install -e .
30
+ ```
31
+ </details>
32
+
33
+ ## License
34
+
35
+ The initial Python script to unpack files came from [pzmap2dzi](https://github.com/cff29546/pzmap2dzi) which was made standalone and improved to newer Python versions and stricter type definitions, while simplifying the whole process to the bare essentials.
36
+
37
+ This project is licensed under the MIT License.
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "pz-unpacker"
3
+ version = "1.0.0"
4
+ description = "PZ Unpacker provides a utility tool to unpack Project Zomboid texture packs. Original script from pzmap2dzi, modified for simplicity."
5
+ readme = "README.md"
6
+ requires-python = ">=3.12.3"
7
+ dependencies = [
8
+ "pillow>=10.4.0",
9
+ "pyyaml>=6.0.4",
10
+ ]
11
+
12
+ [[project.authors]]
13
+ name = "SimKDT"
14
+
15
+ [project.scripts]
16
+ pz-unpacker = "pz_unpacker.__main__:main"
17
+
18
+ [dependency-groups]
19
+ dev = [
20
+ "pytest",
21
+ "build",
22
+ "twine",
23
+ ]
24
+
25
+ [build-system]
26
+ requires = ["uv_build>=0.13.5,<0.14.0"]
27
+ build-backend = "uv_build"
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "pz-unpacker"
3
+ version = "1.0.0"
4
+ description = "PZ Unpacker provides a utility tool to unpack Project Zomboid texture packs. Original script from pzmap2dzi, modified for simplicity."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "SimKDT" }
8
+ ]
9
+ requires-python = ">=3.12.3"
10
+ dependencies = [
11
+ "pillow>=10.4.0",
12
+ "pyyaml>=6.0.4",
13
+ ]
14
+
15
+ [dependency-groups]
16
+ dev = [
17
+ "pytest",
18
+ "build",
19
+ "twine"
20
+ ]
21
+
22
+ [project.scripts]
23
+ pz-unpacker = "pz_unpacker.__main__:main"
24
+
25
+ [build-system]
26
+ requires = ["uv_build>=0.13.5,<0.14.0"]
27
+ build-backend = "uv_build"
File without changes
@@ -0,0 +1,19 @@
1
+ import argparse
2
+ from pathlib import Path
3
+
4
+ from pz_unpacker.unpacker import unpack
5
+
6
+ def main() -> None:
7
+ parser = argparse.ArgumentParser(description='PZ texture unpacker')
8
+ parser.add_argument('-o', '--output', type=Path, default='.')
9
+ parser.add_argument('-d', '--debug', action='store_true')
10
+ parser.add_argument('-m', '--mp', type=int, default=1)
11
+ parser.add_argument('-p', '--page-mode', action='store_true')
12
+ parser.add_argument('packs', nargs='+')
13
+ parse = getattr(parser, 'parse_intermixed_args', parser.parse_args)
14
+ args = parse()
15
+ unpack(args.packs, args.output, args.debug, args.mp, args.page_mode)
16
+
17
+
18
+ if __name__ == '__main__':
19
+ main()
@@ -0,0 +1,12 @@
1
+ import tempfile
2
+ from pathlib import Path
3
+
4
+ from pz_unpacker.unpacker import unpack
5
+
6
+ file_path = Path(__file__).parent
7
+
8
+ def test_unpack() -> None:
9
+ ui_file = file_path / "UI.pack"
10
+ with tempfile.TemporaryDirectory() as tmpdir:
11
+ tmpdir = Path(tmpdir)
12
+ unpack(ui_file, output=tmpdir)
@@ -0,0 +1,180 @@
1
+ """Unpack Project Zomboid texture packs by parsing their binary format."""
2
+
3
+ from __future__ import annotations, print_function
4
+
5
+ import hashlib
6
+ import io
7
+ import os
8
+ import yaml
9
+ import struct
10
+ from pathlib import Path
11
+ from typing import Iterable, Sequence
12
+ from multiprocessing.dummy import Pool
13
+
14
+ from PIL import Image
15
+ from PIL.PngImagePlugin import PngInfo
16
+
17
+
18
+ def read_uint32(data: bytes, pos: int) -> tuple[int, int]:
19
+ return struct.unpack_from('<I', data, pos)[0], pos + 4
20
+
21
+
22
+ def read_int32(data: bytes, pos: int) -> tuple[int, int]:
23
+ return struct.unpack_from('<i', data, pos)[0], pos + 4
24
+
25
+
26
+ def read_bytes_with_length(data: bytes, pos: int) -> tuple[bytes, int]:
27
+ length, pos = read_uint32(data, pos)
28
+ end = pos + length
29
+ if end > len(data):
30
+ raise ValueError('Truncated pack data')
31
+ return data[pos:end], end
32
+
33
+
34
+ def read_texture(data: bytes, pos: int) -> tuple[dict[str, str | int], int]:
35
+ texture = {}
36
+ name, pos = read_bytes_with_length(data, pos)
37
+ texture['name'] = name.decode('utf8')
38
+ for key in ('x', 'y', 'w', 'h', 'ox', 'oy', 'ow', 'oh'):
39
+ texture[key], pos = read_int32(data, pos)
40
+ return texture, pos
41
+
42
+
43
+ def read_page(data: bytes, pos: int, version: int):
44
+ page = {}
45
+ page['name'], pos = read_bytes_with_length(data, pos)
46
+ count, pos = read_uint32(data, pos)
47
+ page['has_alpha'], pos = read_uint32(data, pos)
48
+ textures = []
49
+ for _ in range(count):
50
+ texture, pos = read_texture(data, pos)
51
+ textures.append(texture)
52
+ page['textures'] = textures
53
+ if version == 0:
54
+ end = data.index(b'\xef\xbe\xad\xde', pos) + 4
55
+ page['png'], pos = data[pos:end], end
56
+ elif version == 1:
57
+ page['png'], pos = read_bytes_with_length(data, pos)
58
+ else:
59
+ raise ValueError('Unsupported pack version {}'.format(version))
60
+ return page, pos
61
+
62
+
63
+ def load_pack(path: str | Path):
64
+ data = Path(path).read_bytes()
65
+ if data.startswith(b'PZPK'):
66
+ version, pos = read_uint32(data, 4)
67
+ else:
68
+ version, pos = 0, 0
69
+ if version not in (0, 1):
70
+ raise ValueError('Unsupported pack version {}'.format(version))
71
+ page_num, pos = read_uint32(data, pos)
72
+ print('{}: version {}, {} pages'.format(path, version, page_num))
73
+ pages = []
74
+ for _ in range(page_num):
75
+ page, pos = read_page(data, pos, version)
76
+ pages.append(page)
77
+ return pages
78
+
79
+
80
+ def color_sum(pixels: Sequence[tuple[int, int, int, int]]) -> tuple[int, int, int, int]:
81
+ total = len(pixels)
82
+ if total > 0:
83
+ r, g, b, _ = map(sum, zip(*pixels))
84
+ return r, g, b, total
85
+ return 0, 0, 0, 1
86
+
87
+
88
+ def gethash(path: str | Path, method: str = 'md5') -> str:
89
+ data = Path(path).read_bytes()
90
+ hasher = getattr(hashlib, method)()
91
+ hasher.update(data)
92
+ return ':'.join((method, hasher.hexdigest()))
93
+
94
+
95
+ class Texture(object):
96
+ def __init__(self, im: Image.Image, offset: tuple[int, int] | None = None) -> None:
97
+ if offset:
98
+ ox, oy = offset
99
+ else:
100
+ ox = int(im.info.get('ox', 0))
101
+ oy = int(im.info.get('oy', 0))
102
+ bbox = im.getbbox()
103
+ if bbox is None:
104
+ self.im = Image.new('RGBA', (0, 0))
105
+ self.ox = 0
106
+ self.oy = 0
107
+ elif bbox != (0, 0) + im.size:
108
+ self.im = im.crop(bbox)
109
+ self.ox = bbox[0] + ox
110
+ self.oy = bbox[1] + oy
111
+ else:
112
+ self.im = im
113
+ self.ox = ox
114
+ self.oy = oy
115
+ self.color_sum: tuple[int, int, int, int] | None = None
116
+
117
+ def save(self, path: str | Path) -> None:
118
+ metadata = PngInfo()
119
+ metadata.add_text('ox', str(self.ox))
120
+ metadata.add_text('oy', str(self.oy))
121
+ # PNG cannot represent a 0x0 image; reloading this remains an empty texture.
122
+ im = self.im if all(self.im.size) else Image.new('RGBA', (1, 1))
123
+ im.save(Path(path), pnginfo=metadata)
124
+
125
+
126
+ def unpack(
127
+ pack: str | Path,
128
+ output: str | Path = '.',
129
+ debug: bool = False,
130
+ parallel: int = 1,
131
+ page_mode: bool = False,
132
+ ) -> None:
133
+ if parallel < 1:
134
+ raise ValueError('Worker count must be at least 1')
135
+ textures = {}
136
+ pages = []
137
+ mapping = {}
138
+ hashes = {}
139
+
140
+ # load the packs and extract textures and pages
141
+ pack_pages = load_pack(pack)
142
+ hashes[os.fspath(pack)] = gethash(pack)
143
+ for page in pack_pages:
144
+ im = Image.open(io.BytesIO(page['png']))
145
+ page_id = len(pages)
146
+ if page_mode:
147
+ pages.append(im)
148
+ for entry in page['textures']:
149
+ name = entry['name']
150
+ x, y, w, h = (entry[key] for key in ('x', 'y', 'w', 'h'))
151
+ ox = entry['ox'] - (entry['ow'] >> 1)
152
+ oy = entry['oy'] - entry['oh']
153
+ if debug and name in textures:
154
+ print('Conflict texture: {}'.format(name))
155
+ textures[name] = Texture(im.crop((x, y, x + w, y + h)), (ox, oy))
156
+ if page_mode:
157
+ mapping[name] = (page_id, x, y, w, h, ox, oy)
158
+
159
+ # prepare output directory and tasks for saving images
160
+ output_path = Path(output)
161
+ output_path.mkdir(parents=True, exist_ok=True)
162
+ tasks = list(enumerate(pages)) if page_mode else list(textures.items())
163
+
164
+ def save_image(task: tuple[int | str, Image.Image | Texture]) -> None:
165
+ name, image = task
166
+ image.save(output_path / '{}.png'.format(name))
167
+
168
+ # save images using a pool of workers
169
+ pool = Pool(parallel)
170
+ try:
171
+ pool.map(save_image, tasks)
172
+ finally:
173
+ pool.close()
174
+ pool.join()
175
+ if tasks:
176
+ if page_mode:
177
+ with (output_path / 'mapping.yaml').open('w') as f:
178
+ yaml.safe_dump(mapping, f)
179
+ with (output_path / 'hash.yaml').open('w') as f:
180
+ yaml.safe_dump(hashes, f)