#!/usr/bin/env python3 """Stage AVA2's level 100-125 maps and dungeon maps for the 203 server and the zh client (metin2-server docs/FEATURE-LEVEL-120.md L2/L3). Server (install_maps.py): mobs-server.tsv (AVA2-only monsters, stones, NPCs with zh names), group.txt / group_group.txt blocks, the map directories and their map/index lines. Client: the ava2maps pack = locale/zh/mob_proto with the new rows, every map / model / property file the zh client lacks, locale/zh/atlasinfo.txt with the new maps, property/mt_extra_list.txt (read by CPythonBackground::__CreateProperty) and locale/zh/mt_ava2maps.txt (race names and zone names for the mt_ava2maps script). Usage: see build_zh_locale.build_ava2_maps and --help. """ import argparse,json,re,shutil,subprocess,sys from collections import Counter from pathlib import Path HERE=Path(__file__).resolve().parent REPO=HERE.parents[2] sys.path.insert(0,str(REPO/'tools/epk_scan')) import epk_scan # Map directory -> (AVA2 server map index, zh zone name). None of the indexes is used on 203. MAPS={'plechito_desert_map_01':(57,'法老沙漠'), 'metin2_map_elemental_04_rework':(37,'元素圣地'), 'metin2_map_eastplain_01':(129,'东间平原'), 'metin2_map_eastplain_02':(130,'西间荒原'), 'metin2_map_eastplain_03':(131,'南间深渊'), 'metin2_map_empirecastle':(132,'皇城'), 'metin2_map_dawnmist_dungeon_01':(210,'晨雾地下城'), 'metin2_map_n_flame_dragon':(212,'赤龙巢穴'), 'metin2_map_n_snow_dungeon_01':(352,'冰雪地下城'), 'defensawe_hydra':(355,'九头蛇船防')} # The zh client already ships these maps (files and atlasinfo row). CLIENT_HAS={'metin2_map_n_snow_dungeon_01'} # AVA2 leaves these Town.txt files empty (players would land at the map's corner): the 10107 warp landing. TOWN={'metin2_map_eastplain_01':b'133\t415\r\n'} # defensawe_hydra (972800,153600 2x2) is 203's metin2_map_empirewar03; this corner is free on 203 and in # the zh atlas. The shipdefense quest (L4) must shift its coordinates by the same delta. RELOCATE={'defensawe_hydra':(3276800,0)} # Server map files; stone2.txt is appended to stone.txt. MAP_FILES=('Setting.txt','Town.txt','server_attr','regen.txt','npc.txt','boss.txt','stone.txt','dungeon.txt') REGEN_FILES=('regen.txt','npc.txt','boss.txt','stone.txt','stone2.txt','dungeon.txt') # Yohara (AVA2 levels 119-125): AVA2 gives them the plechito level 101 exp; rescale geometrically to the # level 120 value of the plechito curve, bosses x10. YOHARA=range(6686,6732) def yohara_exp(level,rank):return round(83333*(117005/83333)**((level-101)/19)*(10 if rank=='BOSS' else 1)) # Rows of the Yohara NPCs that AVA2 wrote with one column out of place (EMPIRE holds the immune flags) are # rebuilt from this ordinary NPC (vnum, name and folder kept). NPC_TEMPLATE=20016 ON_CLICK_TALK='2' # Mob model folders RaceManager searches. MODEL_DIRS=('monster','monster2','npc','npc2') TIMER_BOSSES=('nemere','hydra','meley','razador','jotun','devil') # Files the closure follows (text) and the reference pattern (closure of AVA2 packs). NAMES=re.compile(rb'[\w \-:./\\]+?\.(?:dds|tga|jpg|bmp|png|mde|mse|gr2|spt|msf|wav|mp3|mss|msa|msm|msenv|prb|prt|pre|prd|pra|sub|txt|atr|raw|wtr|obv)(?=["\s\x00]|$)',re.I) TEXT=('.mse','.mde','.msm','.msa','.mss','.msenv','.prb','.prt','.pre','.prd','.pra','.sub','.txt','.msf','.spt') EXTRA_PROPERTY_DIR='property/mt_ava2/' def mob_enums(proto_reader): src=proto_reader.read_text(encoding='latin1');src=src[src.index('arRank[]')-32:] arr=lambda name:re.findall(r'"([^"]+)"',re.search(r'string\s+'+name+r'\[\]\s*=\s*\{(.*?)\};',src,re.S).group(1)) return {k:arr(v) for k,v in (('rank','arRank'),('type','arType'),('battle','arBattleType'),('size','arSize'), ('ai','arAIFlag'),('race','arRaceFlag'),('immune','arImmuneFlag'))} def norm(path):return path.strip().strip('"').lower().replace('\\','/') def motion_references(path,raw): """motlist rows are mode, motion, filename, weight (not quoted resource strings).""" folder=path.rsplit('/',1)[0] return [folder+'/'+norm(t[2]) for line in raw.decode('latin1').splitlines() if len(t:=line.split())>=3 and t[2].lower().endswith('.msa')] def number(text): try:return float(text) except ValueError:return 0.0 def names(): out={} for line in (HERE/'names_zh.tsv').read_text().splitlines(): if line and not line.startswith('#'):v,n=line.split('\t');out[int(v)]=n return out class Pack: """The client's effective pack files (pack/Index order, first registered pack wins), without `skip`.""" def __init__(self,client,skip): _,self.keys,order,packs,_=epk_scan.load(client,epk_scan.refroot.reference_root()) self.index={} for name,_ in order: p=packs.get(name) if name==skip or not p or p['missing']:continue for e in p['entries']:self.index.setdefault(norm(e['name']),(p,e)) def __contains__(self,path):return path in self.index def get(self,path): p,e=self.index[path] with open(p['epk'],'rb') as f: f.seek(e['pos']);stored=f.read(e['size']) if e['type']==0:return stored f.seek(e['pos']);data=f.read(epk_scan.lz_object_len(stored[:16])) return epk_scan.lz_object(data,self.keys['s_adwEterPackSecurityKey'] if e['type']==2 else None) def ava_index(pack_maker): """ArchivedPath (lowercase) -> source file, first pack in AVA2 pack/Index wins. CEterFileDict is a multimap and GetItem returns the earliest registration, so a duplicate path resolves to the pack listed first in Index (e.g. Maps before Patch_dungeon_meley), not to the alphabetically first manifest.""" xmls={x.name[:-len('_create.xml')].lower():x for x in pack_maker.glob('*_create.xml')} order=[l.strip().lower() for l in (pack_maker.parent/'pack/Index').read_text(encoding='latin1').splitlines() if l.strip()] order=[n for n in order if n in xmls]+sorted(set(xmls)-set(order)) index={} for name in order: for archived,source in re.findall(r'ArchivedPath="([^"]+)">',xmls[name].read_text(encoding='latin1')): index.setdefault(archived.lower().replace('\\','/'),pack_maker.parent/source) return index def proto_rows(path): rows={} for line in path.read_bytes().splitlines(): cols=[c.strip() for c in line.decode('latin1').split('\t')] if cols[0].isdigit():rows[int(cols[0])]=cols return rows def server_row(cols,zh,E,template): """AVA2 db/mob_proto.txt columns -> 203 server row (str columns, zh name).""" c=list(cols)+['0']*(71-len(cols)) if not re.fullmatch(r'-?\d*',c[11]): # shifted NPC row c=list(template);c[0],c[12]=cols[0],cols[12];c[13]=ON_CLICK_TALK c[1]=zh for i,k in ((7,'ai'),(9,'race'),(10,'immune')): c[i]=','.join(t for t in (x.strip() for x in c[i].split(',')) if t in E[k]) try:float(c[51]) except ValueError:c[51]=c[51].split('.')[0] # AVA2 "2.000.000" if int(c[0]) in YOHARA and c[3]=='MONSTER':c[25]=str(yohara_exp(int(c[5]),c[2])) return c[:71] def client_row(c,E): """Server row -> mob_proto_patch fields (tests/port/mob_proto_patch.cpp order).""" idx=lambda k,v:E[k].index(v) if v in E[k] else 0 bits=lambda k,v:sum(1< " for the server; the client shows the place only. name=c[1].split(' ')[0] if c[3]=='WARP' else c[1] return (text+'\t'+c[12]+'\t'+name).encode('gbk') def blocks(raw,member): """group.txt / group_group.txt -> {vnum: (block bytes, [member vnums])}; member(tokens) -> vnum or None.""" out={};lines=raw.replace(b'\r\n',b'\n').split(b'\n');i=0 while i=2 and t[0].lower()==b'vnum':vnum=int(t[1]) elif t and t[0]!=b'{' and t[0]!=b'}': m=member(t) if m is not None:members.append(m) if vnum is not None:out.setdefault(vnum,(b'\r\n'.join(l.rstrip() for l in body),members)) i=j i+=1 return out def regen_lines(raw): """Regen file -> [(line, kind, vnum)] (kind m/g/r..., None for blank/unknown lines).""" out=[] for line in raw.replace(b'\r\n',b'\n').split(b'\n'): t=line.split() if len(t)>=10 and t[-1].isdigit() and t[0][:1].isalpha():out.append((line.rstrip(),t[0][:1].decode().lower(),int(t[-1]))) elif line.strip():out.append((line.rstrip(),None,None)) return out def prepare(ava,proto_reader,client,output,mob_tool,gr2_tool,packer): srv=ava/'2. Backup SF+SRC and SQL/home/srv1';pack_maker=ava/'1. Client DEV/pack_maker' loc=srv/'share/locale/germany' if not (loc/'map').is_dir() or not (srv/'db/mob_proto.txt').is_file(): raise SystemExit('AVA2 maps need the extracted server tree (AVA2/TEST/2. Backup SF+SRC and SQL/home/srv1)') E=mob_enums(proto_reader);zh=names();AP=proto_rows(srv/'db/mob_proto.txt') assert zh.keys()<=AP.keys(),sorted(zh.keys()-AP.keys()) report={'warnings':[]};warn=report['warnings'].append output.mkdir(parents=True,exist_ok=True) stage=output/'server' if stage.exists():shutil.rmtree(stage) (stage/'map').mkdir(parents=True) # ---------------------------------------------------------------- server: mob rows template=AP[NPC_TEMPLATE] srows={v:server_row(AP[v],zh[v],E,template) for v in sorted(zh)} (stage/'mobs-server.tsv').write_bytes(b''.join('\t'.join(r).encode('gbk')+b'\n' for r in srows.values())) report['mobs']=len(srows) # ---------------------------------------------------------------- server: map dirs + groups G=blocks((loc/'group.txt').read_bytes(),lambda t:int(t[-1]) if t[-1].isdigit() and (t[0].isdigit() or t[0].lower()==b'leader') else None) GG=blocks((loc/'group_group.txt').read_bytes(),lambda t:int(t[1]) if t[0].isdigit() and t[1].isdigit() else None) groups=set();ggroups=set();mobs=set() def add_mob(v): if v in mobs:return mobs.add(v);r=srows.get(v) or AP.get(v) if r is None:return if r[3]=='STONE': lo,hi=sorted((int(number(r[27])),int(number(r[28])))) if hi-lo<50: for g in range(lo,hi+1): if g in G:add_group(g) if number(r[33]):add_mob(int(number(r[33]))) def add_group(g): if g in groups:return groups.add(g) for m in G[g][1]:add_mob(m) index_lines=[];origin={} for m,(index,_) in MAPS.items(): src=loc/'map'/m;dst=stage/'map'/m;dst.mkdir() dropped=Counter() for f in MAP_FILES: raw=(src/f).read_bytes() if (src/f).is_file() else b'' if f=='stone.txt' and (src/'stone2.txt').is_file():raw=raw.rstrip(b'\r\n')+b'\r\n'+(src/'stone2.txt').read_bytes() if f=='Town.txt' and m in TOWN:raw=TOWN[m] if f=='Setting.txt' and m in RELOCATE: raw=re.sub(rb'BasePosition\s+\d+\s+\d+',b'BasePosition\t%d\t%d'%RELOCATE[m],raw);assert b'\t%d\t'%RELOCATE[m][0] in raw if f=='Setting.txt':origin[m]=tuple(map(int,re.search(rb'BasePosition\s+(\d+)\s+(\d+)',raw).groups())) if f in REGEN_FILES: kept=[] for line,kind,v in regen_lines(raw): if kind=='g' and v not in G or kind=='r' and v not in GG:dropped[(kind,v)]+=1;continue if kind=='g':add_group(v) elif kind=='r': ggroups.add(v) for g in GG[v][1]: if g in G:add_group(g) elif kind:add_mob(v) kept.append(line) raw=b'\r\n'.join(kept)+(b'\r\n' if kept else b'') if f=='Town.txt' and not raw.strip() and m not in TOWN:warn('%s: empty Town.txt (map corner)'%m) if f in ('Setting.txt','server_attr') and not raw:raise SystemExit('%s/%s missing'%(m,f)) (dst/f).write_bytes(raw) for (kind,v),n in sorted(dropped.items()):warn('%s: dropped %d regen lines of missing %s %d'%(m,n,'group' if kind=='g' else 'groupgroup',v)) index_lines.append(b'%d %s'%(index,m.encode())) (stage/'index.txt').write_bytes(b'\n'.join(index_lines)+b'\n') (stage/'group.txt').write_bytes(b''.join(G[g][0]+b'\r\n' for g in sorted(groups))) (stage/'group_group.txt').write_bytes(b''.join(GG[g][0]+b'\r\n' for g in sorted(ggroups))) # Every regen / group member must be a 203 mob or one of ours; install_maps.py checks the rest on the server. (stage/'mob_refs.txt').write_text(''.join('%d\n'%v for v in sorted(mobs))) # Server motion data (data/monster/: motlist.txt + .msa timing); install_maps.py adds only folders 203 lacks. # The core opens the folder exactly as spelled (FreeBSD); mob_proto spellings that differ only in case # resolve to the one real folder here, so each is copied once under its on-disk name. motion=srv/'share/data/monster';real={d.name.lower():d.name for d in motion.iterdir() if d.is_dir()};folders=set() for v in mobs|set(srows): r=srows.get(v) or AP.get(v) if r and r[12].lower() in real:folders.add(real[r[12].lower()]) for f in sorted(folders): shutil.copytree(motion/f,stage/'data/monster'/f,ignore=lambda d,names:[n for n in names if n.lower().endswith(('.dds','.gr2','.tga','.jpg'))]) report['motion_folders']=len(folders) report.update(groups=len(groups),group_groups=len(ggroups),mob_refs=len(mobs)) # ---------------------------------------------------------------- client have=Pack(client,'ava2maps');files=ava_index(pack_maker) assets=output/'assets' if assets.exists():shutil.rmtree(assets) target=assets/'locale/zh';target.mkdir(parents=True) crows=[client_row(srows[v],E) for v in sorted(srows)] (output/'mobs-client.tsv').write_bytes(b'\n'.join(crows)+b'\n') (output/'base_mob_proto').write_bytes(have.get('locale/zh/mob_proto')) subprocess.run([str(mob_tool),str(output/'base_mob_proto'),str(output/'mobs-client.tsv'),str(target/'mob_proto')],check=True) # atlasinfo: the locale file the client reads first (CPythonBackground::Initialize), from the root one. base=have.get('locale/zh/atlasinfo.txt') if 'locale/zh/atlasinfo.txt' in have else have.get('atlasinfo.txt') atlas=[l for l in base.replace(b'\r\n',b'\n').split(b'\n') if l.strip()] atlas_names={l.split()[0] for l in atlas} for m in MAPS: if m in CLIENT_HAS:continue setting=files[m+'/setting.txt'].read_bytes() # The server Setting is authoritative: AVA2's Maps pack shadows Patch_dungeon_meley's # flame_dragon setting.txt with BasePosition 0 0, which would misplace the client terrain. bx,by=origin[m] w,h=map(int,re.search(rb'MapSize\s+(\d+)\s+(\d+)',setting).groups()) if m.encode() in atlas_names:raise SystemExit('zh atlasinfo already lists %s'%m) atlas.append(b'%s\t%d\t%d\t%d\t%d'%(m.encode(),bx,by,w,h)) (target/'atlasinfo.txt').write_bytes(b'\r\n'.join(atlas)+b'\r\n') # Properties: AVA2-only CRCs placed on the new maps. def crc_of(raw): t=raw.split(b'\n',2) return int(t[1].strip()) if raw[:4]==b'YPRT' and len(t)>1 and t[1].strip().isdigit() else None zh_crc={crc_of(have.get(p)) for p in have.index if p.startswith('property/') and p!='property/reserve'} ava_crc={} for p in files: if p.startswith('property/') and p!='property/reserve': c=crc_of(files[p].read_bytes()) if c is not None:ava_crc.setdefault(c,p) placed=set() for m in MAPS: if m in CLIENT_HAS:continue for p in files: if p.startswith(m+'/') and p.endswith(('/areadata.txt','/areaambiencedata.txt')): t=files[p].read_bytes().decode('latin1').split('\n') placed|={int(t[i+2].strip()) for i,l in enumerate(t) if l.startswith('Start Object')} extra=[];missing_props=[] for c in sorted(placed-zh_crc): if c not in ava_crc:missing_props.append(c);continue p=ava_crc[c];dest=p if p not in have else EXTRA_PROPERTY_DIR+p[len('property/'):] extra.append((p,dest)) report.update(properties=len(extra),properties_missing=missing_props) # A known race ID does not imply its model exists. 9018 is already in the # base npclist but its hydra_chest folder is absent; seed every required # AVA2 folder and let visit() deduplicate files actually present in packs. def npclist(raw): race={};alias={} for l in raw.decode('latin1').splitlines(): t=l.split() if len(t)>=2 and t[0].isdigit(): if t[0]=='0' and len(t)>=3:alias[t[1].lower()]=norm(t[2]) elif t[0]!='0':race[int(t[0])]=norm(t[1]) return race,alias AR,AA=npclist(files['npclist.txt'].read_bytes());ZR,_=npclist(have.get('npclist.txt')) races=[];srcs={};model_seeds=[] for v in sorted(zh): name=AR.get(v) if not name:warn('race %d: no AVA2 npclist row'%v);continue src=AA.get(name,name) if ZR.get(v)!=name:races.append((v,name)) if src!=name:srcs[name]=src found=[p for d in MODEL_DIRS for p in files if p.startswith('d:/ymir work/%s/%s/'%(d,src))] if not found:warn('race %d: no AVA2 model folder %s'%(v,src)) model_seeds+=found # Closure over the map, atlas, property and model files. seeds=[p for m in MAPS if m not in CLIENT_HAS for p in files if p.startswith(m+'/')] seeds+=[p for m in MAPS if m not in CLIENT_HAS for p in ('d:/ymir work/ui/atlas/%s/atlas.sub'%m,) if p in files] seeds+=[p for p,_ in extra]+model_seeds # Dungeon timer images (DungeonTimerScript.inc, the AVA2 dungeons of ../ava2-dungeons) and their timer.tga. seeds+=['d:/ymir work/ui/game/dungeontimer/%s_%s.sub'%(b,k) for b in TIMER_BOSSES for k in ('back','timer')] need=set();misses=Counter();gr2=[] def refs(a): out=[] if a.endswith('/motlist.txt'):out+=motion_references(a,files[a].read_bytes()) if a.endswith(TEXT) and not a.endswith('/motlist.txt'): for n in NAMES.findall(files[a].read_bytes()): n=norm(n.decode('latin1')) if not n:continue if n.startswith('d:/') or n in files or n in have:out.append(n) elif a.endswith('.sub'):out.append('d:/ymir work/ui/'+n) elif n.endswith('.msenv'):out.append('d:/ymir work/environment/'+n.rsplit('/',1)[-1]) else:out.append(a.rsplit('/',1)[0]+'/'+n) if a.endswith('.gr2'):gr2.append(a) return out def visit(q,frm): if q in have or q in need:return if q not in files: same=frm.rsplit('/',1)[0]+'/'+q.rsplit('/',1)[-1] if same!=q and (same in have or same in files):visit(same,frm) else:misses[q]+=1 return need.add(q) for r in refs(q):visit(r,q) for s in seeds:visit(s,'seed') done=set() while len(done)