| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206 |
- """Package the redrawn V2 art; preserve V1 before installing this character only."""
- import argparse
- from copy import deepcopy
- import hashlib
- import json
- from pathlib import Path
- import shutil
- import numpy as np
- from PIL import Image, ImageDraw, ImageOps
- ROOT = Path(__file__).resolve().parents[2]
- HERE = Path(__file__).resolve().parent
- OUT = HERE / 'v2'
- PREFIX = 'deepseek_bluewhale'
- CANVAS = (128, 112)
- ART_HEIGHT = 90
- PIVOT = (64, 100)
- OFFSET = (-64, -93)
- DIRECTIONS = ('R', 'U', 'L', 'D')
- def dump(path, value):
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(value, ensure_ascii=False, indent=4) + '\n', encoding='utf-8')
- def split_sheet(path, columns, rows):
- image = Image.open(path).convert('RGBA')
- alpha = np.array(image.getchannel('A'))
- width, height = image.size
- row_edges = [0]
- for row in range(1, rows):
- middle = round(row * height / rows)
- radius = round(height / rows * 0.12)
- low, high = max(0, middle - radius), min(height, middle + radius)
- values = (alpha[low:high] > 64).sum(axis=1)
- candidates = np.flatnonzero(values == values.min())
- edge = low + int(candidates[np.argmin(np.abs(candidates + low - middle))])
- row_edges.append(edge)
- row_edges.append(height)
- result = []
- for row in range(rows):
- top, bottom = row_edges[row:row + 2]
- edges = [0]
- for column in range(1, columns):
- middle = round(column * width / columns)
- radius = round(width / columns * 0.12)
- low, high = max(0, middle - radius), min(width, middle + radius)
- values = (alpha[top:bottom, low:high] > 64).sum(axis=0)
- candidates = np.flatnonzero(values == values.min())
- edges.append(low + int(candidates[np.argmin(np.abs(candidates + low - middle))]))
- edges.append(width)
- cells = []
- for column in range(columns):
- cell = image.crop((edges[column], top, edges[column + 1], bottom))
- bbox = cell.getchannel('A').point(lambda a: 255 if a > 64 else 0).getbbox()
- if bbox is None:
- raise ValueError(f'Empty frame: {path}, {row}, {column}')
- cells.append(cell.crop(bbox))
- result.append(cells)
- return result
- def register(image, phase):
- # Use the head, not the whole bounding-box center: a swinging tail must
- # never push the character's face/feet from side to side.
- alpha = np.asarray(image.getchannel('A')) > 64
- top, bottom = round(image.height * .18), round(image.height * .52)
- head = alpha[top:bottom]
- weights = head.sum(axis=0)
- head_x = float(np.dot(weights, np.arange(image.width)) / weights.sum())
- factor = ART_HEIGHT / image.height
- size = (round(image.width * factor), ART_HEIGHT)
- image = image.resize(size, Image.Resampling.LANCZOS)
- bob = 0 if phase is None else (0, -1, 0, 0, -1, 0)[phase]
- x, y = round(PIVOT[0] - head_x * factor), PIVOT[1] - ART_HEIGHT + bob
- if x < 1 or x + size[0] >= CANVAS[0] or y < 1 or y + size[1] >= CANVAS[1]:
- raise ValueError(f'Clipped character: {x, y, size}')
- result = Image.new('RGBA', CANVAS)
- result.alpha_composite(image, (x, y))
- return result
- def make_previews(textures):
- contact = Image.new('RGB', (7 * 164, 4 * 166), '#edf3f8')
- draw = ImageDraw.Draw(contact)
- for row in range(4):
- for column in range(7):
- image = textures[row][column]
- pos = (column * 164 + 18, row * 166 + 12)
- contact.paste(image, pos, image)
- draw.text((column * 164 + 18, row * 166 + 136),
- DIRECTIONS[row] + (' stand' if column == 0 else f' walk {column - 1}'), fill='#203349')
- contact.save(OUT / 'contact_sheet.png')
- sequence = []
- for phase in range(6):
- scene = Image.new('RGB', (640, 200), '#263447')
- draw = ImageDraw.Draw(scene)
- for x in range(0, 641, 40):
- draw.line((x, 0, x, 200), fill='#526174')
- for y in range(0, 201, 40):
- draw.line((0, y, 640, y), fill='#526174')
- for row in range(4):
- image = textures[row][phase + 1]
- scene.paste(image, (16 + row * 160, 27), image)
- draw.text((72 + row * 160, 157), DIRECTIONS[row], fill='white')
- draw.text((10, 181), 'V2 / 90px tall / 40px tiles / 100ms per frame', fill='#e1e9f2')
- sequence.append(scene)
- sequence[0].save(OUT / 'walk_preview.gif', save_all=True, append_images=sequence[1:], duration=100, loop=0)
- old_path = OUT / 'previous_version/res/img/cloth/deepseek_bluewhale_stand_3_0.png'
- if not old_path.exists():
- old_path = ROOT / 'res/img/cloth/deepseek_bluewhale_stand_3_0.png'
- old = Image.open(old_path).convert('RGBA')
- compare = Image.new('RGB', (640, 220), '#263447')
- draw = ImageDraw.Draw(compare)
- for x in range(0, 641, 40):
- draw.line((x, 0, x, 220), fill='#526174')
- for y in range(0, 221, 40):
- draw.line((0, y, 640, y), fill='#526174')
- compare.paste(old, (160 - 32, 160 - 53), old)
- compare.paste(textures[3][0], (480 + OFFSET[0], 160 + OFFSET[1]), textures[3][0])
- draw.text((115, 190), 'V1 ~58 px', fill='white')
- draw.text((435, 190), 'V2 90 px (1.55x)', fill='white')
- compare.save(OUT / 'size_comparison.png')
- def build():
- views = split_sheet(OUT / 'source_views.png', 7, 3)
- side = sum(split_sheet(OUT / 'source_side_walk.png', 3, 2), [])
- source_right = [views[0][0]] + side
- right = [register(image, None if i == 0 else i - 1) for i, image in enumerate(source_right)]
- back = [register(image, None if i == 0 else i - 1) for i, image in enumerate(views[1])]
- front = [register(image, None if i == 0 else i - 1) for i, image in enumerate(views[2])]
- left = [ImageOps.mirror(image) for image in right]
- textures = [right, back, left, front]
- assets = []
- for row in range(4):
- for column, image in enumerate(textures[row]):
- motion, index = ('stand', 0) if column == 0 else ('walk', column - 1)
- relative = Path('res/img/cloth') / f'{PREFIX}_{motion}_{row}_{index}.png'
- path = OUT / 'assets' / relative
- path.parent.mkdir(parents=True, exist_ok=True)
- image.save(path)
- assets.append({'path': relative.as_posix(), 'direction': DIRECTIONS[row],
- 'motion': motion, 'frame': index, 'size': list(CANVAS),
- 'visible_bounds': image.getbbox(), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest()})
- character_path = Path('game/frame/character/CharacterDeepseekBlueWhale.json')
- data = json.loads((ROOT / character_path).read_text(encoding='utf-8'))
- for row, direction in enumerate(DIRECTIONS):
- for standing in (True, False):
- state = ('STAND_' if standing else '') + direction
- data[state]['Cx'], data[state]['Cy'] = OFFSET
- data['HEAD_POS'] = [-max(0, CANVAS[0] // 2 - 15), -max(0, CANVAS[1] // 4 - 15)]
- data['LOSE'] = deepcopy(data['STAND_D'])
- dump(OUT / 'assets' / character_path, data)
- icon = front[0].crop(front[0].getbbox())
- icon.thumbnail((53, 53), Image.Resampling.LANCZOS)
- icon_canvas = Image.new('RGBA', (55, 55))
- icon_canvas.alpha_composite(icon, ((55 - icon.width) // 2, 55 - icon.height))
- icon_path = OUT / 'assets/res/img/ui/game/icon_deepseek_bluewhale.png'
- icon_path.parent.mkdir(parents=True, exist_ok=True)
- icon_canvas.save(icon_path)
- make_previews(textures)
- manifest = {'version': 2, 'hero': 'DeepseekBlueWhale', 'character': 'CharacterDeepseekBlueWhale',
- 'canvas': list(CANVAS), 'art_height': ART_HEIGHT, 'foot_baseline': PIVOT[1],
- 'character_offset': list(OFFSET), 'head_registration': True,
- 'left_is_exact_mirror_of_right': True,
- 'source_sheet': 'v2/source_views.png', 'side_walk_source': 'v2/source_side_walk.png', 'assets': assets}
- dump(OUT / 'asset_manifest.json', manifest)
- return manifest
- def install(manifest):
- # Only the explicitly redrawn character's files are replaced. Keep a
- # recoverable V1 copy, including any edits made since the original build.
- files = list((OUT / 'assets').rglob('*.png')) + list((OUT / 'assets').rglob('*.json'))
- for source in files:
- relative = source.relative_to(OUT / 'assets')
- target = ROOT / relative
- backup = OUT / 'previous_version' / relative
- if target.exists() and not backup.exists():
- backup.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(target, backup)
- for name in ('asset_manifest.json', 'contact_sheet.png', 'walk_preview.gif', 'in_game.png', 'runtime_verification.json'):
- previous = HERE / name
- backup = OUT / 'previous_version/resource_tool/deepseek_character' / name
- if previous.exists() and not backup.exists():
- backup.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(previous, backup)
- for source in files:
- shutil.copy2(source, ROOT / source.relative_to(OUT / 'assets'))
- for name in ('asset_manifest.json', 'contact_sheet.png', 'walk_preview.gif'):
- shutil.copy2(OUT / name, HERE / name)
- print('Installed V2: 28 character sprites, frame JSON and icon. Hero statistics unchanged.')
- if __name__ == '__main__':
- parser = argparse.ArgumentParser()
- parser.add_argument('--install', action='store_true')
- args = parser.parse_args()
- manifest = build()
- if args.install:
- install(manifest)
- else:
- print('Built staged V2 assets and previews; use --install after reviewing.')
|