build_assets_v2.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. """Package the redrawn V2 art; preserve V1 before installing this character only."""
  2. import argparse
  3. from copy import deepcopy
  4. import hashlib
  5. import json
  6. from pathlib import Path
  7. import shutil
  8. import numpy as np
  9. from PIL import Image, ImageDraw, ImageOps
  10. ROOT = Path(__file__).resolve().parents[2]
  11. HERE = Path(__file__).resolve().parent
  12. OUT = HERE / 'v2'
  13. PREFIX = 'deepseek_bluewhale'
  14. CANVAS = (128, 112)
  15. ART_HEIGHT = 90
  16. PIVOT = (64, 100)
  17. OFFSET = (-64, -93)
  18. DIRECTIONS = ('R', 'U', 'L', 'D')
  19. def dump(path, value):
  20. path.parent.mkdir(parents=True, exist_ok=True)
  21. path.write_text(json.dumps(value, ensure_ascii=False, indent=4) + '\n', encoding='utf-8')
  22. def split_sheet(path, columns, rows):
  23. image = Image.open(path).convert('RGBA')
  24. alpha = np.array(image.getchannel('A'))
  25. width, height = image.size
  26. row_edges = [0]
  27. for row in range(1, rows):
  28. middle = round(row * height / rows)
  29. radius = round(height / rows * 0.12)
  30. low, high = max(0, middle - radius), min(height, middle + radius)
  31. values = (alpha[low:high] > 64).sum(axis=1)
  32. candidates = np.flatnonzero(values == values.min())
  33. edge = low + int(candidates[np.argmin(np.abs(candidates + low - middle))])
  34. row_edges.append(edge)
  35. row_edges.append(height)
  36. result = []
  37. for row in range(rows):
  38. top, bottom = row_edges[row:row + 2]
  39. edges = [0]
  40. for column in range(1, columns):
  41. middle = round(column * width / columns)
  42. radius = round(width / columns * 0.12)
  43. low, high = max(0, middle - radius), min(width, middle + radius)
  44. values = (alpha[top:bottom, low:high] > 64).sum(axis=0)
  45. candidates = np.flatnonzero(values == values.min())
  46. edges.append(low + int(candidates[np.argmin(np.abs(candidates + low - middle))]))
  47. edges.append(width)
  48. cells = []
  49. for column in range(columns):
  50. cell = image.crop((edges[column], top, edges[column + 1], bottom))
  51. bbox = cell.getchannel('A').point(lambda a: 255 if a > 64 else 0).getbbox()
  52. if bbox is None:
  53. raise ValueError(f'Empty frame: {path}, {row}, {column}')
  54. cells.append(cell.crop(bbox))
  55. result.append(cells)
  56. return result
  57. def register(image, phase):
  58. # Use the head, not the whole bounding-box center: a swinging tail must
  59. # never push the character's face/feet from side to side.
  60. alpha = np.asarray(image.getchannel('A')) > 64
  61. top, bottom = round(image.height * .18), round(image.height * .52)
  62. head = alpha[top:bottom]
  63. weights = head.sum(axis=0)
  64. head_x = float(np.dot(weights, np.arange(image.width)) / weights.sum())
  65. factor = ART_HEIGHT / image.height
  66. size = (round(image.width * factor), ART_HEIGHT)
  67. image = image.resize(size, Image.Resampling.LANCZOS)
  68. bob = 0 if phase is None else (0, -1, 0, 0, -1, 0)[phase]
  69. x, y = round(PIVOT[0] - head_x * factor), PIVOT[1] - ART_HEIGHT + bob
  70. if x < 1 or x + size[0] >= CANVAS[0] or y < 1 or y + size[1] >= CANVAS[1]:
  71. raise ValueError(f'Clipped character: {x, y, size}')
  72. result = Image.new('RGBA', CANVAS)
  73. result.alpha_composite(image, (x, y))
  74. return result
  75. def make_previews(textures):
  76. contact = Image.new('RGB', (7 * 164, 4 * 166), '#edf3f8')
  77. draw = ImageDraw.Draw(contact)
  78. for row in range(4):
  79. for column in range(7):
  80. image = textures[row][column]
  81. pos = (column * 164 + 18, row * 166 + 12)
  82. contact.paste(image, pos, image)
  83. draw.text((column * 164 + 18, row * 166 + 136),
  84. DIRECTIONS[row] + (' stand' if column == 0 else f' walk {column - 1}'), fill='#203349')
  85. contact.save(OUT / 'contact_sheet.png')
  86. sequence = []
  87. for phase in range(6):
  88. scene = Image.new('RGB', (640, 200), '#263447')
  89. draw = ImageDraw.Draw(scene)
  90. for x in range(0, 641, 40):
  91. draw.line((x, 0, x, 200), fill='#526174')
  92. for y in range(0, 201, 40):
  93. draw.line((0, y, 640, y), fill='#526174')
  94. for row in range(4):
  95. image = textures[row][phase + 1]
  96. scene.paste(image, (16 + row * 160, 27), image)
  97. draw.text((72 + row * 160, 157), DIRECTIONS[row], fill='white')
  98. draw.text((10, 181), 'V2 / 90px tall / 40px tiles / 100ms per frame', fill='#e1e9f2')
  99. sequence.append(scene)
  100. sequence[0].save(OUT / 'walk_preview.gif', save_all=True, append_images=sequence[1:], duration=100, loop=0)
  101. old_path = OUT / 'previous_version/res/img/cloth/deepseek_bluewhale_stand_3_0.png'
  102. if not old_path.exists():
  103. old_path = ROOT / 'res/img/cloth/deepseek_bluewhale_stand_3_0.png'
  104. old = Image.open(old_path).convert('RGBA')
  105. compare = Image.new('RGB', (640, 220), '#263447')
  106. draw = ImageDraw.Draw(compare)
  107. for x in range(0, 641, 40):
  108. draw.line((x, 0, x, 220), fill='#526174')
  109. for y in range(0, 221, 40):
  110. draw.line((0, y, 640, y), fill='#526174')
  111. compare.paste(old, (160 - 32, 160 - 53), old)
  112. compare.paste(textures[3][0], (480 + OFFSET[0], 160 + OFFSET[1]), textures[3][0])
  113. draw.text((115, 190), 'V1 ~58 px', fill='white')
  114. draw.text((435, 190), 'V2 90 px (1.55x)', fill='white')
  115. compare.save(OUT / 'size_comparison.png')
  116. def build():
  117. views = split_sheet(OUT / 'source_views.png', 7, 3)
  118. side = sum(split_sheet(OUT / 'source_side_walk.png', 3, 2), [])
  119. source_right = [views[0][0]] + side
  120. right = [register(image, None if i == 0 else i - 1) for i, image in enumerate(source_right)]
  121. back = [register(image, None if i == 0 else i - 1) for i, image in enumerate(views[1])]
  122. front = [register(image, None if i == 0 else i - 1) for i, image in enumerate(views[2])]
  123. left = [ImageOps.mirror(image) for image in right]
  124. textures = [right, back, left, front]
  125. assets = []
  126. for row in range(4):
  127. for column, image in enumerate(textures[row]):
  128. motion, index = ('stand', 0) if column == 0 else ('walk', column - 1)
  129. relative = Path('res/img/cloth') / f'{PREFIX}_{motion}_{row}_{index}.png'
  130. path = OUT / 'assets' / relative
  131. path.parent.mkdir(parents=True, exist_ok=True)
  132. image.save(path)
  133. assets.append({'path': relative.as_posix(), 'direction': DIRECTIONS[row],
  134. 'motion': motion, 'frame': index, 'size': list(CANVAS),
  135. 'visible_bounds': image.getbbox(), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()})
  136. character_path = Path('game/frame/character/CharacterDeepseekBlueWhale.json')
  137. data = json.loads((ROOT / character_path).read_text(encoding='utf-8'))
  138. for row, direction in enumerate(DIRECTIONS):
  139. for standing in (True, False):
  140. state = ('STAND_' if standing else '') + direction
  141. data[state]['Cx'], data[state]['Cy'] = OFFSET
  142. data['HEAD_POS'] = [-max(0, CANVAS[0] // 2 - 15), -max(0, CANVAS[1] // 4 - 15)]
  143. data['LOSE'] = deepcopy(data['STAND_D'])
  144. dump(OUT / 'assets' / character_path, data)
  145. icon = front[0].crop(front[0].getbbox())
  146. icon.thumbnail((53, 53), Image.Resampling.LANCZOS)
  147. icon_canvas = Image.new('RGBA', (55, 55))
  148. icon_canvas.alpha_composite(icon, ((55 - icon.width) // 2, 55 - icon.height))
  149. icon_path = OUT / 'assets/res/img/ui/game/icon_deepseek_bluewhale.png'
  150. icon_path.parent.mkdir(parents=True, exist_ok=True)
  151. icon_canvas.save(icon_path)
  152. make_previews(textures)
  153. manifest = {'version': 2, 'hero': 'DeepseekBlueWhale', 'character': 'CharacterDeepseekBlueWhale',
  154. 'canvas': list(CANVAS), 'art_height': ART_HEIGHT, 'foot_baseline': PIVOT[1],
  155. 'character_offset': list(OFFSET), 'head_registration': True,
  156. 'left_is_exact_mirror_of_right': True,
  157. 'source_sheet': 'v2/source_views.png', 'side_walk_source': 'v2/source_side_walk.png', 'assets': assets}
  158. dump(OUT / 'asset_manifest.json', manifest)
  159. return manifest
  160. def install(manifest):
  161. # Only the explicitly redrawn character's files are replaced. Keep a
  162. # recoverable V1 copy, including any edits made since the original build.
  163. files = list((OUT / 'assets').rglob('*.png')) + list((OUT / 'assets').rglob('*.json'))
  164. for source in files:
  165. relative = source.relative_to(OUT / 'assets')
  166. target = ROOT / relative
  167. backup = OUT / 'previous_version' / relative
  168. if target.exists() and not backup.exists():
  169. backup.parent.mkdir(parents=True, exist_ok=True)
  170. shutil.copy2(target, backup)
  171. for name in ('asset_manifest.json', 'contact_sheet.png', 'walk_preview.gif', 'in_game.png', 'runtime_verification.json'):
  172. previous = HERE / name
  173. backup = OUT / 'previous_version/resource_tool/deepseek_character' / name
  174. if previous.exists() and not backup.exists():
  175. backup.parent.mkdir(parents=True, exist_ok=True)
  176. shutil.copy2(previous, backup)
  177. for source in files:
  178. shutil.copy2(source, ROOT / source.relative_to(OUT / 'assets'))
  179. for name in ('asset_manifest.json', 'contact_sheet.png', 'walk_preview.gif'):
  180. shutil.copy2(OUT / name, HERE / name)
  181. print('Installed V2: 28 character sprites, frame JSON and icon. Hero statistics unchanged.')
  182. if __name__ == '__main__':
  183. parser = argparse.ArgumentParser()
  184. parser.add_argument('--install', action='store_true')
  185. args = parser.parse_args()
  186. manifest = build()
  187. if args.install:
  188. install(manifest)
  189. else:
  190. print('Built staged V2 assets and previews; use --install after reviewing.')