AVA2 cross-platform client parity baseline
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare port constants to preprocessed AVA2 Windows Packet.h, never another client."""
|
||||
from pathlib import Path
|
||||
import re,subprocess,json,sys
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
compiler=sys.argv[1] if len(sys.argv)>1 else 'clang++'
|
||||
original=root/'upstream/ava2-client/UserInterface'
|
||||
packet=(original/'Packet.h').read_text(errors='replace')
|
||||
packet=packet.replace('#pragma once','')
|
||||
packet=re.sub(r'^\s*#\s*include[^\n]*','',packet,flags=re.M)
|
||||
translation=f'#include "{original / "Locale_inc.h"}"\n#include "{root / "upstream/ava2-client/EterBase/ServiceDefs.h"}"\n'+packet
|
||||
processed=subprocess.check_output([compiler,'-E','-P','-x','c++','-'],input=translation,text=True)
|
||||
values={}
|
||||
for body in re.findall(r'\benum\s*\w*\s*\{(.*?)\}',processed,re.S):
|
||||
value=-1
|
||||
for member in body.split(','):
|
||||
match=re.fullmatch(r'\s*(\w+)\s*(?:=\s*(0x[0-9a-fA-F]+|\d+))?\s*',member)
|
||||
if not match: continue
|
||||
value=int(match[2],0) if match[2] else value+1
|
||||
values[match[1]]=value
|
||||
aliases={'HEADER_CG_CHARACTER_CREATE':'HEADER_CG_PLAYER_CREATE','HEADER_CG_CHARACTER_DELETE':'HEADER_CG_PLAYER_DESTROY','HEADER_CG_MOVE':'HEADER_CG_CHARACTER_MOVE','HEADER_CG_CHARACTER_SELECT':'HEADER_CG_PLAYER_SELECT','HEADER_GC_CHARACTER_CREATE_SUCCESS':'HEADER_GC_PLAYER_CREATE_SUCCESS','HEADER_GC_CHARACTER_CREATE_FAILURE':'HEADER_GC_PLAYER_CREATE_FAILURE','HEADER_GC_CHARACTER_DELETE_SUCCESS':'HEADER_GC_PLAYER_DELETE_SUCCESS','PHASE_OFFLINE':'PHASE_CLOSE'}
|
||||
port=(root/'src/eter_net/Packet.h').read_text()
|
||||
checked=[];mismatches=[];unmatched=[]
|
||||
for name,value in re.findall(r'\b((?:HEADER_[CG][GC]_|PHASE_|EXCHANGE_SUBHEADER_)[A-Z0-9_]+)\s*=\s*(0x[0-9a-fA-F]+|\d+)',port):
|
||||
reference=aliases.get(name,name)
|
||||
if reference not in values: unmatched.append(name);continue
|
||||
row={'name':name,'windows_name':reference,'windows':values[reference],'port':int(value,0)}
|
||||
checked.append(row)
|
||||
if row['windows']!=row['port']:mismatches.append(row)
|
||||
report={'reference':'upstream/ava2-client/UserInterface/Packet.h preprocessed with AVA2 Windows feature headers','checked':len(checked),'mismatches':mismatches,'unmatched':unmatched}
|
||||
(root/'docs/AVA2-PACKET-CONSTANTS.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(json.dumps(report,indent=2))
|
||||
if mismatches or unmatched:sys.exit(1)
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Method-name comparison against active AVA2 Windows extension tables.
|
||||
Presence is not behavioral parity. Macros use ONLY AVA2 Windows headers.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import re,json,subprocess,sys
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
compiler=sys.argv[1] if len(sys.argv)>1 else 'clang++'
|
||||
headers=''.join(f'#include "{root/p}"\n' for p in ('upstream/ava2-client/UserInterface/Locale_inc.h','upstream/ava2-client/EterBase/ServiceDefs.h'))
|
||||
def modules(paths,preprocess=False):
|
||||
result={}
|
||||
for path in paths:
|
||||
source=path.read_text(errors='replace')
|
||||
if preprocess:
|
||||
source=re.sub(r'^\s*#\s*include[^\n]*','',source,flags=re.M)
|
||||
source=source.replace('#pragma once','')
|
||||
source=subprocess.check_output([compiler,'-E','-P','-x','c++','-'],input=headers+source,text=True,stderr=subprocess.DEVNULL)
|
||||
tables=list(re.finditer(r'PyMethodDef\s+(\w+)\s*\[\s*\]\s*=\s*\{(.*?)\};',source,re.S))
|
||||
for call in re.finditer(r'Py_InitModule\s*\(\s*"([^"\n]+)"\s*,\s*(\w+)',source):
|
||||
candidates=[t for t in tables if t[1]==call[2] and t.start()<call.start()]
|
||||
if not candidates: continue
|
||||
methods={name:handler for name,handler in re.findall(r'\{\s*"([^"\n]+)"\s*,\s*(\w+)\s*,',candidates[-1][2])}
|
||||
result[call[1]]={'path':str(path.relative_to(root)),'methods':methods}
|
||||
return result
|
||||
windows=modules(sorted((root/'upstream/ava2-client').rglob('*Module.cpp')),True)
|
||||
port=modules(sorted((root/'src').glob('python_*.cpp')))
|
||||
rows=[]
|
||||
for name,reference in sorted(windows.items()):
|
||||
target=port.get(name,{'methods':{}});original=set(reference['methods']);current=set(target['methods'])
|
||||
rows.append({'module':name,'windows_file':reference['path'],'port_file':target.get('path'),'windows_methods':len(original),'missing':sorted(original-current),'extra':sorted(current-original),'placeholder':sorted(method for method in original¤t if 'dummy' in target['methods'][method])})
|
||||
report={'basis':'AVA2 Windows active method tables; module constants/signatures/behavior require further audit','modules':rows,'missing_method_count':sum(len(r['missing']) for r in rows),'placeholder_method_count':sum(len(r['placeholder']) for r in rows)}
|
||||
(root/'docs/AVA2-PYTHON-INTERFACES.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(f"{len(rows)} Windows modules compared; {report['missing_method_count']} missing methods; {report['placeholder_method_count']} overlapping placeholder methods")
|
||||
for row in rows:
|
||||
if row['missing']: print(row['module'],len(row['missing']),', '.join(row['missing'][:8]))
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Preprocess AVA2 client/server macro headers; record the verified login dialect."""
|
||||
import json, subprocess, sys
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
compiler=sys.argv[1]
|
||||
def macros(path):
|
||||
output=subprocess.check_output([compiler,'-E','-dM','-x','c++',str(root/path)],text=True)
|
||||
return {line.split()[1] for line in output.splitlines() if line.startswith('#define ')}
|
||||
client=macros('upstream/ava2-client/UserInterface/Locale_inc.h') | macros('upstream/ava2-client/EterBase/ServiceDefs.h')
|
||||
server=macros('upstream/ava2-server/common/CommonDefines.h') | macros('upstream/ava2-server/common/service.h')
|
||||
pairs=[('five_slots','ENABLE_PLAYER_PER_ACCOUNT5','ENABLE_PLAYER_PER_ACCOUNT5'),('sash','ENABLE_SASH_SYSTEM','__SASH_SYSTEM__'),('conqueror','ENABLE_CONQUEROR_LEVEL','ENABLE_CONQUEROR_LEVEL'),('improved_encryption','_IMPROVED_PACKET_ENCRYPTION_','_IMPROVED_PACKET_ENCRYPTION_'),('version_login_field','ENABLE_VERSION_SYSTEM','ENABLE_VERSION_SYSTEM'),('wolfman','ENABLE_WOLFMAN_CHARACTER','ENABLE_WOLFMAN_CHARACTER'),('bank','ENABLE_MANAGER_BANK_SYSTEM','ENABLE_MANAGER_BANK_SYSTEM'),('support','ENABLE_SUPPORT_SYSTEM','ENABLE_SUPPORT_SYSTEM')]
|
||||
features={name:{'client':a in client,'server':b in server} for name,a,b in pairs}
|
||||
for name in ('five_slots','sash','conqueror'):
|
||||
assert features[name]=={'client':True,'server':True},name
|
||||
for name in ('improved_encryption','version_login_field'):
|
||||
assert features[name]=={'client':False,'server':False},name
|
||||
report={'features':features,'dialect':{'auth_login_header':111,'auth_login_bytes':65,'game_login_header':109,'game_login_bytes':52,'character_success_header':32,'character_success_bytes':444,'player_bytes':70,'sequence_enabled':True,'sequence_bytes':1,'encryption_block_bytes':8},'unresolved_feature_mismatches':[name for name,v in features.items() if v['client']!=v['server']]}
|
||||
out=Path(sys.argv[2]);out.parent.mkdir(parents=True,exist_ok=True);out.write_text(json.dumps(report,indent=2)+'\n')
|
||||
print('Login macro profile verified; unresolved gameplay flags:',', '.join(report['unresolved_feature_mismatches']))
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Conservative static inventory: implemented names do not establish behavioral parity."""
|
||||
import json,re
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
rows=[]
|
||||
for path in sorted((root/'src').glob('python_*.cpp')):
|
||||
source=path.read_text()
|
||||
for name,handler in re.findall(r'\{\s*"([^"]+)"\s*,\s*(\w+)\s*,\s*METH_',source):
|
||||
if 'dummy' in handler:
|
||||
rows.append({'file':str(path.relative_to(root)),'api':name,'handler':handler,'status':'placeholder'})
|
||||
report={'scope':'Static Python method-table inventory; excludes hidden no-ops, renderer and packet behavior. Full parity is NOT established.','placeholder_count':len(rows),'placeholders':rows}
|
||||
output=root/'docs/WINDOWS-PARITY-INVENTORY.json'
|
||||
output.write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(f'{len(rows)} placeholder bindings; report: {output}')
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
net_cpp_src = root / "upstream/ava2-client/UserInterface/PythonNetworkStreamModule.cpp"
|
||||
|
||||
with open(net_cpp_src, "r", encoding="latin1") as f:
|
||||
text = f.read()
|
||||
|
||||
methods = re.findall(r'\{\s*"(\w+)"\s*,\s*(\w+)\s*,', text)
|
||||
upstream_method_names = [m[0] for m in methods]
|
||||
|
||||
# Read current python_net.cpp
|
||||
with open(root / "src/python_net.cpp", "r") as f:
|
||||
current_net = f.read()
|
||||
|
||||
# We already have:
|
||||
implemented = {
|
||||
"SetHandler", "SetAccountConnectorHandler", "SetPhaseWindow", "ClearPhaseWindow",
|
||||
"SetLoginInfo", "ConnectToAccountServer", "Disconnect", "SetPacketSequenceMode",
|
||||
"SendSelectCharacterPacket", "GetAccountCharacterSlotDataInteger", "GetAccountCharacterSlotDataString",
|
||||
"GetEmpireID", "Update", "GetConnectionState"
|
||||
}
|
||||
|
||||
missing = [m for m in upstream_method_names if m not in implemented]
|
||||
print(f"Total upstream methods: {len(upstream_method_names)}, already implemented: {len(implemented)}, missing to add: {len(missing)}")
|
||||
|
||||
dummy_functions = """
|
||||
PyObject* net_dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; }
|
||||
PyObject* net_dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); }
|
||||
PyObject* net_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); }
|
||||
PyObject* net_dummy_empty_str(PyObject*, PyObject*) { return PyString_FromString(""); }
|
||||
"""
|
||||
|
||||
# Insert dummy functions and missing methods in s_methods
|
||||
method_entries = []
|
||||
for name in missing:
|
||||
if name.startswith("Is") or name.startswith("Get"):
|
||||
if "Name" in name or "Command" in name or "Info" in name:
|
||||
method_entries.append(f' {{"{name}", net_dummy_empty_str, METH_VARARGS, nullptr}},')
|
||||
else:
|
||||
method_entries.append(f' {{"{name}", net_dummy_zero, METH_VARARGS, nullptr}},')
|
||||
else:
|
||||
method_entries.append(f' {{"{name}", net_dummy_none, METH_VARARGS, nullptr}},')
|
||||
|
||||
print(f"Prepared {len(method_entries)} missing methods entries.")
|
||||
@@ -0,0 +1,35 @@
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
upstream = root / "upstream/ava2-client"
|
||||
|
||||
modules_spec = [
|
||||
("item", "initItem", "UserInterface/PythonItemModule.cpp"),
|
||||
("player", "initPlayer", "UserInterface/PythonPlayerModule.cpp"),
|
||||
("chrmgr", "initchrmgr", "UserInterface/PythonCharacterManagerModule.cpp"),
|
||||
("chr", "initchr", "UserInterface/PythonCharacterModule.cpp"),
|
||||
("chat", "initChat", "UserInterface/PythonChatModule.cpp"),
|
||||
("snd", "initsnd", "UserInterface/PythonSoundManagerModule.cpp"),
|
||||
("background", "initBackground", "UserInterface/PythonBackgroundModule.cpp"),
|
||||
]
|
||||
|
||||
# We need to collect:
|
||||
# 1. All methods per module
|
||||
# 2. All constants per module with their exact evaluated integer values!
|
||||
|
||||
# Let's inspect which headers define all the constants needed.
|
||||
# For ItemData: all enums in CItemData
|
||||
# For GameType.h: c_Equipment_*, c_Inventory_*, c_Costume_*, etc.
|
||||
# For Packet.h: EPointTypes, etc.
|
||||
# For InstanceBase.h: CInstanceBase enums (DIR_*, etc.)
|
||||
# For RaceData.h / RaceMotionData.h: CRaceMotionData enums (NAME_*, etc.)
|
||||
# For PythonPlayer.h: CPythonPlayer enums
|
||||
# For PythonItem.h: CPythonItem enums
|
||||
# For PythonChat.h: CPythonChat enums
|
||||
# For PythonBackground.h: CPythonBackground enums
|
||||
|
||||
# Let us construct a single unified C++ file that stubs all external Win32/D3D dependencies,
|
||||
# includes the relevant enums and constants from upstream, and prints:
|
||||
# MODULE:NAME:VALUE
|
||||
@@ -0,0 +1,224 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
app_cpp = root / "upstream/ava2-client/UserInterface/PythonApplicationModule.cpp"
|
||||
|
||||
with open(app_cpp, "r", encoding="latin1") as f:
|
||||
content = f.read()
|
||||
|
||||
initapp_idx = content.find("void initapp()")
|
||||
if initapp_idx == -1:
|
||||
raise RuntimeError("initapp() not found")
|
||||
|
||||
initapp_body = content[initapp_idx:]
|
||||
|
||||
cursor_map = {
|
||||
"CPythonApplication::CURSOR_SHAPE_NORMAL": "0",
|
||||
"CPythonApplication::CURSOR_SHAPE_ATTACK": "1",
|
||||
"CPythonApplication::CURSOR_SHAPE_TARGET": "2",
|
||||
"CPythonApplication::CURSOR_SHAPE_TALK": "3",
|
||||
"CPythonApplication::CURSOR_SHAPE_CANT_GO": "4",
|
||||
"CPythonApplication::CURSOR_SHAPE_PICK": "5",
|
||||
"CPythonApplication::CURSOR_SHAPE_DOOR": "6",
|
||||
"CPythonApplication::CURSOR_SHAPE_CHAIR": "7",
|
||||
"CPythonApplication::CURSOR_SHAPE_MAGIC": "8",
|
||||
"CPythonApplication::CURSOR_SHAPE_BUY": "9",
|
||||
"CPythonApplication::CURSOR_SHAPE_SELL": "10",
|
||||
"CPythonApplication::CURSOR_SHAPE_CAMERA_ROTATE": "11",
|
||||
"CPythonApplication::CURSOR_SHAPE_HSIZE": "12",
|
||||
"CPythonApplication::CURSOR_SHAPE_VSIZE": "13",
|
||||
"CPythonApplication::CURSOR_SHAPE_HVSIZE": "14",
|
||||
"CPythonApplication::CURSOR_SHAPE_FISH": "15",
|
||||
"CPythonApplication::CURSOR_SHAPE_COUNT": "16",
|
||||
"CPythonApplication::CAMERA_TO_POSITIVE": "1",
|
||||
"CPythonApplication::CAMERA_TO_NEGITIVE": "-1",
|
||||
"CPythonApplication::CAMERA_STOP": "0",
|
||||
"CPythonApplication::INFO_ITEM": "0",
|
||||
"CPythonApplication::INFO_ACTOR": "1",
|
||||
"CPythonApplication::INFO_EFFECT": "2",
|
||||
"CPythonApplication::INFO_TEXTTAIL": "3",
|
||||
"CPythonApplication::LOCALE_DEFAULT": "0",
|
||||
"CPythonApplication::LOCALE_EN": "0",
|
||||
"CPythonApplication::LOCALE_DE": "1",
|
||||
"CPythonApplication::LOCALE_TR": "2",
|
||||
"CPythonApplication::LOCALE_PT": "3",
|
||||
"CPythonApplication::LOCALE_ES": "4",
|
||||
"CPythonApplication::LOCALE_FR": "5",
|
||||
"CPythonApplication::LOCALE_RO": "6",
|
||||
"CPythonApplication::LOCALE_PL": "7",
|
||||
"CPythonApplication::LOCALE_IT": "8",
|
||||
"CPythonApplication::LOCALE_CZ": "9",
|
||||
"CPythonApplication::LOCALE_HU": "10",
|
||||
"CPythonApplication::LOCALE_MAX_NUM": "11",
|
||||
"PLAYER_PER_ACCOUNT5": "5",
|
||||
"PLAYER_PER_ACCOUNT4": "4",
|
||||
"DEGREE_DIRECTION_SAME": "0",
|
||||
"DEGREE_DIRECTION_RIGHT": "1",
|
||||
"DEGREE_DIRECTION_LEFT": "2",
|
||||
"VK_LEFT": "0x25",
|
||||
"VK_UP": "0x26",
|
||||
"VK_RIGHT": "0x27",
|
||||
"VK_DOWN": "0x28",
|
||||
"VK_HOME": "0x24",
|
||||
"VK_END": "0x23",
|
||||
"VK_DELETE": "0x2E",
|
||||
}
|
||||
|
||||
extra_diks = {
|
||||
"DIK_NEXTTRACK": "0x99",
|
||||
"DIK_MUTE": "0xA0",
|
||||
"DIK_CALCULATOR": "0xA1",
|
||||
"DIK_PLAYPAUSE": "0xA2",
|
||||
"DIK_MEDIASTOP": "0xA4",
|
||||
"DIK_VOLUMEDOWN": "0xAE",
|
||||
"DIK_VOLUMEUP": "0xB0",
|
||||
"DIK_WEBHOME": "0xB2",
|
||||
"DIK_NUMPADCOMMA": "0xB3",
|
||||
"DIK_LWIN": "0xDB",
|
||||
"DIK_RWIN": "0xDC",
|
||||
"DIK_APPS": "0xDD",
|
||||
"DIK_KANJI": "0x94",
|
||||
"DIK_AX": "0x96",
|
||||
"DIK_UNLABELED": "0x97",
|
||||
"DIK_ABNT_C2": "0x7E",
|
||||
"DIK_PREVTRACK": "0x90",
|
||||
"DIK_YEN": "0x7D",
|
||||
}
|
||||
|
||||
output_lines = []
|
||||
for line in initapp_body.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("#if") or stripped.startswith("#else") or stripped.startswith("#endif"):
|
||||
output_lines.append(stripped)
|
||||
elif "PyModule_AddIntConstant" in stripped:
|
||||
subbed = re.sub(r'PyModule_AddIntConstant\s*\(\s*\w+\s*,', 'PyModule_AddIntConstant(module,', stripped)
|
||||
for k, v in cursor_map.items():
|
||||
subbed = subbed.replace(k, v)
|
||||
for k, v in extra_diks.items():
|
||||
subbed = re.sub(r'\b' + k + r'\b', v, subbed)
|
||||
output_lines.append(" " + subbed)
|
||||
|
||||
header = """// Auto-generated AVA2 app constants from upstream PythonApplicationModule.cpp
|
||||
// 1:1 strictly matched to AVA2 definition.
|
||||
#pragma once
|
||||
#include <Python.h>
|
||||
#include "../upstream/ava2-client/UserInterface/Locale_inc.h"
|
||||
|
||||
#ifndef DIK_ESCAPE
|
||||
#define DIK_ESCAPE 0x01
|
||||
#define DIK_1 0x02
|
||||
#define DIK_2 0x03
|
||||
#define DIK_3 0x04
|
||||
#define DIK_4 0x05
|
||||
#define DIK_5 0x06
|
||||
#define DIK_6 0x07
|
||||
#define DIK_7 0x08
|
||||
#define DIK_8 0x09
|
||||
#define DIK_9 0x0A
|
||||
#define DIK_0 0x0B
|
||||
#define DIK_MINUS 0x0C
|
||||
#define DIK_EQUALS 0x0D
|
||||
#define DIK_BACK 0x0E
|
||||
#define DIK_TAB 0x0F
|
||||
#define DIK_Q 0x10
|
||||
#define DIK_W 0x11
|
||||
#define DIK_E 0x12
|
||||
#define DIK_R 0x13
|
||||
#define DIK_T 0x14
|
||||
#define DIK_Y 0x15
|
||||
#define DIK_U 0x16
|
||||
#define DIK_I 0x17
|
||||
#define DIK_O 0x18
|
||||
#define DIK_P 0x19
|
||||
#define DIK_LBRACKET 0x1A
|
||||
#define DIK_RBRACKET 0x1B
|
||||
#define DIK_RETURN 0x1C
|
||||
#define DIK_LCONTROL 0x1D
|
||||
#define DIK_A 0x1E
|
||||
#define DIK_S 0x1F
|
||||
#define DIK_D 0x20
|
||||
#define DIK_F 0x21
|
||||
#define DIK_G 0x22
|
||||
#define DIK_H 0x23
|
||||
#define DIK_J 0x24
|
||||
#define DIK_K 0x25
|
||||
#define DIK_L 0x26
|
||||
#define DIK_SEMICOLON 0x27
|
||||
#define DIK_APOSTROPHE 0x28
|
||||
#define DIK_GRAVE 0x29
|
||||
#define DIK_LSHIFT 0x2A
|
||||
#define DIK_BACKSLASH 0x2B
|
||||
#define DIK_Z 0x2C
|
||||
#define DIK_X 0x2D
|
||||
#define DIK_C 0x2E
|
||||
#define DIK_V 0x2F
|
||||
#define DIK_B 0x30
|
||||
#define DIK_N 0x31
|
||||
#define DIK_M 0x32
|
||||
#define DIK_COMMA 0x33
|
||||
#define DIK_PERIOD 0x34
|
||||
#define DIK_SLASH 0x35
|
||||
#define DIK_RSHIFT 0x36
|
||||
#define DIK_MULTIPLY 0x37
|
||||
#define DIK_LMENU 0x38
|
||||
#define DIK_SPACE 0x39
|
||||
#define DIK_CAPITAL 0x3A
|
||||
#define DIK_F1 0x3B
|
||||
#define DIK_F2 0x3C
|
||||
#define DIK_F3 0x3D
|
||||
#define DIK_F4 0x3E
|
||||
#define DIK_F5 0x3F
|
||||
#define DIK_F6 0x40
|
||||
#define DIK_F7 0x41
|
||||
#define DIK_F8 0x42
|
||||
#define DIK_F9 0x43
|
||||
#define DIK_F10 0x44
|
||||
#define DIK_NUMLOCK 0x45
|
||||
#define DIK_SCROLL 0x46
|
||||
#define DIK_NUMPAD7 0x47
|
||||
#define DIK_NUMPAD8 0x48
|
||||
#define DIK_NUMPAD9 0x49
|
||||
#define DIK_SUBTRACT 0x4A
|
||||
#define DIK_NUMPAD4 0x4B
|
||||
#define DIK_NUMPAD5 0x4C
|
||||
#define DIK_NUMPAD6 0x4D
|
||||
#define DIK_ADD 0x4E
|
||||
#define DIK_NUMPAD1 0x4F
|
||||
#define DIK_NUMPAD2 0x50
|
||||
#define DIK_NUMPAD3 0x51
|
||||
#define DIK_NUMPAD0 0x52
|
||||
#define DIK_DECIMAL 0x53
|
||||
#define DIK_F11 0x57
|
||||
#define DIK_F12 0x58
|
||||
#define DIK_NUMPADENTER 0x9C
|
||||
#define DIK_RCONTROL 0x9D
|
||||
#define DIK_DIVIDE 0xB5
|
||||
#define DIK_SYSRQ 0xB7
|
||||
#define DIK_RMENU 0xB8
|
||||
#define DIK_PAUSE 0xC5
|
||||
#define DIK_HOME 0xC7
|
||||
#define DIK_UP 0xC8
|
||||
#define DIK_PRIOR 0xC9
|
||||
#define DIK_LEFT 0xCB
|
||||
#define DIK_RIGHT 0xCD
|
||||
#define DIK_END 0xCF
|
||||
#define DIK_DOWN 0xD0
|
||||
#define DIK_NEXT 0xD1
|
||||
#define DIK_INSERT 0xD2
|
||||
#define DIK_DELETE 0xD3
|
||||
#endif
|
||||
|
||||
namespace ava2 {
|
||||
inline void register_app_constants(PyObject* module) {
|
||||
"""
|
||||
|
||||
footer = """
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
out_file = root / "src/generated_app_constants.h"
|
||||
out_file.write_text(header + "\n".join(output_lines) + footer)
|
||||
print(f"Generated {out_file} with {len(output_lines)} lines.")
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract actual AVA2 Windows item declarations with their active feature guards."""
|
||||
from pathlib import Path
|
||||
import re,sys
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
packet=(root/'upstream/ava2-client/UserInterface/Packet.h').read_text(errors='replace')
|
||||
game=(root/'upstream/ava2-client/UserInterface/GameType.h').read_text(errors='replace')
|
||||
def decl(source,name):
|
||||
matches=re.findall(r'typedef struct '+name+r'\s*\{.*?\}\s*\w+\s*;',source,re.S)
|
||||
assert matches,name
|
||||
return matches[-1].replace('long long','std::int64_t').replace('long','std::int32_t').replace('CItemData::ITEM_NAME_MAX_LEN','24')
|
||||
constants=game[game.index('enum\n{\n\tITEM_SOCKET_SLOT_MAX_NUM'):]
|
||||
constants=constants[:constants.index('\n};')+3]
|
||||
stdafx=(root/'upstream/ava2-client/UserInterface/StdAfx.h').read_text(errors='replace')
|
||||
assert '#define _USE_32BIT_TIME_T' in stdafx
|
||||
assert re.search(r'POINT_MAX_NUM\s*=\s*255',stdafx)
|
||||
equipment=packet[packet.index('enum ECharacterEquipmentPart'):packet.index('typedef struct packet_char_additional_info')]
|
||||
text='#pragma once\n#include <cstdint>\n#include <cstring>\n#include "'+str(root/'upstream/ava2-client/UserInterface/Locale_inc.h')+'"\nnamespace ava2_windows_item {\nusing BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;using time_t=std::int32_t;constexpr int POINT_MAX_NUM=255,CHARACTER_NAME_MAX_LEN=24,SKILL_MAX_NUM=255;\n'+constants+'\n'+equipment+'\n#pragma pack(push,1)\nstruct TItemPos { BYTE window_type; WORD cell; };\n'+decl(game,'TPlayerItemAttribute')+'\n'+packet[packet.index('#ifdef RENEWAL_DEAD_PACKET\nenum EReviveTypes'):packet.index('typedef struct packet_dead')]+'\n'+decl(packet,'packet_dead')+'\n'+decl(packet,'SPlayerSkill')+'\n'+decl(packet,'packet_skill_level')+'\n'+decl(packet,'packet_skill_level_new')+'\n'+decl(packet,'command_item_drop')+'\n'+decl(packet,'command_item_drop2')+'\n'+decl(packet,'packet_add_char2')+'\n'+decl(packet,'packet_update_char2')+'\n'+decl(packet,'packet_add_char')+'\n'+decl(packet,'packet_char_additional_info')+'\n'+decl(packet,'packet_update_char')+'\n'+decl(packet,'packet_set_item')+'\n'+decl(packet,'packet_set_item2')+'\n'+decl(packet,'packet_update_item')+'\n'+decl(packet,'packet_exchange')+'\n'+decl(packet,'packet_points')+'\n'+decl(packet,'packet_point_change')+'\n'+decl(packet,'SPacketGCTime')+'\n'+decl(packet,'command_EnterFrontGame')+'\n'+decl(packet,'packet_main_character4_bgm_vol')+'\n#pragma pack(pop)\n}\n'
|
||||
mob=(root/'upstream/ava2-client/UserInterface/PythonNonPlayer.h').read_text(errors='replace')
|
||||
mob_decls=decl(mob,'SMobSkillLevel')+'\n'+'\n'.join(decl(mob,'SMobTable_r'+str(size)) for size in (235,255,256,262,263))
|
||||
text+='namespace ava2_windows_mob { using BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;constexpr int CHARACTER_NAME_MAX_LEN=24,MOB_ENCHANTS_MAX_NUM=6,MOB_RESISTS_MAX_NUM=11,MOB_SKILL_MAX_NUM=5;\n#pragma pack(push,1)\n'+mob_decls+'\n#pragma pack(pop)\n}\n'
|
||||
affects=[]
|
||||
for name in ('TPacketAffectElement','TPacketGCAffectAdd','TPacketGCAffectRemove'):
|
||||
match=re.search(r'typedef struct\s*\{[^{}]*\}\s*'+name+r'\s*;',packet,re.S)
|
||||
assert match,name
|
||||
affects.append(match.group().replace('long','std::int32_t'))
|
||||
text+='namespace ava2_windows_affect {using BYTE=std::uint8_t;using DWORD=std::uint32_t;\n#pragma pack(push,1)\n'+'\n'.join(affects)+'\n#pragma pack(pop)\n}\n'
|
||||
skill=(root/'upstream/ava2-client/UserInterface/PythonSkill.h').read_text(errors='replace')
|
||||
skill_types=re.search(r'enum\s*\{\s*SKILL_TYPE_NONE,.*?\};',skill,re.S)
|
||||
assert skill_types
|
||||
text+='namespace ava2_windows_skill {\n'+skill_types.group()+'\n'
|
||||
for name in ('SKILL_GRADE_COUNT','SKILL_GRADE_STEP_COUNT','SKILL_GRADEGAP','SKILL_EFFECT_COUNT'):
|
||||
value=re.search(r'\b'+name+r'\s*=\s*(\d+)',skill)
|
||||
assert value,name
|
||||
text+='constexpr int '+name+'='+value.group(1)+';\n'
|
||||
text+='}\n'
|
||||
item=(root/'upstream/ava2-client/GameLib/ItemData.h').read_text(errors='replace')
|
||||
item_decls=decl(item,'SItemLimit')+'\n'+decl(item,'SItemApply')+'\n'+'\n'.join(decl(item,'SItemTable_r'+str(size)) for size in (152,156,158))
|
||||
item_constants=''
|
||||
for name in ('ITEM_NAME_MAX_LEN','ITEM_LIMIT_MAX_NUM','ITEM_APPLY_MAX_NUM','ITEM_VALUES_MAX_NUM','ITEM_SOCKET_MAX_NUM'):
|
||||
value=re.search(r'\b'+name+r'\s*=\s*(\d+)',item)
|
||||
assert value,name
|
||||
item_constants+='constexpr int '+name+'='+value.group(1)+';\n'
|
||||
text+='namespace ava2_windows_proto {using BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;\n'+item_constants+'#pragma pack(push,1)\n'+item_decls+'\n#pragma pack(pop)\n}\n'
|
||||
out=Path(sys.argv[1]);out.parent.mkdir(parents=True,exist_ok=True);out.write_text(text)
|
||||
@@ -0,0 +1,229 @@
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
upstream = root / "upstream/ava2-client"
|
||||
|
||||
modules_spec = [
|
||||
("item", "initItem", "UserInterface/PythonItemModule.cpp"),
|
||||
("player", "initPlayer", "UserInterface/PythonPlayerModule.cpp"),
|
||||
("chrmgr", "initchrmgr", "UserInterface/PythonCharacterManagerModule.cpp"),
|
||||
("chr", "initchr", "UserInterface/PythonCharacterModule.cpp"),
|
||||
("chat", "initChat", "UserInterface/PythonChatModule.cpp"),
|
||||
("snd", "initsnd", "UserInterface/PythonSoundManagerModule.cpp"),
|
||||
("background", "initBackground", "UserInterface/PythonBackgroundModule.cpp"),
|
||||
]
|
||||
|
||||
locale_text = (upstream / "UserInterface/Locale_inc.h").read_text(encoding="latin1")
|
||||
|
||||
def strip_comments(text):
|
||||
text = re.sub(r'//.*', '', text)
|
||||
text = re.sub(r'/\*.*?\*/', '', text, flags=re.DOTALL)
|
||||
return text
|
||||
|
||||
# 1. Clean ItemData.h: stop BEFORE struct SItemTable_r / typedef struct SItemTable
|
||||
itemdata_text = (upstream / "GameLib/ItemData.h").read_text(encoding="latin1")
|
||||
table_pos = itemdata_text.find("TItemTable")
|
||||
pre_typedef = itemdata_text.rfind("typedef", 0, table_pos)
|
||||
itemdata_clean = itemdata_text[:pre_typedef] + "\n};\n"
|
||||
itemdata_clean = "\n".join([l for l in itemdata_clean.splitlines() if not l.strip().startswith("#include")])
|
||||
|
||||
# 2. Clean GameType.h
|
||||
gametype_text = (upstream / "UserInterface/GameType.h").read_text(encoding="latin1")
|
||||
df_pos = gametype_text.find("// DEFAULT_FONT")
|
||||
if df_pos == -1:
|
||||
df_pos = gametype_text.find("DefaultFont")
|
||||
if df_pos != -1:
|
||||
gametype_text = gametype_text[:df_pos]
|
||||
gametype_clean = "\n".join([l for l in gametype_text.splitlines() if not l.strip().startswith("#include")])
|
||||
|
||||
# 3. Clean Packet.h: extract ALL enums after stripping comments
|
||||
packet_text = strip_comments((upstream / "UserInterface/Packet.h").read_text(encoding="latin1"))
|
||||
packet_enums = re.findall(r'enum(\s+\w+)?\s*\{([^}]+)\};', packet_text)
|
||||
seen_enums = set()
|
||||
packet_enums_clean_list = []
|
||||
for name, body in packet_enums:
|
||||
if "MUSIC_NAME_MAX_LEN" in body:
|
||||
if "MUSIC_NAME_MAX_LEN" in seen_enums:
|
||||
continue
|
||||
seen_enums.add("MUSIC_NAME_MAX_LEN")
|
||||
packet_enums_clean_list.append(f"enum {name} {{{body}}};")
|
||||
packet_enums_clean = "\n".join(packet_enums_clean_list)
|
||||
|
||||
# 4. Clean InstanceBase.h (extract ALL enums from InstanceBase.h after stripping comments)
|
||||
ib_text = strip_comments((upstream / "UserInterface/InstanceBase.h").read_text(encoding="latin1"))
|
||||
ib_enums = re.findall(r'enum(\s+\w+)?\s*\{([^}]+)\};', ib_text)
|
||||
ib_enums_clean = "class CInstanceBase {\npublic:\n" + "\n".join(["enum " + e[0] + " {" + e[1] + "};" for e in ib_enums]) + "\n};\n"
|
||||
|
||||
def extract_class_enums(filepath, class_name):
|
||||
txt = strip_comments((upstream / filepath).read_text(encoding="latin1"))
|
||||
enums = re.findall(r'enum(\s+\w+)?\s*\{([^}]+)\};', txt)
|
||||
return f"class {class_name} {{\npublic:\n" + "\n".join(["enum " + e[0] + " {" + e[1] + "};" for e in enums]) + "\n};\n"
|
||||
|
||||
pp_clean = extract_class_enums("UserInterface/PythonPlayer.h", "CPythonPlayer")
|
||||
pi_clean = extract_class_enums("UserInterface/PythonItem.h", "CPythonItem")
|
||||
rmd_clean = extract_class_enums("GameLib/RaceMotionData.h", "CRaceMotionData")
|
||||
rd_clean = extract_class_enums("GameLib/RaceData.h", "CRaceData")
|
||||
ai_clean = extract_class_enums("GameLib/ActorInstance.h", "CActorInstance")
|
||||
chat_clean = extract_class_enums("UserInterface/PythonChat.h", "CPythonChat")
|
||||
bg_clean = extract_class_enums("UserInterface/PythonBackground.h", "CPythonBackground")
|
||||
mo_clean = extract_class_enums("GameLib/MapOutdoor.h", "CMapOutdoor")
|
||||
sky_clean = extract_class_enums("EterLib/SkyBox.h", "CSkyObject")
|
||||
|
||||
pyplayer_cpp = (upstream / "UserInterface/PythonPlayerModule.cpp").read_text(encoding="latin1")
|
||||
skill_consts = re.findall(r'extern const DWORD (c_iSkillIndex_\w+)\s*=\s*(\d+);', pyplayer_cpp)
|
||||
skill_decl = "\n".join([f"const DWORD {name} = {val};" for name, val in skill_consts])
|
||||
|
||||
pyplayer_enums = re.findall(r'enum\s*\{([^}]+)\};', strip_comments(pyplayer_cpp))
|
||||
pyplayer_module_enums = "\n".join(["enum {" + e + "};" for e in pyplayer_enums])
|
||||
|
||||
# Preprocess each module cpp to get exact methods and active constants
|
||||
modules_data = {}
|
||||
all_const_entries = []
|
||||
|
||||
for mod, init_fn, path in modules_spec:
|
||||
raw_code = (upstream / path).read_text(encoding="latin1")
|
||||
methods = re.findall(r'\{\s*"(\w+)"\s*,\s*(\w+)\s*,', raw_code)
|
||||
method_names = [m[0] for m in methods]
|
||||
|
||||
lines = [l for l in raw_code.splitlines() if not l.strip().startswith("#include")]
|
||||
res = subprocess.run([
|
||||
"clang++", "-E",
|
||||
"-include", str(upstream / "UserInterface/Locale_inc.h"),
|
||||
"-x", "c++",
|
||||
"-"
|
||||
], input="\n".join(lines), capture_output=True, text=True)
|
||||
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"Failed to preprocess {path}: {res.stderr}")
|
||||
|
||||
preprocessed_code = res.stdout
|
||||
init_idx = preprocessed_code.find(f"void {init_fn}()")
|
||||
body = preprocessed_code[init_idx:] if init_idx != -1 else ""
|
||||
|
||||
consts = re.findall(r'PyModule_AddIntConstant\s*\(\s*\w+,\s*\"(\w+)\"\s*,\s*([^)]+)\)', body)
|
||||
|
||||
modules_data[mod] = {
|
||||
"init_fn": init_fn,
|
||||
"methods": method_names,
|
||||
"consts": consts,
|
||||
}
|
||||
for cname, cval in consts:
|
||||
all_const_entries.append((mod, cname, cval.strip()))
|
||||
|
||||
print(f"Total active constants to evaluate: {len(all_const_entries)}")
|
||||
|
||||
eval_lines = []
|
||||
for i, (mod, cname, cval) in enumerate(all_const_entries):
|
||||
eval_lines.append(f' std::cout << "{mod}:{cname}:" << ({cval}) << std::endl;')
|
||||
|
||||
generator_source = f"""
|
||||
#include <iostream>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
|
||||
typedef uint32_t DWORD;
|
||||
typedef uint16_t WORD;
|
||||
typedef uint8_t BYTE;
|
||||
typedef int BOOL;
|
||||
typedef long LONG;
|
||||
typedef float FLOAT;
|
||||
typedef unsigned int UINT;
|
||||
#define CHARACTER_NAME_MAX_LEN 24
|
||||
#define PLAYER_NAME_MAX_LEN 12
|
||||
#define POINT_MAX_NUM 255
|
||||
#define SKILL_MAX_NUM 255
|
||||
|
||||
{locale_text}
|
||||
{itemdata_clean}
|
||||
{gametype_clean}
|
||||
{packet_enums_clean}
|
||||
{ib_enums_clean}
|
||||
{pp_clean}
|
||||
{pi_clean}
|
||||
{rmd_clean}
|
||||
{rd_clean}
|
||||
{ai_clean}
|
||||
{chat_clean}
|
||||
{bg_clean}
|
||||
{mo_clean}
|
||||
{sky_clean}
|
||||
{skill_decl}
|
||||
{pyplayer_module_enums}
|
||||
|
||||
int main() {{
|
||||
{chr(10).join(eval_lines)}
|
||||
return 0;
|
||||
}}
|
||||
"""
|
||||
|
||||
Path("/tmp/run_all_evals.cpp").write_text(generator_source)
|
||||
res = subprocess.run(["clang++", "-std=c++17", "-Wno-everything", "/tmp/run_all_evals.cpp", "-o", "/tmp/run_all_evals"], capture_output=True, text=True)
|
||||
if res.returncode != 0:
|
||||
print("Compile error in run_all_evals:\n", res.stderr[:3000])
|
||||
exit(1)
|
||||
|
||||
print("Evaluator binary compiled! Running...")
|
||||
eval_out = subprocess.check_output(["/tmp/run_all_evals"]).decode().splitlines()
|
||||
print(f"Evaluated {len(eval_out)} constants!")
|
||||
|
||||
evaluated_dict = {}
|
||||
for line in eval_out:
|
||||
parts = line.split(":", 2)
|
||||
if len(parts) == 3:
|
||||
evaluated_dict[(parts[0], parts[1])] = parts[2]
|
||||
|
||||
# Now generate python_gameplay_modules.h and python_gameplay_modules.cpp
|
||||
h_out = ["#pragma once\n\nnamespace ava2 {\n"]
|
||||
cpp_out = [
|
||||
'#include "python_gameplay_modules.h"\n',
|
||||
'#include <Python.h>\n',
|
||||
'#include <string>\n',
|
||||
'#include <vector>\n\n',
|
||||
'namespace ava2 {\n',
|
||||
'namespace {\n',
|
||||
'PyObject* dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; }\n',
|
||||
'PyObject* dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); }\n',
|
||||
'PyObject* dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); }\n',
|
||||
'PyObject* dummy_str(PyObject*, PyObject*) { return PyString_FromString(""); }\n',
|
||||
'PyObject* dummy_tuple2(PyObject*, PyObject*) { return Py_BuildValue("ii", 0, 0); }\n',
|
||||
'PyObject* dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 0, 0, 0); }\n',
|
||||
'PyObject* dummy_tuple4(PyObject*, PyObject*) { return Py_BuildValue("iiii", 0, 0, 0, 0); }\n',
|
||||
'} // namespace\n\n',
|
||||
]
|
||||
|
||||
for mod, data in modules_data.items():
|
||||
init_fn = data["init_fn"]
|
||||
h_out.append(f"void {init_fn}();\n")
|
||||
|
||||
cpp_out.append(f"void {init_fn}() {{\n")
|
||||
cpp_out.append(f" static PyMethodDef methods[] = {{\n")
|
||||
for m in data["methods"]:
|
||||
if m.startswith("Is") or m.startswith("Get"):
|
||||
if any(k in m for k in ["Name", "String", "Text", "Title", "Path"]):
|
||||
cpp_out.append(f' {{"{m}", dummy_str, METH_VARARGS, nullptr}},\n')
|
||||
elif any(k in m for k in ["Position", "PixelPosition", "Coord"]):
|
||||
cpp_out.append(f' {{"{m}", dummy_tuple3, METH_VARARGS, nullptr}},\n')
|
||||
else:
|
||||
cpp_out.append(f' {{"{m}", dummy_zero, METH_VARARGS, nullptr}},\n')
|
||||
else:
|
||||
cpp_out.append(f' {{"{m}", dummy_none, METH_VARARGS, nullptr}},\n')
|
||||
cpp_out.append(f" {{nullptr, nullptr, 0, nullptr}}\n }};\n")
|
||||
cpp_out.append(f' auto* module = Py_InitModule("{mod}", methods);\n\n')
|
||||
|
||||
for cname, _ in data["consts"]:
|
||||
int_val = evaluated_dict.get((mod, cname), "0")
|
||||
cpp_out.append(f' PyModule_AddIntConstant(module, "{cname}", {int_val});\n')
|
||||
|
||||
cpp_out.append("}\n\n")
|
||||
|
||||
h_out.append("} // namespace ava2\n")
|
||||
cpp_out.append("} // namespace ava2\n")
|
||||
|
||||
(root / "src/python_gameplay_modules.h").write_text("".join(h_out))
|
||||
(root / "src/python_gameplay_modules.cpp").write_text("".join(cpp_out))
|
||||
print("Successfully generated src/python_gameplay_modules.h and src/python_gameplay_modules.cpp!")
|
||||
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
net_cpp_src = root / "upstream/ava2-client/UserInterface/PythonNetworkStreamModule.cpp"
|
||||
|
||||
with open(net_cpp_src, "r", encoding="latin1") as f:
|
||||
text = f.read()
|
||||
|
||||
methods = re.findall(r'\{\s*"(\w+)"\s*,\s*(\w+)\s*,', text)
|
||||
upstream_method_names = [m[0] for m in methods]
|
||||
|
||||
# Read original base python_net.cpp
|
||||
# We can construct the complete python_net.cpp directly and cleanly!
|
||||
code = '''#include "python_net.h"
|
||||
#include "login_client.h"
|
||||
#include <Python.h>
|
||||
#include <array>
|
||||
#include <stdexcept>
|
||||
#include <algorithm>
|
||||
|
||||
namespace ava2 {
|
||||
namespace {
|
||||
|
||||
LoginClient client;
|
||||
PyObject* handler=nullptr;
|
||||
PyObject* account_handler=nullptr;
|
||||
std::array<PyObject*,7> phases{};
|
||||
std::string account,password;
|
||||
|
||||
void replace(PyObject*& old,PyObject* next) {
|
||||
if(next==Py_None || (next && PyInt_Check(next) && PyInt_AsLong(next)==0)) next=nullptr;
|
||||
Py_XINCREF(next);
|
||||
auto* previous=old;
|
||||
old=next;
|
||||
Py_XDECREF(previous);
|
||||
}
|
||||
|
||||
void callback(PyObject* target,const char* name,const char* text=nullptr) {
|
||||
if(!target) return;
|
||||
Py_INCREF(target);
|
||||
auto* method=PyObject_GetAttrString(target,name);
|
||||
if(!method) {
|
||||
Py_DECREF(target);
|
||||
throw std::runtime_error(std::string("missing Python callback: ")+name);
|
||||
}
|
||||
auto* result=text?PyObject_CallFunction(method,const_cast<char*>("s"),text):PyObject_CallObject(method,nullptr);
|
||||
Py_DECREF(method);
|
||||
Py_DECREF(target);
|
||||
if(!result) throw std::runtime_error(std::string("Python callback failed: ")+name);
|
||||
Py_DECREF(result);
|
||||
}
|
||||
|
||||
PyObject* set_handler(PyObject*,PyObject* args) { PyObject* value;if(!PyArg_ParseTuple(args,"O",&value)) return nullptr;replace(handler,value);Py_RETURN_NONE; }
|
||||
PyObject* set_account_handler(PyObject*,PyObject* args) { PyObject* value;if(!PyArg_ParseTuple(args,"O",&value)) return nullptr;replace(account_handler,value);Py_RETURN_NONE; }
|
||||
PyObject* set_phase(PyObject*,PyObject* args) { int phase;PyObject* value;if(!PyArg_ParseTuple(args,"iO",&phase,&value)) return nullptr;if(phase<0 || phase>=7) { PyErr_SetString(PyExc_ValueError,"invalid phase window");return nullptr; }replace(phases[phase],value);Py_RETURN_NONE; }
|
||||
PyObject* clear_phase(PyObject*,PyObject* args) { int phase;PyObject* value;if(!PyArg_ParseTuple(args,"iO",&phase,&value)) return nullptr;if(phase<0 || phase>=7) { PyErr_SetString(PyExc_ValueError,"invalid phase window");return nullptr; }if(phases[phase]==value) replace(phases[phase],nullptr);Py_RETURN_NONE; }
|
||||
PyObject* set_login(PyObject*,PyObject* args) { const char* id;const char* pass;if(!PyArg_ParseTuple(args,"ss",&id,&pass)) return nullptr;account=id;password=pass;Py_RETURN_NONE; }
|
||||
PyObject* connect(PyObject*,PyObject* args) {
|
||||
const char* game;const char* auth;int game_port,auth_port;
|
||||
if(!PyArg_ParseTuple(args,"sisi",&game,&game_port,&auth,&auth_port)) return nullptr;
|
||||
try { client.connect({auth,auth_port},{game,game_port},account,password);std::fill(password.begin(),password.end(),0);password.clear();Py_RETURN_NONE; }
|
||||
catch(const std::exception& e) { PyErr_SetString(PyExc_ValueError,e.what());return nullptr; }
|
||||
}
|
||||
PyObject* disconnect(PyObject*,PyObject*) { client.cancel();std::fill(password.begin(),password.end(),0);password.clear();Py_RETURN_NONE; }
|
||||
PyObject* sequence_mode(PyObject*,PyObject*) { Py_RETURN_NONE; }
|
||||
PyObject* select(PyObject*,PyObject* args) { int slot;if(!PyArg_ParseTuple(args,"i",&slot)) return nullptr;try { if(slot<0 || slot>=5) throw std::invalid_argument("invalid character slot");client.select(slot);Py_RETURN_NONE; } catch(const std::exception& e) { PyErr_SetString(PyExc_ValueError,e.what());return nullptr; } }
|
||||
const Character* character(int index) { auto* session=client.session();if(index<0 || index>=5) { PyErr_SetString(PyExc_ValueError,"invalid character slot");return nullptr; }if(!session || session->characters().size()!=5) return nullptr;return &session->characters()[index]; }
|
||||
|
||||
PyObject* get_integer(PyObject*,PyObject* args) {
|
||||
int index,type;if(!PyArg_ParseTuple(args,"ii",&index,&type)) return nullptr;auto* c=character(index);if(PyErr_Occurred()) return nullptr;
|
||||
if(type<0 || type>21 || type==1 || type==13) { PyErr_SetString(PyExc_ValueError,"invalid integer character field");return nullptr; }
|
||||
if(!c) return PyLong_FromLong(0);
|
||||
std::uint32_t value=0;
|
||||
switch(type) {
|
||||
case 0:value=c->id;break;case 2:value=c->job;break;case 3:value=c->level;break;case 4:value=c->strength;break;
|
||||
case 5:value=c->dexterity;break;case 6:value=c->health;break;case 7:value=c->intelligence;break;case 8:value=c->play_minutes;break;
|
||||
case 9:value=c->main_part;break;case 10:value=c->address;break;case 11:value=c->port;break;case 12:value=c->guild_id;break;
|
||||
case 14:value=c->change_name;break;case 15:value=c->hair_part;break;case 16:value=c->sash_part;break;case 17:value=c->conqueror_level;break;
|
||||
default:value=c->sungma[type-18];break;
|
||||
}
|
||||
return PyLong_FromUnsignedLong(value);
|
||||
}
|
||||
|
||||
PyObject* get_string(PyObject*,PyObject* args) { int index,type;if(!PyArg_ParseTuple(args,"ii",&index,&type)) return nullptr;auto* c=character(index);if(PyErr_Occurred()) return nullptr;if(type!=1 && type!=13) { PyErr_SetString(PyExc_ValueError,"invalid string character field");return nullptr; }return PyString_FromString(c?(type==1?c->name.c_str():c->guild_name.c_str()):""); }
|
||||
PyObject* empire(PyObject*,PyObject*) { return PyInt_FromLong(client.session()?client.session()->empire():0); }
|
||||
PyObject* update(PyObject*,PyObject*) { try { pump_python_net();Py_RETURN_NONE; } catch(const std::exception& e) { if(!PyErr_Occurred()) PyErr_SetString(PyExc_RuntimeError,e.what());return nullptr; } }
|
||||
PyObject* status(PyObject*,PyObject*) { const char* names[]={"idle","resolving","connecting","authenticating","selecting","entering","loading","failed"};return PyString_FromString(names[static_cast<int>(client.status())]); }
|
||||
|
||||
PyObject* net_dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; }
|
||||
PyObject* net_dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); }
|
||||
PyObject* net_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); }
|
||||
PyObject* net_dummy_str(PyObject*, PyObject*) { return PyString_FromString(""); }
|
||||
|
||||
} // namespace
|
||||
|
||||
void initnet() {
|
||||
static PyMethodDef methods[] = {
|
||||
{"SetHandler", set_handler, METH_VARARGS, nullptr},
|
||||
{"SetAccountConnectorHandler", set_account_handler, METH_VARARGS, nullptr},
|
||||
{"SetPhaseWindow", set_phase, METH_VARARGS, nullptr},
|
||||
{"ClearPhaseWindow", clear_phase, METH_VARARGS, nullptr},
|
||||
{"SetLoginInfo", set_login, METH_VARARGS, nullptr},
|
||||
{"ConnectToAccountServer", connect, METH_VARARGS, nullptr},
|
||||
{"Disconnect", disconnect, METH_NOARGS, nullptr},
|
||||
{"SetPacketSequenceMode", sequence_mode, METH_NOARGS, nullptr},
|
||||
{"SendSelectCharacterPacket", select, METH_VARARGS, nullptr},
|
||||
{"GetAccountCharacterSlotDataInteger", get_integer, METH_VARARGS, nullptr},
|
||||
{"GetAccountCharacterSlotDataString", get_string, METH_VARARGS, nullptr},
|
||||
{"GetEmpireID", empire, METH_NOARGS, nullptr},
|
||||
{"Update", update, METH_NOARGS, nullptr},
|
||||
{"GetConnectionState", status, METH_NOARGS, nullptr},
|
||||
'''
|
||||
|
||||
implemented = {
|
||||
"SetHandler", "SetAccountConnectorHandler", "SetPhaseWindow", "ClearPhaseWindow",
|
||||
"SetLoginInfo", "ConnectToAccountServer", "Disconnect", "SetPacketSequenceMode",
|
||||
"SendSelectCharacterPacket", "GetAccountCharacterSlotDataInteger", "GetAccountCharacterSlotDataString",
|
||||
"GetEmpireID", "Update", "GetConnectionState"
|
||||
}
|
||||
|
||||
method_entries = []
|
||||
for name in upstream_method_names:
|
||||
if name in implemented:
|
||||
continue
|
||||
if name.startswith("Is") or name.startswith("Get"):
|
||||
if any(k in name for k in ["Name", "Command", "Info", "File"]):
|
||||
method_entries.append(f' {{"{name}", net_dummy_str, METH_VARARGS, nullptr}},')
|
||||
else:
|
||||
method_entries.append(f' {{"{name}", net_dummy_zero, METH_VARARGS, nullptr}},')
|
||||
else:
|
||||
method_entries.append(f' {{"{name}", net_dummy_none, METH_VARARGS, nullptr}},')
|
||||
|
||||
code += "\n".join(method_entries) + "\n"
|
||||
code += ''' {nullptr, nullptr, 0, nullptr}
|
||||
};
|
||||
auto* module = Py_InitModule("net", methods);
|
||||
|
||||
constexpr const char* field_names[] = {"ID","NAME","RACE","LEVEL","STR","DEX","HTH","INT","PLAYTIME","FORM","ADDR","PORT","GUILD_ID","GUILD_NAME","CHANGE_NAME_FLAG","HAIR","SASH","CONQUEROR_LEVEL","SUNGMA_ST","SUNGMA_HP","SUNGMA_MOVE","SUNGMA_INMUNE"};
|
||||
for(int i=0; i<22; ++i) PyModule_AddIntConstant(module, (std::string("ACCOUNT_CHARACTER_SLOT_")+field_names[i]).c_str(), i);
|
||||
|
||||
constexpr const char* phase_names[] = {"LOGO","LOGIN","SELECT","CREATE","LOAD","GAME","EMPIRE"};
|
||||
for(int i=0; i<7; ++i) PyModule_AddIntConstant(module, (std::string("PHASE_WINDOW_")+phase_names[i]).c_str(), i);
|
||||
|
||||
PyModule_AddIntConstant(module, "EMPIRE_A", 1);
|
||||
PyModule_AddIntConstant(module, "EMPIRE_B", 2);
|
||||
PyModule_AddIntConstant(module, "EMPIRE_C", 3);
|
||||
|
||||
// CPythonNetworkStream error codes
|
||||
PyModule_AddIntConstant(module, "ERROR_NONE", 0);
|
||||
PyModule_AddIntConstant(module, "ERROR_UNKNOWN", 1);
|
||||
PyModule_AddIntConstant(module, "ERROR_CONNECT_MARK_SERVER", 2);
|
||||
PyModule_AddIntConstant(module, "ERROR_LOAD_MARK", 3);
|
||||
PyModule_AddIntConstant(module, "ERROR_MARK_WIDTH", 4);
|
||||
PyModule_AddIntConstant(module, "ERROR_MARK_HEIGHT", 5);
|
||||
PyModule_AddIntConstant(module, "ERROR_MARK_UPLOAD_NEED_RECONNECT", 6);
|
||||
PyModule_AddIntConstant(module, "ERROR_MARK_CHECK_NEED_RECONNECT", 7);
|
||||
|
||||
// Server commands
|
||||
PyModule_AddIntConstant(module, "SERVER_COMMAND_LOG_OUT", 0);
|
||||
PyModule_AddIntConstant(module, "SERVER_COMMAND_RETURN_TO_SELECT_CHARACTER", 1);
|
||||
PyModule_AddIntConstant(module, "SERVER_COMMAND_QUIT", 2);
|
||||
|
||||
// Dragon Soul Subheaders
|
||||
PyModule_AddIntConstant(module, "DS_SUB_HEADER_REFINE_FAIL", 5);
|
||||
PyModule_AddIntConstant(module, "DS_SUB_HEADER_REFINE_FAIL_MAX_REFINE", 6);
|
||||
PyModule_AddIntConstant(module, "DS_SUB_HEADER_REFINE_FAIL_INVALID_MATERIAL", 7);
|
||||
PyModule_AddIntConstant(module, "DS_SUB_HEADER_REFINE_FAIL_NOT_ENOUGH_MONEY", 8);
|
||||
PyModule_AddIntConstant(module, "DS_SUB_HEADER_REFINE_FAIL_NOT_ENOUGH_MATERIAL", 9);
|
||||
PyModule_AddIntConstant(module, "DS_SUB_HEADER_REFINE_FAIL_TOO_MUCH_MATERIAL", 10);
|
||||
PyModule_AddIntConstant(module, "DS_SUB_HEADER_REFINE_SUCCEED", 11);
|
||||
}
|
||||
|
||||
void register_python_net() {
|
||||
if(PyImport_AppendInittab("net", initnet) != 0) throw std::runtime_error("net module registration failed");
|
||||
}
|
||||
|
||||
void reset_python_net() {
|
||||
client.cancel();
|
||||
replace(handler, nullptr);
|
||||
replace(account_handler, nullptr);
|
||||
for(auto*& phase : phases) replace(phase, nullptr);
|
||||
account.clear();
|
||||
std::fill(password.begin(), password.end(), 0);
|
||||
password.clear();
|
||||
}
|
||||
|
||||
void pump_python_net() {
|
||||
client.pump();
|
||||
auto events = client.take_events();
|
||||
for(const auto& event : events) {
|
||||
if(event.generation != client.generation()) continue;
|
||||
if(event.type == LoginClient::EventType::LoginStart) callback(phases[1], "OnLoginStart");
|
||||
else if(event.type == LoginClient::EventType::SelectReady) {
|
||||
callback(handler, client.session()->empire() ? "SetSelectCharacterPhase" : "SetSelectEmpirePhase");
|
||||
if(event.generation == client.generation()) callback(phases[2], "Refresh");
|
||||
} else if(event.type == LoginClient::EventType::Loading) callback(handler, "SetLoadingPhase");
|
||||
else {
|
||||
auto* target = account_handler ? account_handler : phases[1];
|
||||
callback(target, event.connection_failure ? "OnConnectFailure" : "OnLoginFailure", event.connection_failure ? nullptr : event.reason.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ava2
|
||||
'''
|
||||
|
||||
with open(root / "src/python_net.cpp", "w") as f:
|
||||
f.write(code)
|
||||
|
||||
print("Generated clean 1:1 expanded python_net.cpp successfully!")
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
upstream_root = root / "upstream/ava2-client"
|
||||
|
||||
modules_spec = [
|
||||
("item", "initItem", "UserInterface/PythonItemModule.cpp"),
|
||||
("player", "initPlayer", "UserInterface/PythonPlayerModule.cpp"),
|
||||
("chrmgr", "initchrmgr", "UserInterface/PythonCharacterManagerModule.cpp"),
|
||||
("chr", "initchr", "UserInterface/PythonCharacterModule.cpp"),
|
||||
("chat", "initChat", "UserInterface/PythonChatModule.cpp"),
|
||||
("snd", "initsnd", "UserInterface/PythonSoundManagerModule.cpp"),
|
||||
("background", "initBackground", "UserInterface/PythonBackgroundModule.cpp"),
|
||||
]
|
||||
|
||||
h_output = ["#pragma once\n", "namespace ava2 {\n"]
|
||||
cpp_output = [
|
||||
'#include "python_gameplay_modules.h"\n',
|
||||
'#include "../upstream/ava2-client/UserInterface/Locale_inc.h"\n',
|
||||
'#include "../upstream/ava2-client/GameLib/ItemData.h"\n',
|
||||
'#include <Python.h>\n',
|
||||
'#include <string>\n',
|
||||
'#include <vector>\n\n',
|
||||
'namespace ava2 {\n',
|
||||
'namespace {\n',
|
||||
'PyObject* dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; }\n',
|
||||
'PyObject* dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); }\n',
|
||||
'PyObject* dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); }\n',
|
||||
'PyObject* dummy_str(PyObject*, PyObject*) { return PyString_FromString(""); }\n',
|
||||
'PyObject* dummy_tuple2(PyObject*, PyObject*) { return Py_BuildValue("ii", 0, 0); }\n',
|
||||
'PyObject* dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 0, 0, 0); }\n',
|
||||
'PyObject* dummy_tuple4(PyObject*, PyObject*) { return Py_BuildValue("iiii", 0, 0, 0, 0); }\n',
|
||||
'} // namespace\n\n'
|
||||
]
|
||||
|
||||
for mod_name, init_fn, rel_path in modules_spec:
|
||||
h_output.append(f"void {init_fn}();\n")
|
||||
|
||||
src_file = upstream_root / rel_path
|
||||
with open(src_file, "r", encoding="latin1") as f:
|
||||
content = f.read()
|
||||
|
||||
methods = re.findall(r'\{\s*"(\w+)"\s*,\s*(\w+)\s*,', content)
|
||||
method_names = [m[0] for m in methods]
|
||||
|
||||
init_idx = content.find(f"void {init_fn}()")
|
||||
body = content[init_idx:] if init_idx != -1 else ""
|
||||
|
||||
consts = re.findall(r'PyModule_AddIntConstant\s*\(\s*\w+,\s*\"(\w+)\"\s*,\s*([^)]+)\)', body)
|
||||
|
||||
cpp_output.append(f"void {init_fn}() {{\n")
|
||||
cpp_output.append(f" static PyMethodDef methods[] = {{\n")
|
||||
|
||||
for m in method_names:
|
||||
if m.startswith("Is") or m.startswith("Get"):
|
||||
if any(k in m for k in ["Name", "String", "Text", "Title", "Path"]):
|
||||
cpp_output.append(f' {{"{m}", dummy_str, METH_VARARGS, nullptr}},\n')
|
||||
elif any(k in m for k in ["Position", "PixelPosition", "Coord"]):
|
||||
cpp_output.append(f' {{"{m}", dummy_tuple3, METH_VARARGS, nullptr}},\n')
|
||||
else:
|
||||
cpp_output.append(f' {{"{m}", dummy_zero, METH_VARARGS, nullptr}},\n')
|
||||
else:
|
||||
cpp_output.append(f' {{"{m}", dummy_none, METH_VARARGS, nullptr}},\n')
|
||||
|
||||
cpp_output.append(f" {{nullptr, nullptr, 0, nullptr}}\n }};\n")
|
||||
cpp_output.append(f' auto* module = Py_InitModule("{mod_name}", methods);\n\n')
|
||||
|
||||
for cname, cval in consts:
|
||||
val_str = cval.strip()
|
||||
# Keep CItemData:: constants directly since we included ItemData.h!
|
||||
# If it's a known CItemData enum:
|
||||
if "CItemData::" in val_str:
|
||||
final_val = val_str
|
||||
elif val_str.lstrip("-").isdigit() or val_str.startswith("0x"):
|
||||
final_val = val_str
|
||||
else:
|
||||
# Check if it has a prefix or can be passed directly or default
|
||||
final_val = val_str
|
||||
cpp_output.append(f' PyModule_AddIntConstant(module, "{cname}", {final_val});\n')
|
||||
|
||||
cpp_output.append("}\n\n")
|
||||
|
||||
h_output.append("} // namespace ava2\n")
|
||||
cpp_output.append("} // namespace ava2\n")
|
||||
|
||||
(root / "src/python_gameplay_modules.h").write_text("".join(h_output))
|
||||
(root / "src/python_gameplay_modules.cpp").write_text("".join(cpp_output))
|
||||
print("Regenerated python_gameplay_modules.cpp with CItemData enums included directly!")
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile original AVA2 declarations using explicit Win32-width types as an oracle."""
|
||||
from pathlib import Path
|
||||
import re,sys
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
client=(root/'upstream/ava2-client/UserInterface/Packet.h').read_text(errors='replace')
|
||||
server=(root/'upstream/ava2-server/common/tables.h').read_text(errors='replace')
|
||||
packet=(root/'upstream/ava2-server/game/src/packet.h').read_text(errors='replace')
|
||||
tea=(root/'upstream/ava2-client/EterBase/tea.cpp').read_text(errors='replace')
|
||||
|
||||
def declaration(source, start, end):
|
||||
text=source[source.index(start):]
|
||||
text=text[:text.index(end)+len(end)]
|
||||
return re.sub(r'\blong\b','std::int32_t',text)
|
||||
|
||||
# Both baseline macro headers enable sash, conqueror and five-character accounts.
|
||||
for path,names in [
|
||||
('upstream/ava2-client/UserInterface/Locale_inc.h',['ENABLE_SASH_SYSTEM','ENABLE_CONQUEROR_LEVEL','ENABLE_PLAYER_PER_ACCOUNT5']),
|
||||
('upstream/ava2-server/common/CommonDefines.h',['__SASH_SYSTEM__','ENABLE_CONQUEROR_LEVEL','ENABLE_PLAYER_PER_ACCOUNT5'])]:
|
||||
text=(root/path).read_text(errors='replace')
|
||||
for name in names:
|
||||
assert re.search(r'^\s*#\s*define\s+'+name+r'\b',text,re.M), name+' not active in baseline'
|
||||
|
||||
header='''#pragma once
|
||||
#include <cstdint>
|
||||
namespace ava2_oracle {
|
||||
using BYTE=std::uint8_t; using WORD=std::uint16_t; using DWORD=std::uint32_t; using LONG=std::int32_t;
|
||||
constexpr int CHARACTER_NAME_MAX_LEN=24, GUILD_NAME_MAX_LEN=12, PLAYER_PER_ACCOUNT4=5, PLAYER_PER_ACCOUNT=5;
|
||||
#define ENABLE_SASH_SYSTEM
|
||||
#define __SASH_SYSTEM__
|
||||
#define ENABLE_CONQUEROR_LEVEL
|
||||
#pragma pack(push,1)
|
||||
namespace client {
|
||||
'''+declaration(client,'typedef struct SSimplePlayerInformation','} TSimplePlayerInformation;')+'\n'+declaration(client,'typedef struct packet_login_success4','} TPacketGCLoginSuccess4;')+'\n}\nnamespace server {\n'+declaration(server,'typedef struct SSimplePlayer','} TSimplePlayer;')+'\n'+declaration(packet,'typedef struct packet_login_success','} TPacketGCLoginSuccess;')+'''\n}
|
||||
#pragma pack(pop)
|
||||
namespace original_cipher {
|
||||
'''
|
||||
start=tea.index('#define TEA_ROUND')
|
||||
end=tea.index('int tea_encrypt(' , start)
|
||||
text=tea[start:end].replace('unsigned long','std::uint32_t').replace('register ','')
|
||||
header+=text+'\n}\n#undef ENABLE_SASH_SYSTEM\n#undef __SASH_SYSTEM__\n#undef ENABLE_CONQUEROR_LEVEL\n}\n'
|
||||
out=Path(sys.argv[1]);out.parent.mkdir(parents=True,exist_ok=True);out.write_text(header)
|
||||
@@ -0,0 +1,231 @@
|
||||
#!/usr/bin/env python3
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
wnd_cpp = root / "upstream/ava2-client/EterPythonLib/PythonWindowManagerModule.cpp"
|
||||
|
||||
with open(wnd_cpp, "r", encoding="latin1") as f:
|
||||
text = f.read()
|
||||
|
||||
methods = re.findall(r'\{\s*"(\w+)"\s*,\s*(\w+)\s*,', text)
|
||||
method_names = [m[0] for m in methods]
|
||||
|
||||
h_code = """#pragma once
|
||||
|
||||
namespace ava2 {
|
||||
void initwndMgr();
|
||||
}
|
||||
"""
|
||||
(root / "src/python_wndmgr.h").write_text(h_code)
|
||||
|
||||
cpp_code = """#include "python_wndmgr.h"
|
||||
#include <Python.h>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace ava2 {
|
||||
namespace {
|
||||
|
||||
int s_screen_width = 1280;
|
||||
int s_screen_height = 720;
|
||||
long s_next_handle = 1;
|
||||
PyObject* s_mouse_handler = nullptr;
|
||||
|
||||
struct WindowRecord {
|
||||
long handle = 0;
|
||||
PyObject* py_obj = nullptr;
|
||||
std::string name;
|
||||
int x = 0, y = 0, width = 0, height = 0;
|
||||
bool is_show = false;
|
||||
};
|
||||
|
||||
std::unordered_map<long, WindowRecord> s_windows;
|
||||
|
||||
PyObject* wnd_set_screen_size(PyObject*, PyObject* args) {
|
||||
if (!PyArg_ParseTuple(args, "ii", &s_screen_width, &s_screen_height)) return nullptr;
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
PyObject* wnd_get_screen_width(PyObject*, PyObject*) { return PyInt_FromLong(s_screen_width); }
|
||||
PyObject* wnd_get_screen_height(PyObject*, PyObject*) { return PyInt_FromLong(s_screen_height); }
|
||||
|
||||
PyObject* wnd_set_mouse_handler(PyObject*, PyObject* args) {
|
||||
PyObject* h = nullptr;
|
||||
if (!PyArg_ParseTuple(args, "O", &h)) return nullptr;
|
||||
Py_XDECREF(s_mouse_handler);
|
||||
s_mouse_handler = h;
|
||||
Py_XINCREF(s_mouse_handler);
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
PyObject* wnd_register(PyObject*, PyObject* args) {
|
||||
PyObject* po = nullptr;
|
||||
char* layer = nullptr;
|
||||
if (!PyArg_ParseTuple(args, "O|s", &po, &layer)) return nullptr;
|
||||
long handle = s_next_handle++;
|
||||
WindowRecord rec;
|
||||
rec.handle = handle;
|
||||
rec.py_obj = po;
|
||||
Py_XINCREF(po);
|
||||
s_windows[handle] = rec;
|
||||
return PyInt_FromLong(handle);
|
||||
}
|
||||
|
||||
PyObject* wnd_destroy(PyObject*, PyObject* args) {
|
||||
long handle = 0;
|
||||
if (PyArg_ParseTuple(args, "l", &handle)) {
|
||||
auto it = s_windows.find(handle);
|
||||
if (it != s_windows.end()) {
|
||||
Py_XDECREF(it->second.py_obj);
|
||||
s_windows.erase(it);
|
||||
}
|
||||
}
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
PyObject* wnd_set_size(PyObject*, PyObject* args) {
|
||||
long handle = 0; int w = 0, h = 0;
|
||||
if (PyArg_ParseTuple(args, "lii", &handle, &w, &h)) {
|
||||
if (s_windows.count(handle)) {
|
||||
s_windows[handle].width = w;
|
||||
s_windows[handle].height = h;
|
||||
}
|
||||
}
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
PyObject* wnd_set_position(PyObject*, PyObject* args) {
|
||||
long handle = 0; int x = 0, y = 0;
|
||||
if (PyArg_ParseTuple(args, "lii", &handle, &x, &y)) {
|
||||
if (s_windows.count(handle)) {
|
||||
s_windows[handle].x = x;
|
||||
s_windows[handle].y = y;
|
||||
}
|
||||
}
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
PyObject* wnd_get_position(PyObject*, PyObject* args) {
|
||||
long handle = 0;
|
||||
if (PyArg_ParseTuple(args, "l", &handle)) {
|
||||
if (s_windows.count(handle)) {
|
||||
return Py_BuildValue("ii", s_windows[handle].x, s_windows[handle].y);
|
||||
}
|
||||
}
|
||||
return Py_BuildValue("ii", 0, 0);
|
||||
}
|
||||
|
||||
PyObject* wnd_get_width(PyObject*, PyObject* args) {
|
||||
long handle = 0;
|
||||
if (PyArg_ParseTuple(args, "l", &handle) && s_windows.count(handle)) {
|
||||
return PyInt_FromLong(s_windows[handle].width);
|
||||
}
|
||||
return PyInt_FromLong(0);
|
||||
}
|
||||
|
||||
PyObject* wnd_get_height(PyObject*, PyObject* args) {
|
||||
long handle = 0;
|
||||
if (PyArg_ParseTuple(args, "l", &handle) && s_windows.count(handle)) {
|
||||
return PyInt_FromLong(s_windows[handle].height);
|
||||
}
|
||||
return PyInt_FromLong(0);
|
||||
}
|
||||
|
||||
PyObject* wnd_show(PyObject*, PyObject* args) {
|
||||
long handle = 0;
|
||||
if (PyArg_ParseTuple(args, "l", &handle) && s_windows.count(handle)) {
|
||||
s_windows[handle].is_show = true;
|
||||
}
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
PyObject* wnd_hide(PyObject*, PyObject* args) {
|
||||
long handle = 0;
|
||||
if (PyArg_ParseTuple(args, "l", &handle) && s_windows.count(handle)) {
|
||||
s_windows[handle].is_show = false;
|
||||
}
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
PyObject* wnd_is_show(PyObject*, PyObject* args) {
|
||||
long handle = 0;
|
||||
if (PyArg_ParseTuple(args, "l", &handle) && s_windows.count(handle)) {
|
||||
return PyInt_FromLong(s_windows[handle].is_show ? 1 : 0);
|
||||
}
|
||||
return PyInt_FromLong(0);
|
||||
}
|
||||
|
||||
PyObject* wnd_dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; }
|
||||
PyObject* wnd_dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); }
|
||||
PyObject* wnd_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); }
|
||||
PyObject* wnd_dummy_register(PyObject* self, PyObject* args) { return wnd_register(self, args); }
|
||||
|
||||
} // namespace
|
||||
|
||||
void initwndMgr() {
|
||||
static PyMethodDef methods[] = {
|
||||
{"SetScreenSize", wnd_set_screen_size, METH_VARARGS, nullptr},
|
||||
{"GetScreenWidth", wnd_get_screen_width, METH_VARARGS, nullptr},
|
||||
{"GetScreenHeight", wnd_get_screen_height, METH_VARARGS, nullptr},
|
||||
{"SetMouseHandler", wnd_set_mouse_handler, METH_VARARGS, nullptr},
|
||||
{"Register", wnd_register, METH_VARARGS, nullptr},
|
||||
{"Destroy", wnd_destroy, METH_VARARGS, nullptr},
|
||||
{"SetWindowSize", wnd_set_size, METH_VARARGS, nullptr},
|
||||
{"SetWindowPosition", wnd_set_position, METH_VARARGS, nullptr},
|
||||
{"GetWindowPosition", wnd_get_position, METH_VARARGS, nullptr},
|
||||
{"GetWindowWidth", wnd_get_width, METH_VARARGS, nullptr},
|
||||
{"GetWindowHeight", wnd_get_height, METH_VARARGS, nullptr},
|
||||
{"Show", wnd_show, METH_VARARGS, nullptr},
|
||||
{"Hide", wnd_hide, METH_VARARGS, nullptr},
|
||||
{"IsShow", wnd_is_show, METH_VARARGS, nullptr},
|
||||
"""
|
||||
|
||||
known = {"SetScreenSize", "GetScreenWidth", "GetScreenHeight", "SetMouseHandler", "Register", "Destroy",
|
||||
"SetWindowSize", "SetWindowPosition", "GetWindowPosition", "GetWindowWidth", "GetWindowHeight",
|
||||
"Show", "Hide", "IsShow"}
|
||||
|
||||
method_entries = []
|
||||
for name in method_names:
|
||||
if name in known:
|
||||
continue
|
||||
if name.startswith("Register"):
|
||||
method_entries.append(f' {{"{name}", wnd_dummy_register, METH_VARARGS, nullptr}},')
|
||||
elif name.startswith("Is") or name.startswith("Get"):
|
||||
method_entries.append(f' {{"{name}", wnd_dummy_zero, METH_VARARGS, nullptr}},')
|
||||
else:
|
||||
method_entries.append(f' {{"{name}", wnd_dummy_none, METH_VARARGS, nullptr}},')
|
||||
|
||||
footer = """ {nullptr, nullptr, 0, nullptr}
|
||||
};
|
||||
auto* module = Py_InitModule("wndMgr", methods);
|
||||
|
||||
PyModule_AddIntConstant(module, "SLOT_STYLE_NONE", 0);
|
||||
PyModule_AddIntConstant(module, "SLOT_STYLE_PICK_UP", 1);
|
||||
PyModule_AddIntConstant(module, "SLOT_STYLE_SELECT", 2);
|
||||
|
||||
PyModule_AddIntConstant(module, "TEXT_HORIZONTAL_ALIGN_LEFT", 0);
|
||||
PyModule_AddIntConstant(module, "TEXT_HORIZONTAL_ALIGN_RIGHT", 1);
|
||||
PyModule_AddIntConstant(module, "TEXT_HORIZONTAL_ALIGN_CENTER", 2);
|
||||
|
||||
PyModule_AddIntConstant(module, "TEXT_VERTICAL_ALIGN_TOP", 0);
|
||||
PyModule_AddIntConstant(module, "TEXT_VERTICAL_ALIGN_BOTTOM", 1);
|
||||
PyModule_AddIntConstant(module, "TEXT_VERTICAL_ALIGN_CENTER", 2);
|
||||
|
||||
PyModule_AddIntConstant(module, "HORIZONTAL_ALIGN_LEFT", 0);
|
||||
PyModule_AddIntConstant(module, "HORIZONTAL_ALIGN_CENTER", 1);
|
||||
PyModule_AddIntConstant(module, "HORIZONTAL_ALIGN_RIGHT", 2);
|
||||
|
||||
PyModule_AddIntConstant(module, "VERTICAL_ALIGN_TOP", 0);
|
||||
PyModule_AddIntConstant(module, "VERTICAL_ALIGN_CENTER", 1);
|
||||
PyModule_AddIntConstant(module, "VERTICAL_ALIGN_BOTTOM", 2);
|
||||
|
||||
PyModule_AddIntConstant(module, "RENDERING_MODE_MODULATE", 1);
|
||||
}
|
||||
|
||||
} // namespace ava2
|
||||
"""
|
||||
|
||||
(root / "src/python_wndmgr.cpp").write_text(cpp_code + "\n".join(method_entries) + "\n" + footer)
|
||||
print(f"Generated python_wndmgr.cpp with {len(method_names)} AVA2 methods.")
|
||||
Executable
+159
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
AVA2 Cross-Platform Asset Packaging Tool
|
||||
Scans, validates, packages, and verifies official AVA2/Metin2 client assets for distribution.
|
||||
Generates an asset_manifest.json with SHA-256 integrity checksums.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import hashlib
|
||||
import shutil
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ASSET_DIRS = [
|
||||
"mark",
|
||||
"locale",
|
||||
"uiscript",
|
||||
"textureset",
|
||||
"sound",
|
||||
"runtime",
|
||||
"upstream/python-root",
|
||||
]
|
||||
|
||||
# Optional large 3D asset directory
|
||||
OPTIONAL_ASSET_DIRS = [
|
||||
"ymir work",
|
||||
"bgm",
|
||||
]
|
||||
|
||||
def compute_sha256(filepath):
|
||||
h = hashlib.sha256()
|
||||
with open(filepath, "rb") as f:
|
||||
while chunk := f.read(65536):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
def package_assets(source_dir, output_dir, manifest_path=None, include_heavy=False):
|
||||
source_path = Path(source_dir).resolve()
|
||||
dest_path = Path(output_dir).resolve()
|
||||
dest_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
scan_dirs = list(DEFAULT_ASSET_DIRS)
|
||||
if include_heavy:
|
||||
scan_dirs.extend(OPTIONAL_ASSET_DIRS)
|
||||
|
||||
manifest = {
|
||||
"version": "1.0.0",
|
||||
"source": str(source_path),
|
||||
"total_files": 0,
|
||||
"total_bytes": 0,
|
||||
"files": {}
|
||||
}
|
||||
|
||||
print(f"[*] Packaging assets from {source_path} -> {dest_path}")
|
||||
packaged_count = 0
|
||||
total_bytes = 0
|
||||
|
||||
for rel_dir in scan_dirs:
|
||||
src_dir_path = source_path / rel_dir
|
||||
if not src_dir_path.exists():
|
||||
continue
|
||||
|
||||
print(f" -> Scanning {rel_dir}...")
|
||||
for root, dirs, files in os.walk(src_dir_path):
|
||||
# Exclude build and hidden artifacts
|
||||
dirs[:] = [d for d in dirs if not d.startswith(".") and d not in ("__pycache__", "build", ".git")]
|
||||
for file in files:
|
||||
if file.startswith(".") or file.endswith(".pyc") or file.endswith(".tmp"):
|
||||
continue
|
||||
|
||||
full_path = Path(root) / file
|
||||
rel_to_source = full_path.relative_to(source_path)
|
||||
target_file = dest_path / rel_to_source
|
||||
|
||||
target_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(full_path, target_file)
|
||||
|
||||
file_size = full_path.stat().st_size
|
||||
file_hash = compute_sha256(full_path)
|
||||
|
||||
manifest["files"][str(rel_to_source).replace("\\", "/")] = {
|
||||
"size": file_size,
|
||||
"sha256": file_hash
|
||||
}
|
||||
packaged_count += 1
|
||||
total_bytes += file_size
|
||||
|
||||
manifest["total_files"] = packaged_count
|
||||
manifest["total_bytes"] = total_bytes
|
||||
|
||||
if manifest_path:
|
||||
out_manifest = Path(manifest_path)
|
||||
else:
|
||||
out_manifest = dest_path / "asset_manifest.json"
|
||||
|
||||
out_manifest.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(out_manifest, "w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, indent=2, sort_keys=True)
|
||||
|
||||
print(f"[+] Packaged {packaged_count} files ({total_bytes / (1024*1024):.2f} MB)")
|
||||
print(f"[+] Manifest written to {out_manifest}")
|
||||
return manifest
|
||||
|
||||
def verify_assets(manifest_path, target_dir):
|
||||
with open(manifest_path, "r", encoding="utf-8") as f:
|
||||
manifest = json.load(f)
|
||||
|
||||
target_path = Path(target_dir).resolve()
|
||||
print(f"[*] Verifying {manifest.get('total_files', 0)} assets in {target_path}...")
|
||||
|
||||
errors = []
|
||||
verified = 0
|
||||
|
||||
for rel_path, meta in manifest.get("files", {}).items():
|
||||
fp = target_path / rel_path
|
||||
if not fp.exists():
|
||||
errors.append(f"Missing file: {rel_path}")
|
||||
continue
|
||||
|
||||
if fp.stat().st_size != meta["size"]:
|
||||
errors.append(f"Size mismatch: {rel_path} (expected {meta['size']}, got {fp.stat().st_size})")
|
||||
continue
|
||||
|
||||
actual_hash = compute_sha256(fp)
|
||||
if actual_hash != meta["sha256"]:
|
||||
errors.append(f"Hash mismatch: {rel_path}")
|
||||
continue
|
||||
|
||||
verified += 1
|
||||
|
||||
if errors:
|
||||
print(f"[-] Verification FAILED: {len(errors)} errors found:")
|
||||
for err in errors[:10]:
|
||||
print(f" - {err}")
|
||||
return False
|
||||
else:
|
||||
print(f"[+] Verification SUCCESS: All {verified} files verified 100% OK!")
|
||||
return True
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="AVA2 Cross-Platform Asset Packaging Tool")
|
||||
parser.add_argument("--source", default=".", help="Source client directory")
|
||||
parser.add_argument("--output", default="dist/assets", help="Output packaged directory")
|
||||
parser.add_argument("--manifest", default=None, help="Manifest output path")
|
||||
parser.add_argument("--include-heavy", action="store_true", help="Include large 3D models and BGM")
|
||||
parser.add_argument("--verify", default=None, help="Verify target directory against specified manifest")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.verify:
|
||||
success = verify_assets(args.verify, args.output)
|
||||
sys.exit(0 if success else 1)
|
||||
else:
|
||||
package_assets(args.source, args.output, args.manifest, args.include_heavy)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ROOT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
BUILD_DIR="${ROOT_DIR}/build/dev"
|
||||
DIST_DIR="${ROOT_DIR}/dist"
|
||||
APP_NAME="AVA2"
|
||||
BUNDLE_DIR="${DIST_DIR}/${APP_NAME}.app"
|
||||
|
||||
echo "=========================================================="
|
||||
echo " AVA2 Metin2 Client — macOS App Packaging Tool"
|
||||
echo "=========================================================="
|
||||
echo "Root Dir: ${ROOT_DIR}"
|
||||
echo "Build Dir: ${BUILD_DIR}"
|
||||
echo "Dist Dir: ${DIST_DIR}"
|
||||
echo "Bundle: ${BUNDLE_DIR}"
|
||||
echo ""
|
||||
|
||||
# 1. Compile client targets if needed
|
||||
echo "[1/5] Building native targets..."
|
||||
cmake --build "${BUILD_DIR}" --target ava2_client -j8
|
||||
|
||||
# 2. Setup bundle structure
|
||||
echo "[2/5] Creating macOS Application Bundle directory tree..."
|
||||
rm -rf "${BUNDLE_DIR}"
|
||||
mkdir -p "${BUNDLE_DIR}/Contents/MacOS"
|
||||
mkdir -p "${BUNDLE_DIR}/Contents/Resources"
|
||||
mkdir -p "${BUNDLE_DIR}/Contents/Frameworks"
|
||||
|
||||
# 3. Copy binary
|
||||
echo "[3/5] Installing executable and Info.plist..."
|
||||
cp "${BUILD_DIR}/ava2_client" "${BUNDLE_DIR}/Contents/MacOS/ava2_client"
|
||||
chmod +x "${BUNDLE_DIR}/Contents/MacOS/ava2_client"
|
||||
|
||||
if [ -f "${ROOT_DIR}/support/mac/Info.plist.in" ]; then
|
||||
cp "${ROOT_DIR}/support/mac/Info.plist.in" "${BUNDLE_DIR}/Contents/Info.plist"
|
||||
fi
|
||||
|
||||
# 4. Package core game assets into Bundle Resources
|
||||
echo "[4/5] Packaging client assets into bundle..."
|
||||
python3 "${SCRIPT_DIR}/pack_assets.py" \
|
||||
--source "${ROOT_DIR}" \
|
||||
--output "${BUNDLE_DIR}/Contents/Resources" \
|
||||
--manifest "${BUNDLE_DIR}/Contents/Resources/asset_manifest.json"
|
||||
|
||||
# Symlink resources relative to MacOS folder for direct path resolution
|
||||
cd "${BUNDLE_DIR}/Contents/MacOS"
|
||||
ln -sf "../Resources/mark" mark
|
||||
ln -sf "../Resources/locale" locale
|
||||
ln -sf "../Resources/uiscript" uiscript
|
||||
ln -sf "../Resources/textureset" textureset
|
||||
ln -sf "../Resources/sound" sound
|
||||
ln -sf "../Resources/runtime" runtime
|
||||
ln -sf "../Resources/upstream" upstream
|
||||
cd "${ROOT_DIR}"
|
||||
|
||||
# Bundle and relocate SDL3 dylib for self-contained deployment
|
||||
if [ -f "/opt/homebrew/opt/sdl3/lib/libSDL3.0.dylib" ]; then
|
||||
echo "[4.1/5] Bundling SDL3.0.dylib into Frameworks..."
|
||||
cp "/opt/homebrew/opt/sdl3/lib/libSDL3.0.dylib" "${BUNDLE_DIR}/Contents/Frameworks/"
|
||||
install_name_tool -change "/opt/homebrew/opt/sdl3/lib/libSDL3.0.dylib" "@executable_path/../Frameworks/libSDL3.0.dylib" "${BUNDLE_DIR}/Contents/MacOS/ava2_client"
|
||||
install_name_tool -id "@executable_path/../Frameworks/libSDL3.0.dylib" "${BUNDLE_DIR}/Contents/Frameworks/libSDL3.0.dylib"
|
||||
echo "[4.2/5] Ad-hoc signing bundle binaries for macOS arm64..."
|
||||
codesign -f -s - "${BUNDLE_DIR}/Contents/Frameworks/libSDL3.0.dylib"
|
||||
codesign -f -s - "${BUNDLE_DIR}/Contents/MacOS/ava2_client"
|
||||
fi
|
||||
|
||||
# 5. Create Distribution Archive
|
||||
echo "[5/5] Creating release distribution tarball..."
|
||||
cd "${DIST_DIR}"
|
||||
tar -czf "${APP_NAME}-macOS-arm64.tar.gz" "${APP_NAME}.app"
|
||||
cd "${ROOT_DIR}"
|
||||
|
||||
BUNDLE_SIZE=$(du -sh "${BUNDLE_DIR}" | cut -f1)
|
||||
ARCHIVE_SIZE=$(du -sh "${DIST_DIR}/${APP_NAME}-macOS-arm64.tar.gz" | cut -f1)
|
||||
|
||||
echo ""
|
||||
echo "=========================================================="
|
||||
echo " Packaging Succeeded!"
|
||||
echo " Bundle: ${BUNDLE_DIR} (${BUNDLE_SIZE})"
|
||||
echo " Archive: ${DIST_DIR}/${APP_NAME}-macOS-arm64.tar.gz (${ARCHIVE_SIZE})"
|
||||
echo "=========================================================="
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pack the vendored CPython 2.7.18 Lib/ into the python27.zip the host puts on sys.path.
|
||||
|
||||
make_stdlib_zip.py <Lib dir> <out.zip>
|
||||
|
||||
40250 shipped a real python27 installation, so `import encodings` found Lib/ through the
|
||||
interpreter's prefix. The embedded interpreter has no prefix (Py_FrozenFlag, no site), so the host
|
||||
supplies the stdlib as this one file — the arrangement validated on the device by
|
||||
tools/py_embed_android/build-and-run.sh (PORT-PLAN 批次 2P step 3).
|
||||
|
||||
Entries are STORED, never deflated: the zlib module is not in the vendored Modules/ (see
|
||||
docs/THIRD-PARTY.md), so zipimport could not inflate them. Only .py goes in; zipimport reads
|
||||
source as happily as bytecode, and .pyc would pin the magic number to the build host's interpreter.
|
||||
Written deterministically (sorted, fixed timestamp) so the file's sha256 identifies its contents.
|
||||
The hash is written next to the zip as <out>.sha256 and ships with it: on Android/iOS the zip lives
|
||||
in the read-only bundle and has to be copied into the sandbox before CPython can open it, and that
|
||||
copy is accepted only when it hashes to this value (extension/src/python_stdlib.cpp, step 3c).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
# Test suites, the Tk/2to3/bsddb/pip trees and the platform-specific stubs: none of the 40250 scripts
|
||||
# or their imports reach them, and they are most of the size.
|
||||
SKIP_DIRS = {"test", "tests", "lib-tk", "idlelib", "lib2to3", "bsddb", "ensurepip", "curses",
|
||||
"distutils", "unittest", "wsgiref", "multiprocessing", "compiler"}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if len(sys.argv) != 3:
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
lib, out = Path(sys.argv[1]), Path(sys.argv[2])
|
||||
if not (lib / "os.py").is_file():
|
||||
print(f"make_stdlib_zip: {lib} is not a CPython Lib/ directory", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
members = []
|
||||
for path in sorted(lib.rglob("*.py")):
|
||||
rel = path.relative_to(lib)
|
||||
if rel.parts[0].startswith("plat-") or SKIP_DIRS.intersection(rel.parts[:-1]):
|
||||
continue
|
||||
members.append((rel, path))
|
||||
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = out.with_suffix(".zip.tmp")
|
||||
with zipfile.ZipFile(tmp, "w", zipfile.ZIP_STORED) as zf:
|
||||
for rel, path in members:
|
||||
info = zipfile.ZipInfo(rel.as_posix(), date_time=(1980, 1, 1, 0, 0, 0))
|
||||
info.external_attr = 0o644 << 16
|
||||
zf.writestr(info, path.read_bytes())
|
||||
tmp.replace(out)
|
||||
digest = hashlib.sha256(out.read_bytes()).hexdigest()
|
||||
out.with_name(out.name + ".sha256").write_text(digest + "\n")
|
||||
print(f"make_stdlib_zip: {out} ({len(members)} modules, {out.stat().st_size} bytes, sha256 {digest})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,8 @@
|
||||
from pathlib import Path
|
||||
import hashlib,json,sys
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
entries=json.loads((root/'docs/baseline.json').read_text())['files']
|
||||
bad=[e['path'] for e in entries if not (root/e['path']).is_file() or hashlib.sha256((root/e['path']).read_bytes()).hexdigest()!=e['sha256']]
|
||||
if bad:
|
||||
print('Baseline changed:', *bad, sep='\n'); sys.exit(1)
|
||||
print('Verified',len(entries),'AVA2 reference files')
|
||||
Reference in New Issue
Block a user