uppercut-retro-pixels 0.1.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.
- uppercut_retro_pixels-0.1.0/.gitignore +16 -0
- uppercut_retro_pixels-0.1.0/LICENSE +21 -0
- uppercut_retro_pixels-0.1.0/PKG-INFO +110 -0
- uppercut_retro_pixels-0.1.0/README.md +87 -0
- uppercut_retro_pixels-0.1.0/pyproject.toml +36 -0
- uppercut_retro_pixels-0.1.0/src/uppercut_retro_pixels/__init__.py +64 -0
- uppercut_retro_pixels-0.1.0/src/uppercut_retro_pixels/atlas.py +188 -0
- uppercut_retro_pixels-0.1.0/src/uppercut_retro_pixels/blocks.py +105 -0
- uppercut_retro_pixels-0.1.0/src/uppercut_retro_pixels/formats.py +140 -0
- uppercut_retro_pixels-0.1.0/src/uppercut_retro_pixels/palette.py +63 -0
- uppercut_retro_pixels-0.1.0/src/uppercut_retro_pixels/py.typed +0 -0
- uppercut_retro_pixels-0.1.0/src/uppercut_retro_pixels/rle.py +74 -0
- uppercut_retro_pixels-0.1.0/tests/conftest.py +6 -0
- uppercut_retro_pixels-0.1.0/tests/rp_synthetic.py +27 -0
- uppercut_retro_pixels-0.1.0/tests/test_atlas.py +157 -0
- uppercut_retro_pixels-0.1.0/tests/test_blocks.py +105 -0
- uppercut_retro_pixels-0.1.0/tests/test_formats.py +182 -0
- uppercut_retro_pixels-0.1.0/tests/test_palette.py +56 -0
- uppercut_retro_pixels-0.1.0/tests/test_rle.py +49 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Uppercut Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: uppercut-retro-pixels
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Retro console pixel formats as pure functions: RGB565, ARGB4444, ARGB1555, RGBA5551 and BGR555, R/B swap, block swizzle, RLE, palette ramps and a glyph-atlas packer.
|
|
5
|
+
Project-URL: Source, https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-retro-pixels
|
|
6
|
+
Author-email: Uppercut Labs <packages@uppercut-labs.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: argb1555,argb4444,atlas,console,retro,rgb565,rgba5551,swizzle,texture
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Games/Entertainment
|
|
19
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# uppercut-retro-pixels
|
|
25
|
+
|
|
26
|
+
The pixel arithmetic that console ports keep retyping, as pure functions on bytes, integers and tuples: 16-bit colour formats, red/blue swap, the PSP block swizzle and its inverse, run-length coding, palette ramps and padded palettes, and a glyph-atlas packer that writes the metrics as a C header. Standard library only; no Pillow, no numpy. Turning a PNG into RGBA bytes (and running ImageMagick or a texture converter) stays with the caller.
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pip install uppercut-retro-pixels
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Requires Python 3.10 or newer.
|
|
33
|
+
|
|
34
|
+
## Example
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
from uppercut_retro_pixels import ARGB4444, RGB565, encode, pack, swap_rb, swizzle
|
|
38
|
+
|
|
39
|
+
# One pixel, or a whole RGBA image, into a console format
|
|
40
|
+
value = encode(RGB565, 255, 128, 0) # 0xFC00
|
|
41
|
+
data = pack(ARGB4444, rgba_bytes, endian="little") # two bytes a pixel
|
|
42
|
+
|
|
43
|
+
# PSP wants BGR565, laid out in 16-byte by 8-row blocks
|
|
44
|
+
psp = swizzle(pack(RGB565, rgba_bytes), row_bytes=64 * 2, height=64)
|
|
45
|
+
bgr = swap_rb(RGB565, value) # the same pixel as BGR565
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Formats
|
|
49
|
+
|
|
50
|
+
`RGB565`, `BGR565`, `ARGB4444`, `ABGR4444`, `ARGB1555`, `ABGR1555`, `RGBA5551` and `BGR555` are `PixelFormat` values; `FORMATS` maps names to them. A format lists where each channel sits in the 16-bit value, so other layouts are a one-line `PixelFormat(name, {"r": (shift, bits), ...})`.
|
|
51
|
+
|
|
52
|
+
| Function | What it does |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `encode(fmt, r, g, b, a=255, *, rounding="truncate")` | Packs 8-bit channels into a 16-bit integer. `"truncate"` is a right shift; `"nearest"` picks the closest level. A 1-bit alpha is on from 128 in both modes. |
|
|
55
|
+
| `encode_unit(fmt, r, g, b, a=1.0)` | The same for channels given as floats in 0..1: clamped, scaled, rounded with Python's `round` and masked. |
|
|
56
|
+
| `decode(fmt, value, *, expand="replicate")` | Unpacks to `(r, g, b, a)`. `"replicate"` repeats the high bits into the low ones (`v << 3 \| v >> 2` for 5 bits); `"scale"` is `v * 255 // max`. A format with no alpha gives 255. |
|
|
57
|
+
| `swap_rb(fmt, value)` | Exchanges the red and blue fields. `swap_rb(RGB565, v)` is `v` read as `BGR565`, and `swap_rb(ARGB4444, v)` is `v` read as `ABGR4444`. |
|
|
58
|
+
| `pack(fmt, rgba, *, endian="little", rounding="truncate")` | RGBA bytes to packed pixels, two bytes each. |
|
|
59
|
+
| `unpack(fmt, data, *, endian="little", expand="replicate")` | Packed pixels to RGBA bytes. |
|
|
60
|
+
|
|
61
|
+
## Block layouts
|
|
62
|
+
|
|
63
|
+
| Function | What it does |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| `swizzle(data, row_bytes, height)` | Reorders a linear image into 16-byte by 8-row blocks, the PSP texture layout. `row_bytes` is a multiple of 16 and `height` a multiple of 8. Works for any pixel size, 4-bit included, because it counts bytes. |
|
|
66
|
+
| `unswizzle(data, row_bytes, height)` | The inverse. |
|
|
67
|
+
| `swizzle_items(items, width, height, *, block_width=8, block_height=8)` | The same reordering for a list of whole pixels. The default block fits 16-bit pixels; use `block_width=16` for 8-bit ones. |
|
|
68
|
+
| `pack_nibbles(indices)` / `unpack_nibbles(data)` | 4-bit indices, two to a byte, the first in the low nibble. |
|
|
69
|
+
| `morton_index(x, y, bits)` | The interleaved (twiddled) index Dreamcast textures use. |
|
|
70
|
+
|
|
71
|
+
A byte at `(x, y)` lands at `((y // 8) * (row_bytes // 16) + x // 16) * 128 + (y % 8) * 16 + x % 16`.
|
|
72
|
+
|
|
73
|
+
## Run-length coding
|
|
74
|
+
|
|
75
|
+
A record is a one-byte count and a value of one or two bytes.
|
|
76
|
+
|
|
77
|
+
| Function | What it does |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| `rle_runs(values, *, max_run=255)` | `(count, value)` runs. |
|
|
80
|
+
| `rle_pack(values, *, value_bytes=1, endian="big", max_run=255)` | Bytes of `count, value` records. |
|
|
81
|
+
| `rle_unpack(data, *, value_bytes=1, endian="big", limit=None)` | The values back. A record cut off at the end is dropped; `limit` stops at that many values, so a dump with spare runs past the end of the image is trimmed. |
|
|
82
|
+
| `rle_unpack_hex(text, *, value_bytes=2, limit=None)` | The same for records logged as hexadecimal text (two digits of count, then the value), whitespace ignored. |
|
|
83
|
+
| `flatten(runs)` | Expands `(count, value)` runs. |
|
|
84
|
+
|
|
85
|
+
## Palettes
|
|
86
|
+
|
|
87
|
+
| Function | What it does |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| `ramp(stops, steps)` | `steps` colours evenly spaced through a list of `(r, g, b)` stops, ends included, rounded to the nearest integer. |
|
|
90
|
+
| `pad_palette(colors, size=256, fill=None)` | Exactly `size` colours; missing ones come from `fill(index)`, or black. |
|
|
91
|
+
| `palette_bytes(colors, size=256)` | Flat `r, g, b` bytes, zero-padded to `size` entries. |
|
|
92
|
+
|
|
93
|
+
## Glyph atlases
|
|
94
|
+
|
|
95
|
+
| Name | What it does |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `Glyph(char, width, height, y_offset, advance, pixels)` | One glyph bitmap, RGBA bytes. A blank glyph has width and height 0. |
|
|
98
|
+
| `pack_glyphs(sets, atlas_width, atlas_height, *, margin=1)` | Shelf-packs the glyphs of one or more sets into an RGBA atlas and returns it with a `GlyphRect` (x, y, width, height, y_offset, advance) for each glyph. The sets share a cursor. Raises `ValueError` when the atlas is full. |
|
|
99
|
+
| `metrics_header(tables, *, atlas_width, atlas_height, first_char, last_char, ...)` | The C header: atlas size and character range as `#define`s, a glyph struct and one `static const` rectangle table per `(name, rects)`. Names, guard, integer types and include line are parameters. |
|
|
100
|
+
| `outlined_cell_atlas(rows_for, *, first=32, last=126, columns=16, cell_width=8, cell_height=12, ...)` | A texture of equal cells holding 1-bit glyph rows with a one-pixel outline, as pixel values the caller has already packed (`ink`, `outline`, `blank`). |
|
|
101
|
+
|
|
102
|
+
Fonts render from outside: the caller draws glyphs with ImageMagick, Pillow or a bitmap table and hands the RGBA bytes to `pack_glyphs`; a 5x7 table for `outlined_cell_atlas` comes from `bitmap-font` or `uppercut-pixel-art-sheets`.
|
|
103
|
+
|
|
104
|
+
## Errors
|
|
105
|
+
|
|
106
|
+
Every function raises `ValueError` for input it cannot use: a channel outside 0..255, an odd byte count, a size that is not a whole number of blocks, a palette over its size, an atlas that is full.
|
|
107
|
+
|
|
108
|
+
## Licence
|
|
109
|
+
|
|
110
|
+
MIT
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# uppercut-retro-pixels
|
|
2
|
+
|
|
3
|
+
The pixel arithmetic that console ports keep retyping, as pure functions on bytes, integers and tuples: 16-bit colour formats, red/blue swap, the PSP block swizzle and its inverse, run-length coding, palette ramps and padded palettes, and a glyph-atlas packer that writes the metrics as a C header. Standard library only; no Pillow, no numpy. Turning a PNG into RGBA bytes (and running ImageMagick or a texture converter) stays with the caller.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install uppercut-retro-pixels
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Requires Python 3.10 or newer.
|
|
10
|
+
|
|
11
|
+
## Example
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from uppercut_retro_pixels import ARGB4444, RGB565, encode, pack, swap_rb, swizzle
|
|
15
|
+
|
|
16
|
+
# One pixel, or a whole RGBA image, into a console format
|
|
17
|
+
value = encode(RGB565, 255, 128, 0) # 0xFC00
|
|
18
|
+
data = pack(ARGB4444, rgba_bytes, endian="little") # two bytes a pixel
|
|
19
|
+
|
|
20
|
+
# PSP wants BGR565, laid out in 16-byte by 8-row blocks
|
|
21
|
+
psp = swizzle(pack(RGB565, rgba_bytes), row_bytes=64 * 2, height=64)
|
|
22
|
+
bgr = swap_rb(RGB565, value) # the same pixel as BGR565
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Formats
|
|
26
|
+
|
|
27
|
+
`RGB565`, `BGR565`, `ARGB4444`, `ABGR4444`, `ARGB1555`, `ABGR1555`, `RGBA5551` and `BGR555` are `PixelFormat` values; `FORMATS` maps names to them. A format lists where each channel sits in the 16-bit value, so other layouts are a one-line `PixelFormat(name, {"r": (shift, bits), ...})`.
|
|
28
|
+
|
|
29
|
+
| Function | What it does |
|
|
30
|
+
| --- | --- |
|
|
31
|
+
| `encode(fmt, r, g, b, a=255, *, rounding="truncate")` | Packs 8-bit channels into a 16-bit integer. `"truncate"` is a right shift; `"nearest"` picks the closest level. A 1-bit alpha is on from 128 in both modes. |
|
|
32
|
+
| `encode_unit(fmt, r, g, b, a=1.0)` | The same for channels given as floats in 0..1: clamped, scaled, rounded with Python's `round` and masked. |
|
|
33
|
+
| `decode(fmt, value, *, expand="replicate")` | Unpacks to `(r, g, b, a)`. `"replicate"` repeats the high bits into the low ones (`v << 3 \| v >> 2` for 5 bits); `"scale"` is `v * 255 // max`. A format with no alpha gives 255. |
|
|
34
|
+
| `swap_rb(fmt, value)` | Exchanges the red and blue fields. `swap_rb(RGB565, v)` is `v` read as `BGR565`, and `swap_rb(ARGB4444, v)` is `v` read as `ABGR4444`. |
|
|
35
|
+
| `pack(fmt, rgba, *, endian="little", rounding="truncate")` | RGBA bytes to packed pixels, two bytes each. |
|
|
36
|
+
| `unpack(fmt, data, *, endian="little", expand="replicate")` | Packed pixels to RGBA bytes. |
|
|
37
|
+
|
|
38
|
+
## Block layouts
|
|
39
|
+
|
|
40
|
+
| Function | What it does |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `swizzle(data, row_bytes, height)` | Reorders a linear image into 16-byte by 8-row blocks, the PSP texture layout. `row_bytes` is a multiple of 16 and `height` a multiple of 8. Works for any pixel size, 4-bit included, because it counts bytes. |
|
|
43
|
+
| `unswizzle(data, row_bytes, height)` | The inverse. |
|
|
44
|
+
| `swizzle_items(items, width, height, *, block_width=8, block_height=8)` | The same reordering for a list of whole pixels. The default block fits 16-bit pixels; use `block_width=16` for 8-bit ones. |
|
|
45
|
+
| `pack_nibbles(indices)` / `unpack_nibbles(data)` | 4-bit indices, two to a byte, the first in the low nibble. |
|
|
46
|
+
| `morton_index(x, y, bits)` | The interleaved (twiddled) index Dreamcast textures use. |
|
|
47
|
+
|
|
48
|
+
A byte at `(x, y)` lands at `((y // 8) * (row_bytes // 16) + x // 16) * 128 + (y % 8) * 16 + x % 16`.
|
|
49
|
+
|
|
50
|
+
## Run-length coding
|
|
51
|
+
|
|
52
|
+
A record is a one-byte count and a value of one or two bytes.
|
|
53
|
+
|
|
54
|
+
| Function | What it does |
|
|
55
|
+
| --- | --- |
|
|
56
|
+
| `rle_runs(values, *, max_run=255)` | `(count, value)` runs. |
|
|
57
|
+
| `rle_pack(values, *, value_bytes=1, endian="big", max_run=255)` | Bytes of `count, value` records. |
|
|
58
|
+
| `rle_unpack(data, *, value_bytes=1, endian="big", limit=None)` | The values back. A record cut off at the end is dropped; `limit` stops at that many values, so a dump with spare runs past the end of the image is trimmed. |
|
|
59
|
+
| `rle_unpack_hex(text, *, value_bytes=2, limit=None)` | The same for records logged as hexadecimal text (two digits of count, then the value), whitespace ignored. |
|
|
60
|
+
| `flatten(runs)` | Expands `(count, value)` runs. |
|
|
61
|
+
|
|
62
|
+
## Palettes
|
|
63
|
+
|
|
64
|
+
| Function | What it does |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `ramp(stops, steps)` | `steps` colours evenly spaced through a list of `(r, g, b)` stops, ends included, rounded to the nearest integer. |
|
|
67
|
+
| `pad_palette(colors, size=256, fill=None)` | Exactly `size` colours; missing ones come from `fill(index)`, or black. |
|
|
68
|
+
| `palette_bytes(colors, size=256)` | Flat `r, g, b` bytes, zero-padded to `size` entries. |
|
|
69
|
+
|
|
70
|
+
## Glyph atlases
|
|
71
|
+
|
|
72
|
+
| Name | What it does |
|
|
73
|
+
| --- | --- |
|
|
74
|
+
| `Glyph(char, width, height, y_offset, advance, pixels)` | One glyph bitmap, RGBA bytes. A blank glyph has width and height 0. |
|
|
75
|
+
| `pack_glyphs(sets, atlas_width, atlas_height, *, margin=1)` | Shelf-packs the glyphs of one or more sets into an RGBA atlas and returns it with a `GlyphRect` (x, y, width, height, y_offset, advance) for each glyph. The sets share a cursor. Raises `ValueError` when the atlas is full. |
|
|
76
|
+
| `metrics_header(tables, *, atlas_width, atlas_height, first_char, last_char, ...)` | The C header: atlas size and character range as `#define`s, a glyph struct and one `static const` rectangle table per `(name, rects)`. Names, guard, integer types and include line are parameters. |
|
|
77
|
+
| `outlined_cell_atlas(rows_for, *, first=32, last=126, columns=16, cell_width=8, cell_height=12, ...)` | A texture of equal cells holding 1-bit glyph rows with a one-pixel outline, as pixel values the caller has already packed (`ink`, `outline`, `blank`). |
|
|
78
|
+
|
|
79
|
+
Fonts render from outside: the caller draws glyphs with ImageMagick, Pillow or a bitmap table and hands the RGBA bytes to `pack_glyphs`; a 5x7 table for `outlined_cell_atlas` comes from `bitmap-font` or `uppercut-pixel-art-sheets`.
|
|
80
|
+
|
|
81
|
+
## Errors
|
|
82
|
+
|
|
83
|
+
Every function raises `ValueError` for input it cannot use: a channel outside 0..255, an odd byte count, a size that is not a whole number of blocks, a palette over its size, an atlas that is full.
|
|
84
|
+
|
|
85
|
+
## Licence
|
|
86
|
+
|
|
87
|
+
MIT
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.25"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uppercut-retro-pixels"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Retro console pixel formats as pure functions: RGB565, ARGB4444, ARGB1555, RGBA5551 and BGR555, R/B swap, block swizzle, RLE, palette ramps and a glyph-atlas packer."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "Uppercut Labs", email = "packages@uppercut-labs.com" }]
|
|
13
|
+
keywords = ["rgb565", "argb4444", "argb1555", "rgba5551", "swizzle", "texture", "atlas", "retro", "console"]
|
|
14
|
+
dependencies = []
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Operating System :: OS Independent",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Games/Entertainment",
|
|
25
|
+
"Topic :: Multimedia :: Graphics",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Source = "https://github.com/uppercut-labs/game-kit/tree/main/packages/uppercut-retro-pixels"
|
|
31
|
+
|
|
32
|
+
[tool.hatch.build.targets.wheel]
|
|
33
|
+
packages = ["src/uppercut_retro_pixels"]
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.sdist]
|
|
36
|
+
include = ["src", "tests", "README.md"]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Retro console pixel formats as pure functions on bytes and tuples."""
|
|
2
|
+
|
|
3
|
+
from .atlas import Glyph, GlyphRect, metrics_header, outlined_cell_atlas, pack_glyphs
|
|
4
|
+
from .blocks import morton_index, pack_nibbles, swizzle, swizzle_items, unpack_nibbles, unswizzle
|
|
5
|
+
from .formats import (
|
|
6
|
+
ABGR1555,
|
|
7
|
+
ABGR4444,
|
|
8
|
+
ARGB1555,
|
|
9
|
+
ARGB4444,
|
|
10
|
+
BGR555,
|
|
11
|
+
BGR565,
|
|
12
|
+
FORMATS,
|
|
13
|
+
RGB565,
|
|
14
|
+
RGBA5551,
|
|
15
|
+
PixelFormat,
|
|
16
|
+
decode,
|
|
17
|
+
encode,
|
|
18
|
+
encode_unit,
|
|
19
|
+
pack,
|
|
20
|
+
swap_rb,
|
|
21
|
+
unpack,
|
|
22
|
+
)
|
|
23
|
+
from .palette import pad_palette, palette_bytes, ramp
|
|
24
|
+
from .rle import flatten, rle_pack, rle_runs, rle_unpack, rle_unpack_hex
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"ABGR1555",
|
|
28
|
+
"ABGR4444",
|
|
29
|
+
"ARGB1555",
|
|
30
|
+
"ARGB4444",
|
|
31
|
+
"BGR555",
|
|
32
|
+
"BGR565",
|
|
33
|
+
"FORMATS",
|
|
34
|
+
"Glyph",
|
|
35
|
+
"GlyphRect",
|
|
36
|
+
"PixelFormat",
|
|
37
|
+
"RGB565",
|
|
38
|
+
"RGBA5551",
|
|
39
|
+
"decode",
|
|
40
|
+
"encode",
|
|
41
|
+
"encode_unit",
|
|
42
|
+
"flatten",
|
|
43
|
+
"metrics_header",
|
|
44
|
+
"morton_index",
|
|
45
|
+
"outlined_cell_atlas",
|
|
46
|
+
"pack",
|
|
47
|
+
"pack_glyphs",
|
|
48
|
+
"pack_nibbles",
|
|
49
|
+
"pad_palette",
|
|
50
|
+
"palette_bytes",
|
|
51
|
+
"ramp",
|
|
52
|
+
"rle_pack",
|
|
53
|
+
"rle_runs",
|
|
54
|
+
"rle_unpack",
|
|
55
|
+
"rle_unpack_hex",
|
|
56
|
+
"swap_rb",
|
|
57
|
+
"swizzle",
|
|
58
|
+
"swizzle_items",
|
|
59
|
+
"unpack",
|
|
60
|
+
"unpack_nibbles",
|
|
61
|
+
"unswizzle",
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Glyph atlases: pack glyph bitmaps into one texture, write the metrics as a C header, and cut outlined cells."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Callable, Sequence
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass(frozen=True)
|
|
10
|
+
class Glyph:
|
|
11
|
+
"""One glyph bitmap: ``pixels`` is RGBA bytes, row by row, ``width * height * 4`` long (empty for a blank glyph).
|
|
12
|
+
|
|
13
|
+
``y_offset`` is where the bitmap sits against the font's top line; ``advance`` is the pen step in pixels.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
char: int
|
|
17
|
+
width: int
|
|
18
|
+
height: int
|
|
19
|
+
y_offset: int
|
|
20
|
+
advance: int
|
|
21
|
+
pixels: bytes = b""
|
|
22
|
+
|
|
23
|
+
def __post_init__(self) -> None:
|
|
24
|
+
if len(self.pixels) != self.width * self.height * 4 and not (self.width == 0 or self.height == 0):
|
|
25
|
+
raise ValueError(f"glyph {self.char}: {len(self.pixels)} bytes for {self.width}x{self.height} RGBA")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class GlyphRect:
|
|
30
|
+
"""Where a glyph went in the atlas, plus its metrics. A blank glyph has ``x = y = width = height = 0``."""
|
|
31
|
+
|
|
32
|
+
x: int
|
|
33
|
+
y: int
|
|
34
|
+
width: int
|
|
35
|
+
height: int
|
|
36
|
+
y_offset: int
|
|
37
|
+
advance: int
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def pack_glyphs(
|
|
41
|
+
sets: Sequence[Sequence[Glyph]], atlas_width: int, atlas_height: int, *, margin: int = 1
|
|
42
|
+
) -> tuple[bytearray, list[list[GlyphRect]]]:
|
|
43
|
+
"""Shelf-pack every glyph of every set into one RGBA atlas.
|
|
44
|
+
|
|
45
|
+
Glyphs go left to right in the order given, starting ``margin`` pixels in. A glyph that would reach the right edge
|
|
46
|
+
starts a new shelf below the tallest glyph of the last one, ``margin`` pixels lower. The sets share one cursor, so
|
|
47
|
+
the second set continues where the first ended. Blank glyphs take no room. Returns the atlas (``atlas_width *
|
|
48
|
+
atlas_height * 4`` bytes) and, for each set, one :class:`GlyphRect` per glyph. Raises ``ValueError`` when the atlas
|
|
49
|
+
is too small.
|
|
50
|
+
"""
|
|
51
|
+
atlas = bytearray(atlas_width * atlas_height * 4)
|
|
52
|
+
cur_x = cur_y = margin
|
|
53
|
+
shelf_h = 0
|
|
54
|
+
result: list[list[GlyphRect]] = []
|
|
55
|
+
for glyphs in sets:
|
|
56
|
+
rects: list[GlyphRect] = []
|
|
57
|
+
for g in glyphs:
|
|
58
|
+
if g.width == 0 or g.height == 0:
|
|
59
|
+
rects.append(GlyphRect(0, 0, 0, 0, g.y_offset, g.advance))
|
|
60
|
+
continue
|
|
61
|
+
if cur_x + g.width + margin >= atlas_width:
|
|
62
|
+
cur_x = margin
|
|
63
|
+
cur_y += shelf_h + margin
|
|
64
|
+
shelf_h = 0
|
|
65
|
+
if cur_y + g.height + margin >= atlas_height:
|
|
66
|
+
raise ValueError(f"glyph atlas overflowed {atlas_width}x{atlas_height}")
|
|
67
|
+
for row in range(g.height):
|
|
68
|
+
dst = ((cur_y + row) * atlas_width + cur_x) * 4
|
|
69
|
+
src = row * g.width * 4
|
|
70
|
+
atlas[dst : dst + g.width * 4] = g.pixels[src : src + g.width * 4]
|
|
71
|
+
rects.append(GlyphRect(cur_x, cur_y, g.width, g.height, g.y_offset, g.advance))
|
|
72
|
+
cur_x += g.width + margin
|
|
73
|
+
shelf_h = max(shelf_h, g.height)
|
|
74
|
+
result.append(rects)
|
|
75
|
+
return atlas, result
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def metrics_header(
|
|
79
|
+
tables: Sequence[tuple[str, Sequence[GlyphRect]]],
|
|
80
|
+
*,
|
|
81
|
+
atlas_width: int,
|
|
82
|
+
atlas_height: int,
|
|
83
|
+
first_char: int,
|
|
84
|
+
last_char: int,
|
|
85
|
+
extra_defines: Sequence[tuple[str, int]] = (),
|
|
86
|
+
guard: str = "FONT_METRICS_H",
|
|
87
|
+
define_prefix: str = "FONT_",
|
|
88
|
+
table_prefix: str = "FONT_GLYPHS_",
|
|
89
|
+
struct_name: str = "FontGlyph",
|
|
90
|
+
types: tuple[str, str, str] = ("u16", "u8", "i8"),
|
|
91
|
+
include: str | None = None,
|
|
92
|
+
banner: str = "Generated. Do not edit.",
|
|
93
|
+
) -> str:
|
|
94
|
+
"""The C header that goes with an atlas: atlas size, character range, and a ``static const`` table of glyph
|
|
95
|
+
rectangles for each ``(name, rects)`` in ``tables``.
|
|
96
|
+
|
|
97
|
+
The struct is ``{ x, y, w, h, y_off, advance }`` using the type names in ``types`` (for x and y, for w, h and
|
|
98
|
+
advance, and for y_off). Defines are ``<define_prefix>ATLAS_W``, ``ATLAS_H``, ``FIRST_CHAR``, ``LAST_CHAR`` and
|
|
99
|
+
``GLYPH_COUNT``, then ``extra_defines``; tables are named ``<table_prefix><name>``. Numbers are written with a
|
|
100
|
+
``u`` suffix, and the offset without one. Ends with a newline.
|
|
101
|
+
"""
|
|
102
|
+
t16, t8, ti8 = types
|
|
103
|
+
count = last_char - first_char + 1
|
|
104
|
+
d = define_prefix
|
|
105
|
+
lines = [f"/* {banner} */", f"#ifndef {guard}", f"#define {guard}", ""]
|
|
106
|
+
if include:
|
|
107
|
+
lines += [f'#include "{include}"', ""]
|
|
108
|
+
lines += [
|
|
109
|
+
f"#define {d}ATLAS_W {atlas_width}u",
|
|
110
|
+
f"#define {d}ATLAS_H {atlas_height}u",
|
|
111
|
+
f"#define {d}FIRST_CHAR {first_char}u",
|
|
112
|
+
f"#define {d}LAST_CHAR {last_char}u",
|
|
113
|
+
f"#define {d}GLYPH_COUNT {count}u",
|
|
114
|
+
]
|
|
115
|
+
lines += [f"#define {d}{name} {value}u" for name, value in extra_defines]
|
|
116
|
+
lines += [
|
|
117
|
+
"",
|
|
118
|
+
f"typedef struct {struct_name} {{",
|
|
119
|
+
f" {t16} x;",
|
|
120
|
+
f" {t16} y;",
|
|
121
|
+
f" {t8} w;",
|
|
122
|
+
f" {t8} h;",
|
|
123
|
+
f" {ti8} y_off;",
|
|
124
|
+
f" {t8} advance;",
|
|
125
|
+
f"}} {struct_name};",
|
|
126
|
+
"",
|
|
127
|
+
]
|
|
128
|
+
for name, rects in tables:
|
|
129
|
+
if len(rects) != count:
|
|
130
|
+
raise ValueError(f"table {name} has {len(rects)} glyphs, expected {count}")
|
|
131
|
+
lines.append(f"static const {struct_name} {table_prefix}{name}[{d}GLYPH_COUNT] = {{")
|
|
132
|
+
for r in rects:
|
|
133
|
+
lines.append(f" {{ {r.x}u, {r.y}u, {r.width}u, {r.height}u, {r.y_offset}, {r.advance}u }},")
|
|
134
|
+
lines += ["};", ""]
|
|
135
|
+
lines += ["#endif", ""]
|
|
136
|
+
return "\n".join(lines)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def outlined_cell_atlas(
|
|
140
|
+
rows_for: Callable[[int], Sequence[str]],
|
|
141
|
+
*,
|
|
142
|
+
first: int = 32,
|
|
143
|
+
last: int = 126,
|
|
144
|
+
columns: int = 16,
|
|
145
|
+
cell_width: int = 8,
|
|
146
|
+
cell_height: int = 12,
|
|
147
|
+
glyph_x: int = 1,
|
|
148
|
+
glyph_y: int = 2,
|
|
149
|
+
atlas_width: int = 128,
|
|
150
|
+
atlas_height: int = 128,
|
|
151
|
+
ink: int = 0xFFFF,
|
|
152
|
+
outline: int = 0x0000,
|
|
153
|
+
blank: int = 0,
|
|
154
|
+
) -> list[int]:
|
|
155
|
+
"""A texture of equal cells, one per character code, with each glyph outlined by one pixel all round.
|
|
156
|
+
|
|
157
|
+
``rows_for(code)`` gives the glyph as rows of ``"0"`` and ``"1"`` characters (``"1"`` is ink). Cell ``code - first``
|
|
158
|
+
sits at column ``(code - first) % columns`` and row ``(code - first) // columns``; the glyph is placed ``glyph_x``,
|
|
159
|
+
``glyph_y`` pixels into it, and the outline stays inside the cell. Pixels hold ``ink`` where the glyph is,
|
|
160
|
+
``outline`` in the 8-neighbourhood of ink and ``blank`` elsewhere: pass values already packed in the target
|
|
161
|
+
format. Returns ``atlas_width * atlas_height`` pixels, row by row.
|
|
162
|
+
"""
|
|
163
|
+
if (last - first) // columns >= atlas_height // cell_height or columns * cell_width > atlas_width:
|
|
164
|
+
raise ValueError("the cells do not fit the atlas")
|
|
165
|
+
pixels = [blank] * (atlas_width * atlas_height)
|
|
166
|
+
for code in range(first, last + 1):
|
|
167
|
+
idx = code - first
|
|
168
|
+
gx, gy = (idx % columns) * cell_width, (idx // columns) * cell_height
|
|
169
|
+
rows = rows_for(code)
|
|
170
|
+
fg = [[False] * cell_width for _ in range(cell_height)]
|
|
171
|
+
for r, line in enumerate(rows):
|
|
172
|
+
for c, ch in enumerate(line):
|
|
173
|
+
ty, tx = r + glyph_y, c + glyph_x
|
|
174
|
+
if ch == "1" and 0 <= ty < cell_height and 0 <= tx < cell_width:
|
|
175
|
+
fg[ty][tx] = True
|
|
176
|
+
for ry in range(cell_height):
|
|
177
|
+
for cx in range(cell_width):
|
|
178
|
+
if fg[ry][cx]:
|
|
179
|
+
value = ink
|
|
180
|
+
else:
|
|
181
|
+
near = any(
|
|
182
|
+
0 <= ry + dy < cell_height and 0 <= cx + dx < cell_width and fg[ry + dy][cx + dx]
|
|
183
|
+
for dy in (-1, 0, 1)
|
|
184
|
+
for dx in (-1, 0, 1)
|
|
185
|
+
)
|
|
186
|
+
value = outline if near else blank
|
|
187
|
+
pixels[(gy + ry) * atlas_width + gx + cx] = value
|
|
188
|
+
return pixels
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Block swizzle, 4-bit packing and Morton order for texture memory layouts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Sequence, TypeVar
|
|
6
|
+
|
|
7
|
+
T = TypeVar("T")
|
|
8
|
+
BLOCK_BYTES_WIDE = 16
|
|
9
|
+
BLOCK_ROWS = 8
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _check(row_bytes: int, height: int, length: int) -> None:
|
|
13
|
+
if row_bytes <= 0 or row_bytes % BLOCK_BYTES_WIDE:
|
|
14
|
+
raise ValueError(f"row size {row_bytes} bytes is not a multiple of {BLOCK_BYTES_WIDE}")
|
|
15
|
+
if height <= 0 or height % BLOCK_ROWS:
|
|
16
|
+
raise ValueError(f"height {height} is not a multiple of {BLOCK_ROWS}")
|
|
17
|
+
if length != row_bytes * height:
|
|
18
|
+
raise ValueError(f"data is {length} bytes, expected {row_bytes * height}")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def swizzle(data: bytes, row_bytes: int, height: int) -> bytes:
|
|
22
|
+
"""Reorder a linear image into 16-byte by 8-row blocks, the PSP graphics engine's texture layout.
|
|
23
|
+
|
|
24
|
+
The blocks are laid out left to right, then top to bottom; each block's rows are stored one after another.
|
|
25
|
+
``row_bytes`` is the width in bytes (``width * bits_per_pixel // 8``), a multiple of 16, and ``height`` a multiple
|
|
26
|
+
of 8. The byte at ``(x, y)`` lands at
|
|
27
|
+
``((y // 8) * (row_bytes // 16) + x // 16) * 128 + (y % 8) * 16 + x % 16``.
|
|
28
|
+
"""
|
|
29
|
+
_check(row_bytes, height, len(data))
|
|
30
|
+
blocks_per_row = row_bytes // BLOCK_BYTES_WIDE
|
|
31
|
+
out = bytearray(len(data))
|
|
32
|
+
for y in range(height):
|
|
33
|
+
base = ((y // BLOCK_ROWS) * blocks_per_row) * 128 + (y % BLOCK_ROWS) * BLOCK_BYTES_WIDE
|
|
34
|
+
row = y * row_bytes
|
|
35
|
+
for block in range(blocks_per_row):
|
|
36
|
+
src = row + block * BLOCK_BYTES_WIDE
|
|
37
|
+
dst = base + block * 128
|
|
38
|
+
out[dst : dst + BLOCK_BYTES_WIDE] = data[src : src + BLOCK_BYTES_WIDE]
|
|
39
|
+
return bytes(out)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def unswizzle(data: bytes, row_bytes: int, height: int) -> bytes:
|
|
43
|
+
"""Undo :func:`swizzle`."""
|
|
44
|
+
_check(row_bytes, height, len(data))
|
|
45
|
+
blocks_per_row = row_bytes // BLOCK_BYTES_WIDE
|
|
46
|
+
out = bytearray(len(data))
|
|
47
|
+
for y in range(height):
|
|
48
|
+
base = ((y // BLOCK_ROWS) * blocks_per_row) * 128 + (y % BLOCK_ROWS) * BLOCK_BYTES_WIDE
|
|
49
|
+
row = y * row_bytes
|
|
50
|
+
for block in range(blocks_per_row):
|
|
51
|
+
src = base + block * 128
|
|
52
|
+
dst = row + block * BLOCK_BYTES_WIDE
|
|
53
|
+
out[dst : dst + BLOCK_BYTES_WIDE] = data[src : src + BLOCK_BYTES_WIDE]
|
|
54
|
+
return bytes(out)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def swizzle_items(items: Sequence[T], width: int, height: int, *, block_width: int = 8, block_height: int = 8) -> list[T]:
|
|
58
|
+
"""The same reordering for a list of whole pixels (any value), with the block measured in pixels.
|
|
59
|
+
|
|
60
|
+
The default 8 by 8 block is the layout for 16-bit pixels (8 pixels of 2 bytes make a 16-byte row), so for
|
|
61
|
+
those ``swizzle_items(pixels, w, h)`` equals :func:`swizzle` on their bytes. Use ``block_width=16`` for 8-bit
|
|
62
|
+
pixels and ``4`` for 32-bit ones.
|
|
63
|
+
"""
|
|
64
|
+
if width % block_width or height % block_height:
|
|
65
|
+
raise ValueError("width and height must be whole numbers of blocks")
|
|
66
|
+
if len(items) != width * height:
|
|
67
|
+
raise ValueError(f"expected {width * height} pixels, got {len(items)}")
|
|
68
|
+
out: list[T] = []
|
|
69
|
+
for tile_y in range(0, height, block_height):
|
|
70
|
+
for tile_x in range(0, width, block_width):
|
|
71
|
+
for row in range(tile_y, tile_y + block_height):
|
|
72
|
+
start = row * width + tile_x
|
|
73
|
+
out.extend(items[start : start + block_width])
|
|
74
|
+
return out
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def pack_nibbles(indices: Sequence[int]) -> bytes:
|
|
78
|
+
"""Pack 4-bit indices two to a byte, the first index in the low nibble. The count must be even."""
|
|
79
|
+
if len(indices) % 2:
|
|
80
|
+
raise ValueError("an odd number of 4-bit indices")
|
|
81
|
+
out = bytearray(len(indices) // 2)
|
|
82
|
+
for i in range(0, len(indices), 2):
|
|
83
|
+
lo, hi = indices[i], indices[i + 1]
|
|
84
|
+
if not (0 <= lo < 16 and 0 <= hi < 16):
|
|
85
|
+
raise ValueError("a 4-bit index is outside 0..15")
|
|
86
|
+
out[i // 2] = lo | (hi << 4)
|
|
87
|
+
return bytes(out)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def unpack_nibbles(data: bytes) -> list[int]:
|
|
91
|
+
"""Undo :func:`pack_nibbles`."""
|
|
92
|
+
out: list[int] = []
|
|
93
|
+
for byte in data:
|
|
94
|
+
out.append(byte & 0xF)
|
|
95
|
+
out.append(byte >> 4)
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def morton_index(x: int, y: int, bits: int) -> int:
|
|
100
|
+
"""Interleave the low ``bits`` bits of ``x`` and ``y`` (y in the even positions, x in the odd ones): the
|
|
101
|
+
twiddled order Dreamcast PowerVR textures are stored in."""
|
|
102
|
+
if x < 0 or y < 0 or x >> bits or y >> bits:
|
|
103
|
+
raise ValueError("coordinate does not fit in the bit count")
|
|
104
|
+
return sum((((x >> b) & 1) << (2 * b + 1)) | (((y >> b) & 1) << (2 * b)) for b in range(bits))
|
|
105
|
+
|