From 6c26e2617c8cabdb8e05ca0f7180123a169b13a2 Mon Sep 17 00:00:00 2001 From: Rangi Date: Sun, 18 Sep 2022 23:08:43 -0400 Subject: [PATCH] Update and add more tool scripts --- tools/free_space.py | 38 ++++---- tools/mapreader.py | 1 - tools/palfix.py | 27 +++--- tools/rgb555.py | 38 ++++++++ tools/sym_comments.py | 71 +++++++-------- tools/toc.py | 47 +++++----- tools/unique.py | 106 +++++++++++++++++++++++ tools/unnamed.py | 196 ++++++++++++++++++++++-------------------- tools/used_space.py | 30 +++---- 9 files changed, 355 insertions(+), 199 deletions(-) create mode 100755 tools/rgb555.py create mode 100755 tools/unique.py diff --git a/tools/free_space.py b/tools/free_space.py index b6847e8ea..6d4ac00c4 100755 --- a/tools/free_space.py +++ b/tools/free_space.py @@ -17,24 +17,23 @@ from mapreader import MapReader def main(): print_bank = 'none' - mapfile = 'pokecrystal.map' + filename = 'pokecrystal.map' for arg in sys.argv[1:]: if arg.startswith('BANK='): print_bank = arg.split('=', 1)[-1] else: - mapfile = arg + filename = arg if print_bank not in {'all', 'none'}: try: - if print_bank.startswith('0x') or print_bank.startswith('0X'): - print_bank = int(print_bank[2:], 16) - else: - print_bank = int(print_bank) + print_bank = (int(print_bank[2:], 16) + if print_bank.startswith('0x') or print_bank.startswith('0X') + else int(print_bank)) except ValueError: - error = 'Error: invalid BANK: %s' % print_bank + error = f'Error: invalid BANK: {print_bank}' if print_bank.isalnum(): - error += ' (did you mean: 0x%s?)' % print_bank + error += f' (did you mean: 0x{print_bank}?)' print(error, file=sys.stderr) sys.exit(1) @@ -42,30 +41,29 @@ def main(): bank_size = 0x4000 # bytes total_size = num_banks * bank_size - r = MapReader() - with open(mapfile, 'r', encoding='utf-8') as f: - l = f.readlines() - r.read_map_data(l) + reader = MapReader() + with open(filename, 'r', encoding='utf-8') as file: + reader.read_map_data(file.readlines()) free_space = 0 per_bank = [] default_bank_data = {'sections': [], 'used': 0, 'slack': bank_size} for bank in range(num_banks): - bank_data = r.bank_data['ROM0 bank'] if bank == 0 else r.bank_data['ROMX bank'] + bank_data = reader.bank_data['ROM0 bank' if bank == 0 else 'ROMX bank'] data = bank_data.get(bank, default_bank_data) - used = data['used'] - slack = data['slack'] + used, slack = data['used'], data['slack'] per_bank.append((used, slack)) free_space += slack - print('Free space: %d/%d (%.2f%%)' % (free_space, total_size, free_space * 100.0 / total_size)) + free_percent = 100 * free_space / total_size + print(f'Free space: {free_space}/{total_size} ({free_percent:.2f}%)') if print_bank != 'none': print() print('bank, used, free') - for bank in range(num_banks): - used, slack = per_bank[bank] - if print_bank in {'all', bank}: - print('$%02X, %d, %d' % (bank, used, slack)) + for bank in range(num_banks): + used, slack = per_bank[bank] + if print_bank in {'all', bank}: + print(f'${bank:02X}, {used}, {slack}') if __name__ == '__main__': main() diff --git a/tools/mapreader.py b/tools/mapreader.py index 42eaa76de..de2ec3423 100644 --- a/tools/mapreader.py +++ b/tools/mapreader.py @@ -1,4 +1,3 @@ -#!/usr/bin/env python3 # -*- coding: utf-8 -*- # A library for parsing the pokecrystal.map file output by rgbds. diff --git a/tools/palfix.py b/tools/palfix.py index 2ecd3236d..a0b431da7 100755 --- a/tools/palfix.py +++ b/tools/palfix.py @@ -30,15 +30,18 @@ def luminance(c): return 0.299 * r**2 + 0.587 * g**2 + 0.114 * b**2 def rgb5_pixels(row): - for x in range(0, len(row), 4): - yield rgb8_to_rgb5(row[x:x+3]) + yield from (rgb8_to_rgb5(row[x:x+3]) for x in range(0, len(row), 4)) + +def is_grayscale(palette): + return (palette == ((31, 31, 31), (21, 21, 21), (10, 10, 10), (0, 0, 0)) or + palette == ((31, 31, 31), (20, 20, 20), (10, 10, 10), (0, 0, 0))) def fix_pal(filename): with open(filename, 'rb') as file: - width, height, data = png.Reader(file).asRGBA8()[:3] - data = list(data) + width, height, rows = png.Reader(file).asRGBA8()[:3] + rows = list(rows) b_and_w = {(0, 0, 0), (31, 31, 31)} - colors = set(c for row in data for c in rgb5_pixels(row)) - b_and_w + colors = {c for row in rows for c in rgb5_pixels(row)} - b_and_w if not colors: colors = {(21, 21, 21), (10, 10, 10)} elif len(colors) == 1: @@ -48,26 +51,26 @@ def fix_pal(filename): return False palette = tuple(sorted(colors | b_and_w, key=luminance, reverse=True)) assert len(palette) == 4 - data = [list(map(palette.index, rgb5_pixels(row))) for row in data] - if palette == ((31, 31, 31), (21, 21, 21), (10, 10, 10), (0, 0, 0)): - data = [[3 - c for c in row] for row in data] + rows = [list(map(palette.index, rgb5_pixels(row))) for row in rows] + if is_grayscale(palette): + rows = [[3 - c for c in row] for row in rows] writer = png.Writer(width, height, greyscale=True, bitdepth=2, compression=9) else: palette = tuple(map(rgb5_to_rgb8, palette)) writer = png.Writer(width, height, palette=palette, bitdepth=8, compression=9) with open(filename, 'wb') as file: - writer.write(file, data) + writer.write(file, rows) return True def main(): if len(sys.argv) < 2: - print('Usage:', sys.argv[0], 'pic.png', file=sys.stderr) + print(f'Usage: {sys.argv[0]} pic.png', file=sys.stderr) sys.exit(1) for filename in sys.argv[1:]: if not filename.lower().endswith('.png'): - print(filename, 'is not a .png file!', file=sys.stderr) + print(f'{filename} is not a .png file!', file=sys.stderr) elif not fix_pal(filename): - print(filename, 'has too many colors!', file=sys.stderr) + print(f'{filename} has too many colors!', file=sys.stderr) if __name__ == '__main__': main() diff --git a/tools/rgb555.py b/tools/rgb555.py new file mode 100755 index 000000000..bf650313b --- /dev/null +++ b/tools/rgb555.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Usage: python rgb555.py image.png + +Round all colors of the input image to RGB555. +""" + +import sys + +import png + +def rgb8_to_rgb5(c): + return (c & 0b11111000) | (c >> 5) + +def round_pal(filename): + with open(filename, 'rb') as file: + width, height, rows = png.Reader(file).asRGBA8()[:3] + rows = list(rows) + for row in rows: + del row[3::4] + rows = [[rgb8_to_rgb5(c) for c in row] for row in rows] + writer = png.Writer(width, height, greyscale=False, bitdepth=8, compression=9) + with open(filename, 'wb') as file: + writer.write(file, rows) + +def main(): + if len(sys.argv) < 2: + print(f'Usage: {sys.argv[0]} pic.png', file=sys.stderr) + sys.exit(1) + for filename in sys.argv[1:]: + if not filename.lower().endswith('.png'): + print(f'{filename} is not a .png file!', file=sys.stderr) + round_pal(filename) + +if __name__ == '__main__': + main() diff --git a/tools/sym_comments.py b/tools/sym_comments.py index 27d37ca23..af0a93602 100755 --- a/tools/sym_comments.py +++ b/tools/sym_comments.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- """ -Usage: python3 sym_comments.py file.asm [pokecrystal.sym] > file_commented.asm +Usage: python sym_comments.py file.asm [pokecrystal.sym] > file_commented.asm Comments each label in file.asm with its bank:address from the sym file. """ @@ -10,40 +10,43 @@ Comments each label in file.asm with its bank:address from the sym file. import sys import re -if len(sys.argv) != 2 and len(sys.argv) != 3: - print('Usage: %s file.asm [pokecrystal.sym] > file_commented.asm' % sys.argv[0], file=sys.stderr) +def main(): + if len(sys.argv) not in {2, 3}: + print(f'Usage: {sys.argv[0]} file.asm [pokecrystal.sym] > file_commented.asm', file=sys.stderr) + sys.exit(1) -wram_name = sys.argv[1] -sym_name = sys.argv[2] if len(sys.argv) == 3 else 'pokecrystal.sym' + wram_name = sys.argv[1] + sym_name = sys.argv[2] if len(sys.argv) == 3 else 'pokecrystal.sym' -sym_format = r'[A-Za-z_][A-Za-z0-9_#@]*' -sym_def_rx = re.compile(r'(^%s)(:.*)|(^\.%s)(.*)' % (sym_format, sym_format)) + sym_def_rx = re.compile(r'(^{sym})(:.*)|(^\.{sym})(.*)'.format(sym=r'[A-Za-z_][A-Za-z0-9_#@]*')) -sym_addrs = {} -with open(sym_name, 'r', encoding='utf-8') as f: - for line in f: - line = line.split(';', 1)[0].rstrip() - parts = line.split(' ', 1) - if len(parts) != 2: - continue - addr, sym = parts - sym_addrs[sym] = addr + sym_addrs = {} + with open(sym_name, 'r', encoding='utf-8') as file: + for line in file: + line = line.split(';', 1)[0].rstrip() + parts = line.split(' ', 1) + if len(parts) != 2: + continue + addr, sym = parts + sym_addrs[sym] = addr -with open(wram_name, 'r', encoding='utf-8') as f: - cur_label = None - for line in f: - line = line.rstrip() - m = re.match(sym_def_rx, line) - if m: - sym, rest = m.group(1), m.group(2) - if sym is None and rest is None: - sym, rest = m.group(3), m.group(4) - key = sym - if not sym.startswith('.'): - cur_label = sym - elif cur_label: - key = cur_label + sym - if key in sym_addrs: - addr = sym_addrs[key] - line = sym + rest + ' ; ' + addr - print(line) + with open(wram_name, 'r', encoding='utf-8') as file: + cur_label = None + for line in file: + line = line.rstrip() + if (m = re.match(sym_def_rx, line)): + sym, rest = m.group(1), m.group(2) + if sym is None and rest is None: + sym, rest = m.group(3), m.group(4) + key = sym + if not sym.startswith('.'): + cur_label = sym + elif cur_label: + key = cur_label + sym + if key in sym_addrs: + addr = sym_addrs[key] + line = sym + rest + ' ; ' + addr + print(line) + +if __name__ == '__main__': + main() diff --git a/tools/toc.py b/tools/toc.py index f03b973b0..d9a3d963d 100755 --- a/tools/toc.py +++ b/tools/toc.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- """ -Usage: python3 toc.py [-n] files.md... +Usage: python toc.py file.md Replace a "## TOC" heading in a Markdown file with a table of contents, generated from the other headings in the file. Supports multiple files. @@ -18,17 +18,18 @@ toc_name = 'Contents' valid_toc_headings = {'## TOC', '##TOC'} TocItem = namedtuple('TocItem', ['name', 'anchor', 'level']) -punctuation_regexp = re.compile(r'[^\w\- ]+') -specialchar_regexp = re.compile(r'[⅔]+') +punctuation_rx = re.compile(r'[^\w\- ]+') +numbered_heading_rx = re.compile(r'^[0-9]+\. ') +specialchar_rx = re.compile(r'[⅔]+') def name_to_anchor(name): # GitHub's algorithm for generating anchors from headings # https://github.com/jch/html-pipeline/blob/master/lib/html/pipeline/toc_filter.rb - anchor = name.strip().lower() # lowercase - anchor = re.sub(punctuation_regexp, '', anchor) # remove punctuation - anchor = anchor.replace(' ', '-') # replace spaces with dash - anchor = re.sub(specialchar_regexp, '', anchor) # remove misc special chars - anchor = quote(anchor) # url encode + anchor = name.strip().lower() # lowercase + anchor = re.sub(punctuation_rx, '', anchor) # remove punctuation + anchor = anchor.replace(' ', '-') # replace spaces with dash + anchor = re.sub(specialchar_rx, '', anchor) # remove misc special chars + anchor = quote(anchor) # url encode return anchor def get_toc_index(lines): @@ -51,42 +52,46 @@ def get_toc_items(lines, toc_index): yield TocItem(name, anchor, level) def toc_string(toc_items): - lines = ['## %s' % toc_name, ''] + lines = [f'## {toc_name}', ''] for name, anchor, level in toc_items: padding = ' ' * level - line = '%s- [%s](#%s)' % (padding, name, anchor) - lines.append(line) + if re.match(numbered_heading_rx, name): + bullet, name = name.split('.', 1) + bullet += '.' + name = name.lstrip() + else: + bullet = '-' + lines.append(f'{padding}{bullet} [{name}](#{anchor})') return '\n'.join(lines) + '\n' def add_toc(filename): - with open(filename, 'r', encoding='utf-8') as f: - lines = f.readlines() + with open(filename, 'r', encoding='utf-8') as file: + lines = file.readlines() toc_index = get_toc_index(lines) if toc_index is None: return None # no TOC heading toc_items = list(get_toc_items(lines, toc_index)) if not toc_items: return False # no content headings - with open(filename, 'w', encoding='utf-8') as f: + with open(filename, 'w', encoding='utf-8') as file: for i, line in enumerate(lines): if i == toc_index: - f.write(toc_string(toc_items)) + file.write(toc_string(toc_items)) else: - f.write(line) + file.write(line) return True # OK def main(): if len(sys.argv) < 2: - print('*** ERROR: No filenames specified') - print(__doc__) - exit(1) + print(f'Usage: {sys.argv[0]} file.md', file=sys.stderr) + sys.exit(1) for filename in sys.argv[1:]: print(filename) result = add_toc(filename) if result is None: - print('*** WARNING: No "## TOC" heading found') + print('Warning: No "## TOC" heading found', file=sys.stderr) elif result is False: - print('*** WARNING: No content headings found') + print('Warning: No content headings found', file=sys.stderr) else: print('OK') diff --git a/tools/unique.py b/tools/unique.py new file mode 100755 index 000000000..34530a3e0 --- /dev/null +++ b/tools/unique.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" +Usage: python unique.py [-f|--flip] [-x|--cross] image.png + +Erase duplicate tiles from an input image. +-f or --flip counts X/Y mirrored tiles as duplicates. +-x or --cross erases with a cross instead of a blank tile. +""" + +import sys + +import png + +def rgb5_pixels(row): + yield from (tuple(c // 8 for c in row[x:x+3]) for x in range(0, len(row), 4)) + +def rgb8_pixels(row): + yield from (c * 8 + c // 4 for pixel in row for c in pixel) + +def gray_pixels(row): + yield from (pixel[0] // 10 for pixel in row) + +def rows_to_tiles(rows, width, height): + assert len(rows) == height and len(rows[0]) == width + yield from (tuple(tuple(row[x:x+8]) for row in rows[y:y+8]) + for y in range(0, height, 8) for x in range(0, width, 8)) + +def tiles_to_rows(tiles, width, height): + assert width % 8 == 0 and height % 8 == 0 + width, height = width // 8, height // 8 + tiles = list(tiles) + assert len(tiles) == width * height + tile_rows = (tiles[y:y+width] for y in range(0, width * height, width)) + yield from ([tile[y][x] for tile in tile_row for x in range(8)] + for tile_row in tile_rows for y in range(8)) + +def tile_variants(tile, flip): + yield tile + if flip: + yield tile[::-1] + yield tuple(row[::-1] for row in tile) + yield tuple(row[::-1] for row in tile[::-1]) + +def unique_tiles(tiles, flip, cross): + if cross: + blank = [[(0, 0, 0)] * 8 for _ in range(8)] + for y in range(8): + blank[y][y] = blank[y][7 - y] = (31, 31, 31) + blank = tuple(tuple(row) for row in blank) + else: + blank = tuple(tuple([(31, 31, 31)] * 8) for _ in range(8)) + seen = set() + for tile in tiles: + if any(variant in seen for variant in tile_variants(tile, flip)): + yield blank + else: + yield tile + seen.add(tile) + +def is_grayscale(colors): + return (colors.issubset({(31, 31, 31), (21, 21, 21), (10, 10, 10), (0, 0, 0)}) or + colors.issubset({(31, 31, 31), (20, 20, 20), (10, 10, 10), (0, 0, 0)})) + +def erase_duplicates(filename, flip, cross): + with open(filename, 'rb') as file: + width, height, rows = png.Reader(file).asRGBA8()[:3] + rows = [list(rgb5_pixels(row)) for row in rows] + if width % 8 or height % 8: + return False + tiles = unique_tiles(rows_to_tiles(rows, width, height), flip, cross) + rows = list(tiles_to_rows(tiles, width, height)) + if is_grayscale({c for row in rows for c in row}): + rows = [list(gray_pixels(row)) for row in rows] + writer = png.Writer(width, height, greyscale=True, bitdepth=2, compression=9) + else: + rows = [list(rgb8_pixels(row)) for row in rows] + writer = png.Writer(width, height, greyscale=False, bitdepth=8, compression=9) + with open(filename, 'wb') as file: + writer.write(file, rows) + return True + +def main(): + flip = cross = False + while True: + if len(sys.argv) < 2: + print(f'Usage: {sys.argv[0]} [-f|--flip] [-x|--cross] tileset.png', file=sys.stderr) + sys.exit(1) + elif sys.argv[1] in {'-f', '--flip'}: + flip = True + elif sys.argv[1] in {'-x', '--cross'}: + cross = True + elif sys.argv[1] in {'-fx', '-xf'}: + flip = cross = True + else: + break + sys.argv.pop(1) + for filename in sys.argv[1:]: + if not filename.lower().endswith('.png'): + print(f'{filename} is not a .png file!', file=sys.stderr) + elif not erase_duplicates(filename, flip, cross): + print(f'{filename} is not divisible into 8x8 tiles!', file=sys.stderr) + +if __name__ == '__main__': + main() diff --git a/tools/unnamed.py b/tools/unnamed.py index 53c5eebad..2f04b5c1e 100755 --- a/tools/unnamed.py +++ b/tools/unnamed.py @@ -1,131 +1,137 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from sys import stderr, exit -from subprocess import Popen, PIPE -from struct import unpack, calcsize -from enum import Enum +""" +Usage: unnamed.py [-h] [-r rootdir] [-l count] pokecrystal.sym -class symtype(Enum): - LOCAL = 0 - IMPORT = 1 - EXPORT = 2 +Parse the symfile to find unnamed symbols. +""" -def unpack_file(fmt, file): - size = calcsize(fmt) - return unpack(fmt, file.read(size)) +import sys +import argparse +import subprocess +import struct +import enum +import signal + +class symtype(enum.Enum): + LOCAL = 0 + IMPORT = 1 + EXPORT = 2 + +def unpack_from(fmt, file): + size = struct.calcsize(fmt) + return struct.unpack(fmt, file.read(size)) def read_string(file): - buf = bytearray() - while True: - b = file.read(1) - if b is None or b == b'\0': - return buf.decode() - else: - buf += b - + buf = bytearray() + while True: + b = file.read(1) + if b is None or b == b'\0': + return buf.decode() + buf += b # Fix broken pipe when using `head` -from signal import signal, SIGPIPE, SIG_DFL -signal(SIGPIPE,SIG_DFL) +signal.signal(signal.SIGPIPE, signal.SIG_DFL) -import argparse -parser = argparse.ArgumentParser(description="Parse the symfile to find unnamed symbols") -parser.add_argument('symfile', type=argparse.FileType('r'), help="the list of symbols") -parser.add_argument('-r', '--rootdir', type=str, help="scan the output files to obtain a list of files with unnamed symbols (NOTE: will rebuild objects as necessary)") -parser.add_argument('-l', '--list', type=int, default=0, help="output this many of each file's unnamed symbols (NOTE: requires -r)") +parser = argparse.ArgumentParser(description='Parse the symfile to find unnamed symbols') +parser.add_argument('symfile', type=argparse.FileType('r'), + help='the list of symbols') +parser.add_argument('-r', '--rootdir', type=str, + help='scan the output files to obtain a list of files with unnamed symbols (note: will rebuild objects as necessary)') +parser.add_argument('-l', '--list', type=int, default=0, + help="output this many of each file's unnamed symbols (note: requires -r)") args = parser.parse_args() # Get list of object files objects = None if args.rootdir: - for line in Popen(["make", "-C", args.rootdir, "-s", "-p", "DEBUG=1"], - stdout=PIPE).stdout.read().decode().split("\n"): - if line.startswith("pokecrystal_obj := "): - objects = line[19:].strip().split() - break - else: - print("Error: Object files not found!", file=stderr) - exit(1) + for line in subprocess.Popen(['make', '-C', args.rootdir, '-s', '-p', 'DEBUG=1'], + stdout=subprocess.PIPE).stdout.read().decode().split('\n'): + if line.startswith('pokecrystal_obj := '): + objects = line[19:].strip().split() + break + else: + print('Error: Object files not found!', file=sys.stderr) + sys.exit(1) # Scan all unnamed symbols from the symfile symbols_total = 0 symbols = set() for line in args.symfile: - line = line.split(";")[0].strip() - split = line.split(" ") - if len(split) < 2: - continue + line = line.split(';')[0].strip() + split = line.split(' ') + if len(split) < 2: + continue - symbols_total += 1 + symbols_total += 1 - symbol = " ".join(split[1:]).strip() - if symbol[-3:].lower() == split[0][-3:].lower(): - symbols.add(symbol) + symbol = ' '.join(split[1:]).strip() + if symbol[-3:].lower() == split[0][-3:].lower(): + symbols.add(symbol) # If no object files were provided, just print what we know and exit -print("Unnamed pokecrystal symbols: %d (%.2f%% complete)" % (len(symbols), - (symbols_total - len(symbols)) / symbols_total * 100)) +unnamed_percent = 100 * (symbols_total - len(symbols)) / symbols_total +print(f'Unnamed pokecrystal symbols: {len(symbols)} ({unnamed_percent:.2f}% complete)') if not objects: - for sym in symbols: - print(sym) - exit() + for sym in symbols: + print(sym) + sys.exit() # Count the amount of symbols in each file -files = {} +file_symbols = {} for objfile in objects: - f = open(objfile, "rb") - obj_ver = None + with open(objfile, 'rb') as file: + obj_ver = None - magic = unpack_file("4s", f)[0] - if magic == b'RGB6': - obj_ver = 6 - elif magic == b'RGB9': - obj_ver = 10 + unpack_file("= 2 else 'pokecrystal.map' - filename = sys.argv[2] if len(sys.argv) >= 3 else 'used_space.png' + outfile = sys.argv[2] if len(sys.argv) >= 3 else 'used_space.png' num_banks = 0x80 bank_mask = 0x3FFF @@ -29,16 +29,15 @@ def main(): bank_width = pixels_per_bank // height # 8 pixels width = bank_width * num_banks # 1024 pixels - r = MapReader() - with open(mapfile, 'r', encoding='utf-8') as f: - l = f.readlines() - r.read_map_data(l) + reader = MapReader() + with open(mapfile, 'r', encoding='utf-8') as file: + reader.read_map_data(file.readlines()) hit_data = [] default_bank_data = {'sections': [], 'used': 0, 'slack': bank_size} for bank in range(num_banks): hits = [0] * pixels_per_bank - bank_data = r.bank_data['ROM0 bank'] if bank == 0 else r.bank_data['ROMX bank'] + bank_data = reader.bank_data['ROM0 bank' if bank == 0 else 'ROMX bank'] data = bank_data.get(bank, default_bank_data) for s in data['sections']: beg = s['beg'] & bank_mask @@ -49,18 +48,17 @@ def main(): pixels = [[(0xFF, 0xFF, 0xFF)] * width for _ in range(height)] for bank, hits in enumerate(hit_data): - hue = 0 if not bank else 210 if bank % 2 else 270 - for i, h in enumerate(hits): - y = i // bank_width - x = i % bank_width + bank * bank_width - hls = (hue / 360.0, 1.0 - (h / bpp * (100 - 15)) / 100.0, 1.0) - rgb = tuple(c * 255 for c in hls_to_rgb(*hls)) + hue = 0 if bank == 0 else 210 if bank % 2 else 270 + for i, hit in enumerate(hits): + x, y = i % bank_width + bank * bank_width, i // bank_width + hls = (hue / 360, 1 - (85 * hit / bpp) / 100, 1) + rgb = tuple(int(c * 0xFF) for c in hls_to_rgb(*hls)) pixels[y][x] = rgb png_data = [tuple(c for pixel in row for c in pixel) for row in pixels] - with open(filename, 'wb') as f: - w = png.Writer(width, height) - w.write(f, png_data) + with open(outfile, 'wb') as file: + writer = png.Writer(width, height, greyscale=False, bitdepth=8, compression=9) + writer.write(file, png_data) if __name__ == '__main__': main()