M-Film: film simulation for Canon EOS cameras with Magic Lantern. 72 film stocks (Portra, Velvia, Tri-X, CineStill…), a film-camera interface and an in-camera darkroom that develops your RAWs. 5D Mark III, 6D, 600D, 650D, 700D, EOS M and more.
C analog-photographycamera-firmwarecanoncanon-5d-mark-ivcanon-5dmark2canon-6dcanon-eoscr2darkroomeos-mfilm-emulationfilm-lookfilm-photographyfilm-simulationfujifilm-recipeskodak-portralutmagic-lanternphotographyraw
"""Rasterise the film OS fonts into fos_font.c.
python3 mkfont.py # writes ../fos_font.c and ../sim/out/fonts.png
Glyphs are 4-bit anti-aliased coverage, run-length coded (fos_gfx.c
decodes them). Advances and kerning are kept in 1/16 px so spacing comes
out like the real font even at small sizes. Needs Pillow with raqm
(for GPOS kerning) and the Barlow TTFs in ../fonts (SIL OFL 1.1).
"""
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
HERE = Path(__file__).resolve().parent
FONTS = HERE.parent / "fonts"
OUT_C = HERE.parent / "fos_font.c"
OUT_PNG = HERE.parent / "sim" / "out" / "fonts.png"
ASCII = "".join(chr(c) for c in range(32, 127))
# bytes 0x80.. in our strings; see FOS_T_* in fos_gfx.h
EXTRAS = ["·", "°", "×", "–", "—", "’", "…", "•", "‹", "›"]
UPPER = " !\"#%&'()*+,-./0123456789:;?ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# name, file, px size, characters
SPECS = [
("xs", "Barlow-SemiBold.ttf", 13, ASCII),
("sm", "Barlow-Medium.ttf", 16, ASCII),
("md", "Barlow-Medium.ttf", 20, ASCII),
("mdb", "Barlow-SemiBold.ttf", 20, ASCII),
("lg", "Barlow-SemiBold.ttf", 27, ASCII),
("xl", "BarlowCondensed-SemiBold.ttf", 50, ASCII),
("num", "BarlowCondensed-Medium.ttf", 84, " 0123456789/:-.S"),
# canister label art (drawn into the label textures)
("lbig", "BarlowCondensed-ExtraBold.ttf", 54, " 0123456789HPT"),
("lname", "BarlowCondensed-Bold.ttf", 25, UPPER),
("lsm", "BarlowCondensed-SemiBold.ttf", 13, UPPER),
]
def kern_pairs(font, chars, scale):
"""Kerning that raqm applies between two characters, in 1/16 px.
Measured on a big unhinted copy of the font and scaled down, so the
rounding of small sizes doesn't show up as fake kerning."""
adv = {c: font.getlength(c) for c in chars}
out = []
letters = [c for c in chars if c.isalnum() or c in ".,'-" or ord(c) >= 0x80]
for a in letters:
for b in letters:
k = (font.getlength(a + b) - adv[a] - adv[b]) * scale
k16 = max(-127, min(127, round(k * 16)))
if abs(k16) >= 4: # a quarter pixel or more
out.append((a, b, k16))
return out
def rle(values):
"""4-bit coverage -> bytes. 0x00-0x7F: (count-1) << 4 | value, a run of
1..8 equal values; zero runs use 0x80 | (count-1), 1..128 zeros."""
out = bytearray()
i = 0
n = len(values)
while i < n:
v = values[i]
j = i
if v == 0:
while j < n and values[j] == 0 and j - i < 128:
j += 1
out.append(0x80 | (j - i - 1))
else:
while j < n and values[j] == v and j - i < 8:
j += 1
out.append(((j - i - 1) << 4) | v)
i = j
return out
def build(name, file, size, chars):
font = ImageFont.truetype(str(FONTS / file), size)
big = ImageFont.truetype(str(FONTS / file), 512)
scale = size / 512
ascent, descent = font.getmetrics()
chars = sorted(set(chars), key=ord)
allchars = chars + (EXTRAS if chars is not None and len(chars) > 80 else [])
glyphs = []
data = bytearray()
for ch in allchars:
code = ord(ch) if ord(ch) < 128 else 0x80 + EXTRAS.index(ch)
x0, y0, x1, y1 = font.getbbox(ch)
w, h = max(0, x1 - x0), max(0, y1 - y0)
adv16 = round(big.getlength(ch) * scale * 16)
if w and h:
img = Image.new("L", (w, h), 0)
ImageDraw.Draw(img).text((-x0, -y0), ch, font=font, fill=255)
px = list(img.tobytes())
# trim empty rows / columns the bbox may include
vals = [round(p * 15 / 255) for p in px]
else:
vals = []
glyphs.append(dict(code=code, ch=ch, off=len(data), w=w, h=h,
ox=x0, oy=y0 - ascent, adv=adv16))
data += rle(vals)
kerns = kern_pairs(big, allchars, scale)
codes = {g["ch"]: g["code"] for g in glyphs}
kerns = sorted((codes[a], codes[b], k) for a, b, k in kerns)
return dict(name=name, size=size, ascent=ascent, descent=descent,
glyphs=sorted(glyphs, key=lambda g: g["code"]), data=data, kerns=kerns, font=font)
def c_bytes(data):
lines = []
for i in range(0, len(data), 24):
lines.append(" " + ",".join(str(b) for b in data[i:i + 24]) + ",")
return "\n".join(lines)
def emit(fonts):
out = [
"/* generated by tools/mkfont.py from Barlow (SIL Open Font License 1.1,",
" * see fonts/OFL.txt) - do not edit. Not linked into the camera: it goes",
" * on the card as ML/DATA/FOSFONT.BIN (tools/fontblob.c) */",
"",
'#include "fos_gfx.h"',
"",
]
total = 0
for f in fonts:
n = f["name"]
# glyph lookup by byte value: index into the glyph table, 0xFF = missing
lut = [255] * 256
for i, g in enumerate(f["glyphs"]):
lut[g["code"]] = i
out.append(f"static const uint8_t {n}_bits[] = {{\n{c_bytes(f['data'])}\n}};")
out.append(f"static const struct fos_glyph {n}_glyphs[] = {{")
for g in f["glyphs"]:
out.append(f" {{ {g['off']:5d}, {g['w']:3d}, {g['h']:3d}, {g['ox']:3d}, {g['oy']:4d}, {g['adv']:5d} }},"
f" /* {g['code']:#04x} */")
out.append("};")
out.append(f"static const uint8_t {n}_lut[256] = {{\n{c_bytes(lut)}\n}};")
if f["kerns"]:
out.append(f"static const struct fos_kern {n}_kern[] = {{")
row = []
for a, b, k in f["kerns"]:
row.append(f"{{{a},{b},{k}}}")
if len(row) == 8:
out.append(" " + ",".join(row) + ",")
row = []
if row:
out.append(" " + ",".join(row) + ",")
out.append("};")
kern_ref, nk = f"{n}_kern", len(f["kerns"])
else:
kern_ref, nk = "0", 0
out.append(f"const struct fos_font fos_font_{n}_data = {{ {n}_bits, {n}_glyphs, {n}_lut, {kern_ref}, {nk}, "
f"{f['ascent']}, {f['descent']} }};")
out.append("")
total += len(f["data"]) + 8 * len(f["glyphs"]) + 256 + 3 * nk
OUT_C.write_text("\n".join(out))
return total
def preview(fonts):
OUT_PNG.parent.mkdir(parents=True, exist_ok=True)
rows = []
for f in fonts:
sample = "".join(g["ch"] for g in f["glyphs"] if g["ch"].strip())
rows.append((f, f"{f['name']} {f['size']}px {sample[:60]}"))
h = sum(f["ascent"] + f["descent"] + 8 for f, _ in rows)
img = Image.new("L", (1400, h), 0)
d = ImageDraw.Draw(img)
y = 0
for f, text in rows:
d.text((4, y), text, font=f["font"], fill=255)
y += f["ascent"] + f["descent"] + 8
img.save(OUT_PNG)
if __name__ == "__main__":
fonts = [build(*s) for s in SPECS]
size = emit(fonts)
preview(fonts)
for f in fonts:
print(f"{f['name']:6s} {f['size']:3d}px glyphs {len(f['glyphs']):3d} data {len(f['data']):6d} B kern {len(f['kerns'])}")
print(f"total ~{size} bytes -> {OUT_C}")