Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / voxels / build_atlas.py

build_atlas.py458 lines · 19.0 KiBRaw
1#!/usr/bin/env python3
2"""Build the voxels block-texture atlas (raw RGBA) from a Minecraft-style texture pack.
3
4The runtime loads `games/voxels/src/main/rust/shaders/atlas.bin` as a raw RGBA buffer of
5ATLAS_W*ATLAS_H*4 bytes, laid out as COLS x ROWS tiles of TILE px each. Tile index i lives at
6column i%COLS, row i//COLS (matching block.frag / block.rs tile_uv). No PIL: we decode PNGs with a
7small pure-Python decoder (zlib is stdlib).
8
9Existing tiles (0..63) are preserved by copying them out of the current atlas.bin so their pixels are
10byte-identical; only the layout stride changes (8 cols -> 16 cols) with the tile INDEX kept the same.
11New tiles are decoded from the pack. Referenced PNGs are also copied into assets/block/ for the
12Compose hotbar icons.
13"""
14import os, struct, zlib, shutil
15
16ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
17PACK = os.path.join(ROOT, "tmp/Matcha_Flavoured/assets/minecraft/textures/block")
18PACK_ITEM = os.path.join(ROOT, "tmp/Matcha_Flavoured/assets/minecraft/textures/item")
19ATLAS_BIN = os.path.join(ROOT, "games/voxels/src/main/rust/shaders/atlas.bin")
20ASSETS = os.path.join(ROOT, "games/voxels/src/main/assets/block")
21
22TILE = 16
23OLD_COLS = 8
24NEW_COLS = 16
25NEW_ROWS = 16
26NEW_W = NEW_COLS * TILE
27NEW_H = NEW_ROWS * TILE
28
29# New tiles: atlas index -> source PNG filename in the pack. Indices 0..63 are copied from the old
30# atlas untouched; new blocks start at 64.
31NEW_TILES = {
32 144: "suspicious_sand_0.png",
33 145: "wheat_stage7_top.png",
34 146: "carrots_stage3.png",
35 147: "melon_stem_stage7.png",
36 64: "red_sand.png",
37 65: "red_sandstone.png",
38 66: "red_sandstone_top.png",
39 67: "sandstone.png",
40 68: "sandstone_top.png",
41 69: "sandstone_bottom.png",
42 70: "podzol_top.png",
43 71: "podzol_side.png",
44 72: "coarse_dirt.png",
45 73: "mycelium_side.png",
46 74: "packed_ice.png",
47 75: "ice.png",
48 76: "blue_ice.png",
49 77: "mud.png",
50 78: "rooted_dirt.png",
51 79: "dark_oak_log.png",
52 80: "dark_oak_log_top.png",
53 81: "dark_oak_leaves.png",
54 82: "dark_oak_planks.png",
55 83: "acacia_log.png",
56 84: "acacia_log_top.png",
57 85: "jungle_log.png",
58 86: "jungle_log_top.png",
59 87: "jungle_planks.png",
60 88: "granite_bricks.png",
61 89: "deepslate_bricks.png",
62 90: "nether_bricks.png",
63 91: "end_stone_bricks.png",
64 92: "cobbled_deepslate.png",
65 93: "hay_block_side.png",
66 94: "hay_block_top.png",
67 95: "farmland.png",
68 96: "packed_dirt.png",
69 116: "azalea_leaves.png",
70 133: "netherite_block.png",
71}
72
73# Procedurally generated tiles (index -> base RGB) for blocks the pack lacks textures for (coral,
74# cave, and ocean specials). Each is a solid colour with light deterministic speckle so it reads as a
75# textured block rather than a flat swatch.
76PROC_TILES = {
77 143: (236, 238, 234), # wool (soft off-white; the pack never retextures it)
78 97: (52, 90, 235), # tube coral (blue)
79 98: (240, 116, 168), # brain coral (pink)
80 99: (178, 52, 216), # bubble coral (purple)
81 100: (228, 54, 62), # fire coral (red)
82 101: (240, 214, 66), # horn coral (yellow)
83 102: (46, 112, 48), # kelp (green)
84 103: (204, 240, 228), # sea lantern (bright cyan-white)
85 104: (92, 158, 152), # prismarine (teal)
86 105: (44, 82, 76), # dark prismarine
87 106: (140, 108, 92), # dripstone (tan-brown)
88 107: (82, 128, 52), # moss block (green)
89 108: (18, 34, 44), # sculk (dark blue-black)
90 109: (154, 116, 216), # amethyst (purple)
91 110: (230, 230, 222), # calcite (near white)
92 111: (108, 112, 102), # tuff (gray)
93 112: (140, 46, 20), # magma (dark orange-red)
94 113: (242, 204, 90), # glowstone (yellow)
95 114: (26, 16, 40), # obsidian (near-black purple)
96 115: (158, 166, 178), # clay (light gray-blue)
97 117: (86, 214, 190), # warding stone (glowing teal checkpoint)
98 118: (74, 50, 30), # jukebox (dark wood box)
99 119: (139, 94, 52), # chest (brown wood)
100 120: (214, 92, 24), # lava (glowing orange)
101 121: (222, 226, 165), # end stone (pale)
102 122: (146, 52, 214), # nether portal (purple)
103 123: (36, 18, 66), # end portal (dark starry)
104 124: (150, 236, 240), # beacon (bright glowing cyan)
105 125: (170, 116, 172), # purpur (muted purple)
106 126: (214, 66, 66), # firework rocket icon (red) — item only, tile unused by any block
107 127: (226, 238, 250), # snowball icon (near-white) — item only
108 131: (198, 202, 214), # silver block (pale metal)
109 132: (86, 92, 104), # steel block (blue-gray)
110 134: (58, 54, 62), # blast furnace top (dark iron)
111 135: (44, 42, 48), # blast furnace side
112 138: (204, 118, 66), # copper block
113 139: (246, 208, 62), # gold block
114 140: (176, 141, 87), # bronze block
115 141: (188, 192, 198), # stonecutter top (saw blade steel)
116 142: (112, 110, 106), # stonecutter side (stone body)
117}
118
119# Ore tiles: a stone/netherrack base with deterministic mineral blobs speckled over it, so new ores
120# read like the pack's real ore textures rather than a flat colour.
121# index -> (base tile index, mineral rgb, blob seed)
122ORE_TILES = {
123 128: (0, (214, 220, 232), 0x511E), # silver ore in stone
124 129: (37, (238, 214, 62), 0x5F1F), # sulfur ore in netherrack
125 130: (37, (196, 40, 44), 0xC14B), # cinnabar ore in netherrack
126 136: (0, (216, 130, 78), 0xC099), # copper ore in stone
127 137: (0, (250, 214, 76), 0x901D), # gold ore in stone
128}
129
130# Blocks and items whose icon comes straight from a pack PNG. dest filename -> (subdir, source).
131COPY_ICONS = {
132 "adamant_block.png": ("block", "netherite_block.png"),
133 "adamant_ingot.png": ("item", "netherite_ingot.png"),
134 "adamant_pickaxe.png": ("item", "adamant_mattock.png"),
135 "adamant_sword.png": ("item", "adamant_claymore.png"),
136 "adamant_helmet.png": ("item", "netherite_helmet.png"),
137 "adamant_chestplate.png": ("item", "netherite_chestplate.png"),
138 "adamant_leggings.png": ("item", "netherite_leggings.png"),
139 "adamant_boots.png": ("item", "netherite_boots.png"),
140 "silver_ingot.png": ("item", "prismarine_crystals.png"),
141 "shears.png": ("item", "shears.png"),
142 "raw_fish.png": ("item", "catfish.png"),
143 "brush.png": ("item", "archaeologists_brush.png"),
144 "wheat.png": ("item", "wheat.png"),
145 "wheat_seeds.png": ("item", "wheat_seeds.png"),
146 "quicksilver.png": ("item", "prismarine_shard.png"),
147 # The blessing pantheon. Items only: a blessing is never placed as a block, so no atlas tile.
148 **{f"blessing_{n}.png": ("item", f"blessing_{n}.png") for n in (
149 "aeolus", "apollo", "arachnae", "ares", "artemis", "clement", "cronus", "daedalus",
150 "demeter", "eros", "glaucus", "god_king", "hyacinthus", "icarus", "lu_ban", "paris",
151 "prometheus", "talos", "warding", "will", "yama", "yamm",
152 )},
153 # Matcha's bronze tier, between iron and diamond.
154 "copper_ingot.png": ("item", "copper_ingot.png"),
155 "gold_ingot.png": ("item", "gold_ingot.png"),
156 **{f"bronze_{n}.png": ("item", f"bronze_{n}.png") for n in (
157 "pickaxe", "sword", "helmet", "chestplate", "leggings", "boots",
158 )},
159 # Matcha's cooked dishes.
160 "cooked_meat.png": ("item", "porkchop_classic.png"),
161 **{f"{n}.png": ("item", f"{n}.png") for n in (
162 "ramen", "japanese_curry", "green_curry", "gnocchi", "naan", "pupusa", "latke",
163 "bruschetta", "french_toast", "sweet_berry_danish", "melon_sorbet", "stroganoff",
164 )},
165}
166
167# New blessings have no Matcha artwork, so they borrow a charm silhouette from an existing one and
168# recolour it. dest -> (source blessing png, rgb multiplier).
169TINT_ICONS = {
170 "blessing_athena.png": ("blessing_warding.png", (0.72, 0.86, 1.25)),
171 "blessing_sekhmet.png": ("blessing_ares.png", (1.30, 0.52, 0.48)),
172 "blessing_camazotz.png": ("blessing_glaucus.png", (1.25, 0.45, 0.62)),
173 "blessing_tangaroa.png": ("blessing_yamm.png", (0.55, 1.15, 1.10)),
174 "blessing_anubis.png": ("blessing_prometheus.png", (1.20, 0.98, 0.42)),
175 # No fishing rod in the pack; a blaze rod browned down reads as a wooden one.
176 "fishing_rod.png": ("blaze_rod.png", (0.62, 0.46, 0.30)),
177}
178
179# Item-only icons with no atlas tile (items are never placed as blocks). filename -> base rgb.
180PROC_ITEM_ICON = {
181 "sulfur.png": (238, 214, 62),
182 "steel_ingot.png": (118, 126, 140),
183 "raw_meat.png": (214, 108, 116), # the pack leaves raw meat vanilla, so make our own
184 "bronze_ingot.png": (176, 141, 87),
185}
186
187
188# Asset filenames for the procedural tiles so the Compose hotbar has matching icons.
189PROC_ICON = {
190 97: "tube_coral.png", 98: "brain_coral.png", 99: "bubble_coral.png", 100: "fire_coral.png",
191 101: "horn_coral.png", 102: "kelp.png", 103: "sea_lantern.png", 104: "prismarine.png",
192 105: "dark_prismarine.png", 106: "dripstone.png", 107: "moss_block.png", 108: "sculk.png",
193 109: "amethyst.png", 110: "calcite.png", 111: "tuff.png", 112: "magma.png", 113: "glowstone.png",
194 114: "obsidian.png", 115: "clay.png", 117: "warding_stone.png", 118: "jukebox.png", 119: "chest.png",
195 120: "lava.png", 121: "end_stone.png", 124: "beacon.png", 125: "purpur_block.png", 126: "firework_rocket.png", 127: "snowball.png",
196 128: "silver_ore.png", 129: "sulfur_ore.png", 130: "cinnabar_ore.png",
197 131: "silver_block.png", 132: "steel_block.png", 134: "blast_furnace.png",
198 136: "copper_ore.png", 137: "gold_ore.png",
199 138: "copper_block.png", 139: "gold_block.png", 140: "bronze_block.png",
200 141: "stonecutter.png",
201 143: "wool.png",
202 144: "suspicious_sand.png",
203 145: "wheat_crop.png",
204 146: "carrot_crop.png",
205 147: "melon_crop.png",
206}
207
208
209def write_png(path, w, h, rgba):
210 def chunk(typ, data):
211 c = typ + data
212 return struct.pack(">I", len(data)) + c + struct.pack(">I", zlib.crc32(c) & 0xffffffff)
213 raw = bytearray()
214 for y in range(h):
215 raw.append(0) # filter: none
216 raw += rgba[y*w*4:(y+1)*w*4]
217 ihdr = struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)
218 out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw))) + chunk(b"IEND", b"")
219 open(path, "wb").write(out)
220
221
222def make_proc_tile(rgb):
223 """A 16x16 RGBA solid tile with deterministic per-pixel brightness speckle for texture."""
224 r, g, b = rgb
225 out = bytearray(TILE * TILE * 4)
226 for y in range(TILE):
227 for x in range(TILE):
228 # cheap hash noise in [-18, 18]
229 hh = (x * 374761393 + y * 668265263) & 0xFFFFFFFF
230 hh = (hh ^ (hh >> 13)) * 1274126177 & 0xFFFFFFFF
231 n = (hh % 37) - 18
232 o = (y * TILE + x) * 4
233 out[o] = max(0, min(255, r + n))
234 out[o+1] = max(0, min(255, g + n))
235 out[o+2] = max(0, min(255, b + n))
236 out[o+3] = 255
237 return out
238
239
240def read_tile(atlas, tile_index):
241 """Copy a 16x16 RGBA tile out of the packed atlas."""
242 col, row = tile_index % NEW_COLS, tile_index // NEW_COLS
243 out = bytearray(TILE * TILE * 4)
244 for ty in range(TILE):
245 s = ((row * TILE + ty) * NEW_W + col * TILE) * 4
246 out[ty*TILE*4:(ty+1)*TILE*4] = atlas[s:s + TILE*4]
247 return out
248
249
250def make_ore_tile(base, rgb, seed):
251 """Speckle mineral blobs over a base stone tile so it reads as an ore vein."""
252 out = bytearray(base)
253 r, g, b = rgb
254 h = seed & 0xFFFFFFFF
255 def rnd(limit):
256 nonlocal h
257 h = (h * 1103515245 + 12345) & 0x7FFFFFFF
258 return h % limit
259 for _ in range(8):
260 cx, cy, rad = rnd(TILE), rnd(TILE), 1 + rnd(2)
261 for y in range(cy - rad, cy + rad + 1):
262 for x in range(cx - rad, cx + rad + 1):
263 if not (0 <= x < TILE and 0 <= y < TILE): continue
264 if (x - cx) ** 2 + (y - cy) ** 2 > rad * rad: continue
265 # Keep the base tile's own luminance variation so the ore isn't a flat blob.
266 o = (y * TILE + x) * 4
267 shade = (base[o] + base[o+1] + base[o+2]) / 765.0 * 0.4 + 0.8
268 out[o] = max(0, min(255, int(r * shade)))
269 out[o+1] = max(0, min(255, int(g * shade)))
270 out[o+2] = max(0, min(255, int(b * shade)))
271 out[o+3] = 255
272 return out
273
274
275def _paeth(a, b, c):
276 p = a + b - c
277 pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
278 if pa <= pb and pa <= pc: return a
279 if pb <= pc: return b
280 return c
281
282
283def decode_png(path):
284 """Return (w, h, rgba_bytes). Supports 8-bit gray/RGB/RGBA and 4/8-bit palette, with tRNS."""
285 data = open(path, "rb").read()
286 assert data[:8] == b"\x89PNG\r\n\x1a\n", "not a png: " + path
287 pos = 8
288 w = h = bd = ct = None
289 idat = bytearray()
290 plte = None
291 trns = None
292 while pos < len(data):
293 (ln,) = struct.unpack(">I", data[pos:pos+4])
294 typ = data[pos+4:pos+8]
295 chunk = data[pos+8:pos+8+ln]
296 if typ == b"IHDR":
297 w, h, bd, ct = struct.unpack(">IIBB", chunk[:10])
298 elif typ == b"PLTE":
299 plte = chunk
300 elif typ == b"tRNS":
301 trns = chunk
302 elif typ == b"IDAT":
303 idat += chunk
304 elif typ == b"IEND":
305 break
306 pos += 12 + ln
307
308 raw = zlib.decompress(bytes(idat))
309 if ct == 0: channels = 1
310 elif ct == 2: channels = 3
311 elif ct == 3: channels = 1
312 elif ct == 4: channels = 2
313 elif ct == 6: channels = 4
314 else: raise ValueError("unsupported color type %d in %s" % (ct, path))
315
316 bits_per_pixel = channels * bd
317 bpp = max(1, (bits_per_pixel + 7) // 8) # filter byte offset
318 stride = (w * bits_per_pixel + 7) // 8 # bytes per scanline (no filter byte)
319
320 # Unfilter.
321 out = bytearray(h * stride)
322 prev = bytearray(stride)
323 p = 0
324 for y in range(h):
325 f = raw[p]; p += 1
326 line = bytearray(raw[p:p+stride]); p += stride
327 if f == 1:
328 for i in range(bpp, stride): line[i] = (line[i] + line[i-bpp]) & 255
329 elif f == 2:
330 for i in range(stride): line[i] = (line[i] + prev[i]) & 255
331 elif f == 3:
332 for i in range(stride):
333 a = line[i-bpp] if i >= bpp else 0
334 line[i] = (line[i] + ((a + prev[i]) >> 1)) & 255
335 elif f == 4:
336 for i in range(stride):
337 a = line[i-bpp] if i >= bpp else 0
338 c = prev[i-bpp] if i >= bpp else 0
339 line[i] = (line[i] + _paeth(a, prev[i], c)) & 255
340 out[y*stride:(y+1)*stride] = line
341 prev = line
342
343 # Expand to RGBA.
344 rgba = bytearray(w * h * 4)
345 def pal(idx):
346 r, g, b = plte[idx*3], plte[idx*3+1], plte[idx*3+2]
347 a = trns[idx] if (trns and idx < len(trns)) else 255
348 return r, g, b, a
349 for y in range(h):
350 for x in range(w):
351 o = (y*w + x) * 4
352 if ct == 6:
353 s = y*stride + x*4
354 rgba[o:o+4] = out[s:s+4]
355 elif ct == 2:
356 s = y*stride + x*3
357 rgba[o] = out[s]; rgba[o+1] = out[s+1]; rgba[o+2] = out[s+2]; rgba[o+3] = 255
358 elif ct == 0:
359 g = out[y*stride + x]
360 rgba[o] = g; rgba[o+1] = g; rgba[o+2] = g; rgba[o+3] = 255
361 elif ct == 4:
362 s = y*stride + x*2
363 g, a = out[s], out[s+1]
364 rgba[o] = g; rgba[o+1] = g; rgba[o+2] = g; rgba[o+3] = a
365 elif ct == 3:
366 if bd == 8:
367 idx = out[y*stride + x]
368 elif bd == 4:
369 byte = out[y*stride + (x >> 1)]
370 idx = (byte >> 4) if (x & 1) == 0 else (byte & 0xF)
371 else:
372 raise ValueError("palette bd %d unsupported" % bd)
373 r, g, b, a = pal(idx)
374 rgba[o] = r; rgba[o+1] = g; rgba[o+2] = b; rgba[o+3] = a
375 return w, h, rgba
376
377
378def blit(dst, dst_w, tile_index, cols, src_rgba, src_w):
379 col = tile_index % cols
380 row = tile_index // cols
381 x0 = col * TILE
382 y0 = row * TILE
383 for ty in range(TILE):
384 for tx in range(TILE):
385 s = (ty * src_w + tx) * 4 # src is at least TILE wide; use first 16x16 of animated strips
386 d = ((y0 + ty) * dst_w + (x0 + tx)) * 4
387 dst[d:d+4] = src_rgba[s:s+4]
388
389
390def main():
391 raw = open(ATLAS_BIN, "rb").read()
392 if len(raw) == NEW_W * NEW_H * 4:
393 # Already expanded: keep every existing tile, only (re)write the new ones below.
394 new = bytearray(raw)
395 elif len(raw) == (OLD_COLS * TILE) * (OLD_COLS * TILE) * 4:
396 # Migrate the original 8x8 atlas into the 16x16 layout, preserving tile INDEX.
397 old_w = OLD_COLS * TILE
398 new = bytearray(NEW_W * NEW_H * 4)
399 for i in range(OLD_COLS * OLD_COLS):
400 oc, orow = i % OLD_COLS, i // OLD_COLS
401 tile = bytearray(TILE * TILE * 4)
402 for ty in range(TILE):
403 for tx in range(TILE):
404 s = ((orow*TILE + ty) * old_w + (oc*TILE + tx)) * 4
405 tile[(ty*TILE + tx)*4:(ty*TILE + tx)*4+4] = old[s:s+4]
406 blit(new, NEW_W, i, NEW_COLS, tile, TILE)
407 else:
408 raise SystemExit("unexpected atlas.bin size %d" % len(raw))
409
410 os.makedirs(ASSETS, exist_ok=True)
411 # Icons that COPY_ICONS renames are skipped here so the pack filename isn't also left behind.
412 renamed = {src for _, src in COPY_ICONS.values()}
413 for idx, fname in sorted(NEW_TILES.items()):
414 src = os.path.join(PACK, fname)
415 w, h, rgba = decode_png(src)
416 blit(new, NEW_W, idx, NEW_COLS, rgba, w)
417 if fname not in renamed:
418 shutil.copyfile(src, os.path.join(ASSETS, fname))
419 print("tile %3d <- %s (%dx%d)" % (idx, fname, w, h))
420
421 for idx, rgb in sorted(PROC_TILES.items()):
422 tile = make_proc_tile(rgb)
423 blit(new, NEW_W, idx, NEW_COLS, tile, TILE)
424 if idx in PROC_ICON:
425 write_png(os.path.join(ASSETS, PROC_ICON[idx]), TILE, TILE, tile)
426 print("tile %3d <- proc %s" % (idx, rgb))
427
428 for idx, (base_idx, rgb, seed) in sorted(ORE_TILES.items()):
429 tile = make_ore_tile(read_tile(new, base_idx), rgb, seed)
430 blit(new, NEW_W, idx, NEW_COLS, tile, TILE)
431 if idx in PROC_ICON:
432 write_png(os.path.join(ASSETS, PROC_ICON[idx]), TILE, TILE, tile)
433 print("tile %3d <- ore over tile %d %s" % (idx, base_idx, rgb))
434
435 for name, rgb in sorted(PROC_ITEM_ICON.items()):
436 write_png(os.path.join(ASSETS, name), TILE, TILE, make_proc_tile(rgb))
437 print("icon %s <- proc %s" % (name, rgb))
438
439 for dest, (subdir, src_name) in sorted(COPY_ICONS.items()):
440 src = os.path.join(PACK if subdir == "block" else PACK_ITEM, src_name)
441 shutil.copyfile(src, os.path.join(ASSETS, dest))
442 print("icon %s <- %s/%s" % (dest, subdir, src_name))
443
444 for dest, (src_name, mul) in sorted(TINT_ICONS.items()):
445 w, h, rgba = decode_png(os.path.join(PACK_ITEM, src_name))
446 out = bytearray(rgba)
447 for i in range(0, len(out), 4):
448 for c in range(3):
449 out[i + c] = min(255, int(out[i + c] * mul[c]))
450 write_png(os.path.join(ASSETS, dest), w, h, bytes(out))
451 print("icon %s <- %s tinted %s" % (dest, src_name, mul))
452
453 open(ATLAS_BIN, "wb").write(new)
454 print("wrote %s (%dx%d, %d bytes)" % (ATLAS_BIN, NEW_W, NEW_H, len(new)))
455
456
457if __name__ == "__main__":
458 main()