42_KFS/tools/font_converter.py

77 lines
2.0 KiB
Python
Raw Normal View History

2024-12-11 14:31:39 -05:00
from PIL import Image
import re
import sys
import os
if (len(sys.argv) < 2):
print(f"Error: usage python {sys.argv[0]} {{file.fnt}}")
with open(sys.argv[1]) as f:
fnt_data = f.read()
font_name: str = os.path.basename(sys.argv[1]).split(".")[0]
img_file_relative_path: str = re.findall(r"file=\"(\w+[^\"]+)\"", fnt_data)[0]
img_file_absolute_path: str = sys.argv[1][0:sys.argv[1].rfind("/") +
1] + img_file_relative_path
2024-12-11 14:31:39 -05:00
image = Image.open(img_file_absolute_path)
width, height = image.size
pixels = list(image.getdata())
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]
2024-12-11 14:31:39 -05:00
characteres: list[list[int]] = [None for i in range(128)]
for id, x, y, width, height, xoffset, yoffset, xadvance in re.findall(
r"id=(\d+) x=(\d+) y=(\d+) width=(\d+) height=(\d+) xoffset=(-?\d+) yoffset=(-?\d+) xadvance=(\d+)",
fnt_data):
id, x, y, width, height, xoffset, yoffset, xadvance = int(id), int(x), int(
y), int(width), int(height), int(xoffset), int(yoffset), int(xadvance)
2024-12-11 14:31:39 -05:00
bitmap: list[str] = []
for line in pixels[y:y + height]:
tmp: str = ""
for r, g, b, a in line[x:x + width]:
2024-12-11 14:31:39 -05:00
tmp += "#" if a else " "
bitmap.append(tmp)
characteres[id] = [height, width, yoffset, bitmap]
2024-12-11 14:31:39 -05:00
string: str = f"""\
#pragma once
#include <stddef.h>
2024-12-11 14:31:39 -05:00
#include "font.h"
struct font {font_name}_font[] = {{\\\
2024-12-11 14:31:39 -05:00
"""
for charactere in characteres:
if (charactere is not None):
height, width, yoffset, bitmap = charactere
2024-12-11 14:31:39 -05:00
string += f"""
{{
.width = {width},
.height = {height},
.yoffset = {yoffset},
2024-12-11 14:31:39 -05:00
.bitmap = "{"".join(bitmap)}",
}},\
"""
else:
string += f"""
{{
.width = 0,
.height = 0,
.yoffset = 0,
2024-12-11 14:31:39 -05:00
.bitmap = NULL,
}},\
"""
string += "\n};"
2024-12-11 14:31:39 -05:00
if not os.path.exists("./headers/fonts"):
os.makedirs("./headers/fonts")
with open(f"./headers/fonts/{font_name}.h", "w") as f:
f.write(string)