| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246 |
- """Background asset decoding; all Pygame surfaces stay on the UI thread."""
- import json
- import re
- from pathlib import Path
- from runtime_paths import PROJECT_ROOT
- from concurrent.futures import ThreadPoolExecutor
- from PIL import Image
- import pygame
- from const.window import WINDOW_W, WINDOW_H, TOOL_PANEL_WIDTH
- from game.frame import floor, obstacle
- from game.frame.frame import Frame
- def scan(root, library):
- directory = root / 'res/img/mapElem' / library
- entries = []
- for path in directory.iterdir():
- match = re.fullmatch(r'(elem\d+)(\.png|_stand_0_0\.png)', path.name, re.I)
- if not match:
- continue
- name, suffix = match.groups()
- kind = 'floor' if suffix.lower() == '.png' else 'obstacle'
- registration = None
- if kind == 'obstacle':
- registration = next((root / 'game/frame' / folder / library / (name+'.json')
- for folder in ('obstacle', 'obstacles')
- if (root / 'game/frame' / folder / library / (name+'.json')).is_file()), None)
- if registration is None:
- continue
- entries.append(dict(type=library, name=name, elem_type=kind, path=path, registration=registration))
- return sorted(entries, key=lambda n: (int(n['name'][4:]), n['elem_type']))
- def decode(root, entry, full=False):
- entry = dict(entry)
- path = entry['path']
- width = height = 1
- cx = cy = 0
- if entry['registration']:
- config = json.loads(entry['registration'].read_text(encoding='utf-8-sig'))
- width, height = config['WIDTH'], config['HEIGHT']
- if not isinstance(width, int) or not isinstance(height, int) or width < 1 or height < 1:
- raise ValueError('无效占地尺寸')
- stand = config['STAND']
- path = root / 'res/img/mapElem' / config['TYPE'] / stand['IMG'][0]
- cx, cy = stand['CX'][0], stand['CY'][0]
- with Image.open(path) as source:
- img = source.convert('RGBA')
- entry.update(width=width, height=height, cx=cx, cy=cy)
- if full:
- return entry, img.size, img.tobytes()
- # Fit the sprite and its offset relative to the occupied cells together.
- left, top = min(0, cx), min(0, cy)
- right, bottom = max(width*40, cx+img.width), max(height*40, cy+img.height)
- scale = min(1, 112/(right-left), 88/(bottom-top))
- size = (max(1, round(img.width*scale)), max(1, round(img.height*scale)))
- img = img.resize(size, Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
- thumb = Image.new('RGBA', (112, 88))
- thumb.alpha_composite(img, (round((112-(right-left)*scale)/2+(cx-left)*scale),
- round((88-(bottom-top)*scale)/2+(cy-top)*scale)))
- return entry, thumb.size, thumb.tobytes()
- class AssetLibrary:
- def __init__(self, app):
- self.app = app
- self.root = PROJECT_ROOT
- self.pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix='map-assets')
- self.visible = False
- self.libraries = []
- self.directory_job = self.pool.submit(lambda: sorted(p.name for p in (self.root/'res/img/mapElem').iterdir() if p.is_dir()))
- self.scan_job = None
- self.jobs = {}
- self.pending = []
- self.entries = []
- self.selected_job = None
- self.library = None
- self.dropdown = False
- self.folder_offset = self.offset = self.failed = 0
- self.header = pygame.Rect(WINDOW_W+12, 44, TOOL_PANEL_WIDTH-24, 32)
- self.button = pygame.Rect(616, 2, 86, 28)
- def toggle(self):
- self.visible = not self.visible
- if not self.visible and self.selected_job:
- self.selected_job.cancel()
- self.selected_job = None
- self.app.menu.active = None
- self.app.menu.block_pointer = True
- self.app.settings.focus = None
- pygame.key.stop_text_input()
- if self.visible:
- self.app.tools.visible = True
- self.app.tools.regions.finish_drag()
- self.app.tools.choose('paint')
- self.app.tools.regions.enabled = False
- def choose_library(self, name):
- for job in self.jobs:
- job.cancel()
- if self.selected_job:
- self.selected_job.cancel()
- self.selected_job = None
- self.jobs.clear()
- self.pending = []
- self.entries = []
- self.offset = self.failed = 0
- self.library = name
- self.dropdown = False
- self.scan_job = self.pool.submit(scan, self.root, name)
- def update(self):
- if self.directory_job and self.directory_job.done():
- try:
- self.libraries = self.directory_job.result()
- except Exception as error:
- self.app.menu.notify('素材目录读取失败:'+str(error))
- self.directory_job = None
- if self.visible and self.library is None and self.libraries:
- self.choose_library(self.libraries[0])
- if self.scan_job and self.scan_job.done():
- try:
- self.pending = self.scan_job.result()
- except Exception as error:
- self.app.menu.notify('素材扫描失败:'+str(error))
- self.scan_job = None
- for job in list(self.jobs):
- if job.done():
- del self.jobs[job]
- try:
- entry, size, pixels = job.result()
- entry['thumbnail'] = pygame.image.fromstring(pixels, size, 'RGBA').convert_alpha()
- self.entries.append(entry)
- except Exception:
- self.failed += 1
- self.entries.sort(key=lambda n: (int(n['name'][4:]), n['elem_type']))
- while self.pending and len(self.jobs) < 8:
- entry = self.pending.pop(0)
- self.jobs[self.pool.submit(decode, self.root, entry)] = True
- if self.selected_job and self.selected_job.done() and not self.app.placement.active:
- job, self.selected_job = self.selected_job, None
- try:
- entry, size, pixels = job.result()
- img = pygame.image.fromstring(pixels, size, 'RGBA').convert_alpha()
- kind, library, name = entry['elem_type'], entry['type'], entry['name']
- if kind == 'floor':
- floor.floors.setdefault(library, {})[name] = img
- else:
- obstacle.obstacles.setdefault(library, {})[name] = dict(TYPE=library, NAME=name,
- WIDTH=entry['width'], HEIGHT=entry['height'], STAND=[Frame(img, entry['cx'], entry['cy'])])
- self.app.show_obstacle = True
- self.app.tools.choose('paint')
- self.app.current_elem = dict(elem_type=kind, type=library, name=name)
- selection = self.app.selection
- selection.group = [dict(layer=kind, type=library, name=name, x=0, y=0)]
- selection.clipboard_text = selection.read_clipboard()
- self.app.redraw_floor_obstacle_trigger = True
- self.app.menu.notify('已选择 '+library+'/'+name+';左键放置')
- except Exception as error:
- self.app.menu.notify('素材读取失败:'+str(error))
- def handle_event(self, event):
- if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and self.button.collidepoint(event.pos):
- self.toggle()
- return True
- if not self.visible:
- return False
- pos = getattr(event, 'pos', pygame.mouse.get_pos())
- if pos[0] < WINDOW_W:
- if event.type == pygame.MOUSEBUTTONDOWN:
- self.dropdown = False
- return False
- if event.type == pygame.MOUSEBUTTONDOWN:
- self.app.menu.block_pointer = True
- if event.button in (4, 5):
- self.scroll(-1 if event.button == 4 else 1)
- elif event.button == 1:
- if self.header.collidepoint(pos):
- self.dropdown = not self.dropdown
- elif self.dropdown:
- index = (pos[1]-80)//30 + self.folder_offset
- if 80 <= pos[1] < 80+min(18, len(self.libraries)-self.folder_offset)*30 and 0 <= index < len(self.libraries):
- self.choose_library(self.libraries[index])
- else:
- self.dropdown = False
- elif 112 <= pos[1] < WINDOW_H:
- col, row = (pos[0]-WINDOW_W-12)//154, (pos[1]-112)//144
- index = (self.offset+row)*3+col
- if 0 <= col < 3 and 0 <= row < 5 and 0 <= index < len(self.entries):
- if self.selected_job:
- self.selected_job.cancel()
- self.selected_job = self.pool.submit(decode, self.root, self.entries[index], True)
- return True
- if event.type == pygame.MOUSEWHEEL:
- self.scroll(-event.y)
- return event.type in (pygame.MOUSEWHEEL, pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP)
- def scroll(self, delta):
- if self.dropdown:
- self.folder_offset = max(0, min(max(0, len(self.libraries)-18), self.folder_offset+delta))
- else:
- self.offset = max(0, min(max(0, (len(self.entries)+2)//3-5), self.offset+delta))
- def draw_button(self):
- screen, font = self.app.screen, self.app.text_font
- pygame.draw.rect(screen, (22, 26, 33) if self.visible else (53, 61, 74), self.button)
- pygame.draw.rect(screen, (144, 155, 173), self.button, 1)
- text = font.render('素材库', True, (237, 240, 245))
- screen.blit(text, text.get_rect(center=self.button.center))
- def draw(self):
- screen, font = self.app.screen, self.app.text_font
- pygame.draw.rect(screen, (35, 39, 46), (WINDOW_W, 32, TOOL_PANEL_WIDTH, WINDOW_H-32))
- pygame.draw.rect(screen, (144, 155, 173), self.header, 1)
- screen.blit(font.render((self.library or '选择素材子库')+' ▼', True, (235, 235, 240)), (self.header.x+8, self.header.y+6))
- loading = self.scan_job or self.jobs or self.pending
- status = '%d 个素材%s%s' % (len(self.entries), ' · 加载中…' if loading else '', ' · 跳过 %d 个无效素材' % self.failed if self.failed else '')
- screen.blit(font.render(status, True, (170, 185, 200)), (WINDOW_W+12, 86))
- for i, entry in enumerate(self.entries[self.offset*3:self.offset*3+15]):
- rect = pygame.Rect(WINDOW_W+12+(i%3)*154, 112+(i//3)*144, 146, 136)
- selected = self.app.current_elem == {k: entry[k] for k in ('elem_type', 'type', 'name')}
- pygame.draw.rect(screen, (22, 26, 33) if selected else (52, 59, 70), rect)
- pygame.draw.rect(screen, (245, 195, 80) if selected else (120, 135, 150), rect, 2 if selected else 1)
- screen.blit(entry['thumbnail'], (rect.x+17, rect.y+4))
- label = font.render(entry['name'], True, (235, 238, 245))
- screen.blit(label, label.get_rect(center=(rect.centerx, rect.y+104)))
- label = font.render('%s %d×%d' % ('地板' if entry['elem_type']=='floor' else '障碍', entry['width'], entry['height']), True, (175, 190, 205))
- screen.blit(label, label.get_rect(center=(rect.centerx, rect.y+124)))
- rows = (len(self.entries)+2)//3
- if rows > 5:
- track = pygame.Rect(WINDOW_W+TOOL_PANEL_WIDTH-12, 112, 6, 712)
- pygame.draw.rect(screen, (22, 26, 33), track)
- height = max(24, round(track.height*5/rows))
- pygame.draw.rect(screen, (145, 160, 180), (track.x, track.y+round((track.height-height)*self.offset/(rows-5)), track.width, height))
- screen.blit(font.render('滚轮浏览素材 · 再点“素材库”返回工具栏', True, (170, 185, 200)), (WINDOW_W+12, 845))
- if self.dropdown:
- for i, name in enumerate(self.libraries[self.folder_offset:self.folder_offset+18]):
- rect = pygame.Rect(WINDOW_W+12, 80+i*30, TOOL_PANEL_WIDTH-24, 30)
- pygame.draw.rect(screen, (65, 77, 93) if name == self.library else (28, 33, 40), rect)
- pygame.draw.rect(screen, (110, 125, 140), rect, 1)
- screen.blit(font.render(name, True, (235, 235, 240)), (rect.x+8, rect.y+5))
- def close(self):
- for job in self.jobs:
- job.cancel()
- self.pool.shutdown(wait=False)
|