-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtual_vram.py
More file actions
48 lines (36 loc) · 1.5 KB
/
Copy pathvirtual_vram.py
File metadata and controls
48 lines (36 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Author: Luca De Stefani
# virtual_vram.py
import numpy as np
class VirtualVRAM:
"""
Carica in memoria il tile sheet e lo sprite sheet.
I file sono salvati in formato packed: ogni byte contiene due pixel da 4 bit.
"""
SHEET_SIZE = 256
EXPECTED_BYTES = (SHEET_SIZE * SHEET_SIZE) // 2
def __init__(self, tiles_path, sprites_path):
# Carico entrambi gli sheet già decodificati in matrici 256x256.
self.tile_sheet = self._load_sheet(tiles_path)
self.sprite_sheet = self._load_sheet(sprites_path)
def _load_sheet(self, path):
"""
Legge un file binario packed e lo trasforma in una matrice 256x256.
Ogni byte contiene due pixel:
- nibble alto: primo pixel
- nibble basso: secondo pixel
"""
with open(path, "rb") as file:
raw_data = file.read()
if len(raw_data) != self.EXPECTED_BYTES:
raise ValueError(
f"Il file {path} deve essere grande esattamente {self.EXPECTED_BYTES} byte."
)
packed = np.frombuffer(raw_data, dtype=np.uint8)
# Estraggo i 4 bit alti e i 4 bit bassi da ogni byte.
high_nibble = packed >> 4
low_nibble = packed & 0x0F
# Ricompongo i pixel nell'ordine corretto: alto, basso, alto, basso...
pixels = np.empty(self.SHEET_SIZE * self.SHEET_SIZE, dtype=np.uint8)
pixels[0::2] = high_nibble
pixels[1::2] = low_nibble
return pixels.reshape((self.SHEET_SIZE, self.SHEET_SIZE))