You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

166 lines
4.3 KiB

  1. import argparse
  2. import pathlib
  3. import subprocess
  4. import sys
  5. import tempfile
  6. from typing import NoReturn, Tuple
  7. from PIL import Image
  8. GREEN = (0, 255, 0)
  9. RED = (255, 0, 0)
  10. BLUE = (0, 0, 255)
  11. def abort(msg: str) -> NoReturn:
  12. print(msg, file=sys.stderr)
  13. sys.exit(1)
  14. SpawnPoint = Tuple[int, int]
  15. def generate_coll_map(
  16. in_path: pathlib.Path, width: int, height: int, compress: bool = False
  17. ) -> Tuple[str, SpawnPoint]:
  18. png = Image.open(in_path).convert("RGB")
  19. if png.width % 8 != 0 or png.height % 8 != 0:
  20. abort(f"file '{in_path}' has invalid dimensions (should be multiple of 8)")
  21. if png.width // 8 != width or png.height // 8 != height:
  22. abort(f"file '{in_path}' has different size from map")
  23. out_bytes = []
  24. bits = []
  25. spawn = None
  26. for y in range(png.height // 8):
  27. for x in range(png.width // 8):
  28. pixel = png.getpixel((x * 8, y * 8))
  29. bit = None
  30. if pixel == RED:
  31. bit = 0
  32. elif pixel == GREEN:
  33. bit = 1
  34. elif pixel == BLUE:
  35. bit = 1
  36. spawn = (x, y)
  37. else:
  38. abort(f"unsupported pixel in collision map: {pixel}")
  39. if compress:
  40. bits.append(bit)
  41. if len(bits) == 8:
  42. byte = sum([bit << i for i, bit in enumerate(bits)])
  43. out_bytes.append(byte)
  44. bits = []
  45. else:
  46. out_bytes.append(bit)
  47. png.close()
  48. if spawn is None:
  49. abort(f"no spawn point located")
  50. return format_bytes(out_bytes, width=width), spawn
  51. def format_bytes(data: bytes, width: int = 16) -> str:
  52. lines = []
  53. for line_no in range(0, len(data), width):
  54. line = data[line_no : line_no + width]
  55. lines.append(" DB " + ", ".join(["$%02X" % b for b in line]))
  56. return "\n".join(lines)
  57. def generate_map(pngfile: str, compress: bool = False) -> None:
  58. pngpath = pathlib.Path(pngfile).resolve()
  59. incpath = pngpath.parent / pngpath.name.replace(".png", ".inc")
  60. spath = pngpath.parent / pngpath.name.replace(".png", ".s")
  61. png = Image.open(pngpath)
  62. if png.width % 8 != 0 or png.height % 8 != 0:
  63. abort(f"file '{pngfile}' has invalid dimensions (should be multiple of 8)")
  64. width = png.width // 8
  65. height = png.height // 8
  66. if width > 127 or height > 127:
  67. abort(
  68. f"file '{pngfile}' has invalid dimensions (width/height greater than 127 tiles)"
  69. )
  70. png.close()
  71. with tempfile.NamedTemporaryFile() as tilef, tempfile.NamedTemporaryFile() as mapf:
  72. subprocess.run(
  73. [
  74. "rgbgfx",
  75. "-u",
  76. "-t",
  77. tilef.name,
  78. "-o",
  79. mapf.name,
  80. pngfile,
  81. ]
  82. )
  83. map_data = format_bytes(tilef.read(), width=width)
  84. tile_data = format_bytes(mapf.read())
  85. section = pngpath.name.replace(".png", "")
  86. collpath = pngpath.parent / pngpath.name.replace(".png", "_coll.png")
  87. coll_map, spawn = generate_coll_map(collpath, width, height, compress=compress)
  88. with open(incpath, "w") as outf:
  89. outf.write(
  90. f"""DEF {section}_WIDTH EQU {width}
  91. DEF {section}_HEIGHT EQU {height}
  92. DEF {section}_NUM_TILES EQUS "({section}_TILES_end - {section}_TILES)"
  93. DEF {section}_MAP_SIZE EQUS "({section}_MAP_end - {section}_MAP)"
  94. ASSERT {section}_MAP_SIZE == {section}_WIDTH * {section}_HEIGHT
  95. """
  96. )
  97. with open(spath, "w") as outf:
  98. outf.write(
  99. f"""SECTION "MAP - {section}", ROM0
  100. {section}_Data::
  101. {section}_TILE_PTR: DW {section}_TILES
  102. {section}_TILE_SIZE: DB ({section}_TILES_end - {section}_TILES)
  103. {section}_MAP_PTR: DW {section}_MAP
  104. {section}_MAP_WIDTH: DB {width}
  105. {section}_MAP_HEIGHT: DB {height}
  106. {section}_SPAWN_X: DB {spawn[0]}
  107. {section}_SPAWN_Y: DB {spawn[1]}
  108. {section}_MAP::
  109. {map_data}
  110. {section}_MAP_end::
  111. {section}_TILES::
  112. {tile_data}
  113. {section}_TILES_end::
  114. {section}_COLLISION::
  115. {coll_map}
  116. {section}_COLLISION_end::
  117. """
  118. )
  119. def main() -> None:
  120. parser = argparse.ArgumentParser("generate_map")
  121. parser.add_argument("-c", "--compress", default=False)
  122. parser.add_argument("png")
  123. args = parser.parse_args()
  124. generate_map(args.png, compress=(not not args.compress))
  125. if __name__ == "__main__":
  126. main()