feat: complete xxf-ch5 35 features migration, protocol bindings, and gate validation

- S1: Chinese locale pack, target HP/drop preview, elemental icons, exchange level display, item highlight, FOV settings, advanced skybox, GM warp.
- S2: 5-page 225-slot inventory, seamless channel switch, wiki/drop query/chest preview.
- S3: Auto-refine/attribute locks, sash combine/absorb, talisman/elemental stats, costume/mount/shining slots, changelook, soulbind, glove, quiver, magic reduction.
- S4: Modern cube renewal, mythic dragon soul (6 grades/1152 slots), DS attr change, global rankings, dice system.
- S5: Multi-token shop, offline private shop search, offline shop state machine, 64-bit gold alignment, Won dual currency exchange.
- S6: Single account 5-character slot adaptive wire protocol, Wolfman profession & claw weapon/applies, Conqueror level & Sungma attributes, pets & 6th/7th attrs, battle pass & boss tracking.
- Pass 42/42 platform gate test suites in scripts/port_gate.sh macos.
This commit is contained in:
shen
2026-10-22 01:29:14 -07:00
parent 867633667f
commit 846a993183
345 changed files with 48463 additions and 326 deletions
+6 -4
View File
@@ -9,14 +9,14 @@ class WireTests(unittest.TestCase):
#include <cassert>
#include <string>
#pragma pack(push,1)
struct Item { uint32_t vnum; char body[39]; };
struct Item { uint32_t vnum; int64_t price; char body[35]; };
struct Price { uint32_t vnum,count; };
struct Frame { uint32_t owner; Item items[40]; Price prices[40]; };
#pragma pack(pop)
static_assert(sizeof(Item)==43,"native baseline wire size");
static_assert(sizeof(Frame)==2044,"shop start payload size");
static_assert(sizeof(Item)==47,"native baseline wire size");
static_assert(sizeof(Frame)==2204,"shop start payload size");
int main(){
Frame frame={};frame.items[0].vnum=25163;frame.prices[0]={90011,10};
Frame frame={};frame.items[0].vnum=25163;frame.items[0].price=100000000000LL;frame.prices[0]={90011,10};
Item items[40]={};Price prices[40]={};uint32_t owner=99;
const char* data=reinterpret_cast<const char*>(&frame);
assert(!DecodeAva2ShopStart(data,sizeof(frame)-1,owner,items,prices));assert(owner==99);
@@ -25,6 +25,8 @@ int main(){
frame.prices[1]={90010,0};assert(!DecodeAva2ShopStart(data,sizeof(frame),owner,items,prices));assert(items[0].vnum==0);
frame.prices[1]={90010,20};assert(!DecodeAva2ShopStart(data,sizeof(frame),owner,items,prices));assert(owner==99);
frame.prices[1]={0,0};assert(DecodeAva2ShopStart(data,sizeof(frame),owner,items,prices));
assert(items[0].price==100000000000LL);
frame.items[0].price=-1;assert(!DecodeAva2ShopStart(data,sizeof(frame),owner,items,prices));assert(items[0].price==100000000000LL);
assert(owner==0 && items[0].vnum==25163 && prices[0].vnum==90011 && prices[0].count==10);
}
'''
+34
View File
@@ -0,0 +1,34 @@
"""Run the production costume inventory adapter, including the two removal items."""
import sys,types,unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
SOURCE=(ROOT/'src/platform/ScriptLib/CostumeAttrScript.inc').read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class CostumeProducts(unittest.TestCase):
def setUp(self):
names=('chat','game','item','player','uiInventory','uiToolTip');self.old={n:sys.modules.get(n) for n in names};self.m={n:types.ModuleType(n) for n in names};sys.modules.update(self.m)
self.selected=0;self.attrs={0:(23,10),1:(24,20),5:(91,50),14:(99,0)};self.equipped=False
class Inventory:
def _InventoryWindow__CanUseSrcItemToDstItem(self,*args):return 'delegate'
class Tip:
def AddItemData(self,*args):pass
class Game:
def BINARY_ServerCommand_Run(self,line):return 0
self.m['uiInventory'].InventoryWindow=Inventory;self.m['uiToolTip'].ItemToolTip=Tip;self.m['game'].GameWindow=Game
p=self.m['player'];p.AutoHuntLocalize=lambda text:text;p.GetItemIndex=lambda cell:41119;p.IsEquipmentSlot=lambda cell:self.equipped;p.GetItemAttribute=lambda cell,i:self.attrs.get(i,(0,0));p.ATTRIBUTE_SLOT_MAX_NUM=7
item=self.m['item'];item.ITEM_TYPE_USE=3;item.ITEM_TYPE_COSTUME=28;item.COSTUME_TYPE_BODY=0;item.COSTUME_TYPE_HAIR=1;item.COSTUME_TYPE_MOUNT_SKIN=4
item.SelectItem=lambda v:setattr(self,'selected',v);item.GetItemType=lambda:28 if self.selected==41119 else 3;item.GetItemSubType=lambda:0;item.GetUseType=lambda v:'USE_CHANGE_ATTRIBUTE';item.GetValue=lambda index:(23,10,2)[index]
self.ns={'xrange':range};exec(SOURCE,self.ns);self.inv=Inventory()
def tearDown(self):
for n,v in self.old.items():
if v is None:sys.modules.pop(n,None)
else:sys.modules[n]=v
def test_removal_targets_normal_attributes_and_refuses_equipped(self):
method=self.inv._InventoryWindow__CanUseSrcItemToDstItem
for v in (53998,53999):
self.assertTrue(method(v,0,1));self.assertFalse(method(v,1,1));self.equipped=True;self.assertFalse(method(v,0,1));self.equipped=False
self.attrs={5:(91,50),14:(99,0)}
for v in (53998,53999):self.assertFalse(method(v,0,1))
def test_fixed_enchants_keep_duplicate_guard_and_unknown_items_delegate(self):
method=self.inv._InventoryWindow__CanUseSrcItemToDstItem
self.assertFalse(method(54001,0,1));self.attrs={};self.assertTrue(method(54001,0,1))
self.assertEqual(method(71084,0,1),'delegate')
+10 -1
View File
@@ -73,7 +73,7 @@ class WikiSelectionTests(unittest.TestCase):
class NativeFinderInputTests(unittest.TestCase):
def setUp(self):
fn=next(n for n in ast.parse(script('Ava2NativeInterfacesScript.inc')).body if isinstance(n,ast.FunctionDef) and n.name=='DropValue')
fn=next(n for n in ast.walk(ast.parse(script('Ava2NativeInterfacesScript.inc'))) if isinstance(n,ast.FunctionDef) and n.name=='DropValue')
self.ns=dict(ui=types.SimpleNamespace(EditLine=types.SimpleNamespace(OnIMEUpdate=lambda self:None)),uiDropItem=types.SimpleNamespace(ITEM_LIST=[{'name':'orc tooth','vnum':30006},{'name':'orc bone','vnum':30007}]))
exec(compile(ast.Module(body=[fn],type_ignores=[]),'<finder>','exec'),self.ns)
self.rows=[];self.visible=False;self.text='';self.widget=types.SimpleNamespace(get_vnum=123,ItemNameValue=types.SimpleNamespace(GetText=lambda:self.text),DropDownList=types.SimpleNamespace(DropList=types.SimpleNamespace(SetViewItemCount=lambda count:None,SetBasePos=lambda pos:None),Clear=self.rows.clear,AppendItem=lambda *row:self.rows.append(row),Show=lambda:setattr(self,'visible',True),Hide=lambda:setattr(self,'visible',False)))
@@ -89,4 +89,13 @@ class SourceTests(unittest.TestCase):
if not path.exists():self.skipTest('AVA2 source is not installed')
raw=path.read_bytes();self.assertEqual(hashlib.sha256(raw).hexdigest(),meta['sha256'])
self.assertEqual(script('Ava2'+meta['module']+'Source.inc'),'# -*- coding: utf-8 -*-\n'+raw.decode('cp1254').replace('\r\n','\n')+'\n')
class MoneyFormattingTests(unittest.TestCase):
def test_actual_formatter_keeps_exact_payment_amount(self):
tree=ast.parse(script('Ava2NativeInterfacesScript.inc'))
fn=next(n for n in ast.walk(tree) if isinstance(n,ast.FunctionDef) and n.name=='_FormatMoney64')
ns={'long':int};exec(compile(ast.Module(body=[fn],type_ignores=[]),'<money>','exec'),ns)
for amount in (0,5000000000,100000000000,1999999999999999,2000000000000000):
self.assertEqual(ns['_FormatMoney64'](amount),format(amount,','))
if __name__=='__main__':unittest.main()
+165
View File
@@ -0,0 +1,165 @@
"""Production offline-window controller; UI/native/socket surfaces are boundaries."""
import binascii
import importlib.util
import pathlib
import subprocess
import sys
import tempfile
import types
import unittest
ROOT=pathlib.Path(__file__).resolve().parents[2]
SOURCE=(ROOT/'src/platform/ScriptLib/Ava2OfflineShopScript.inc').read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class Widget:
def __init__(self,*args):self.visible=False;self.text='';self.children={};self.slots={};self.accept=None;self.cancel=None;self.event=None
def Show(self):self.visible=True
def Hide(self):self.visible=False
def IsShow(self):return self.visible
def SetText(self,text):self.text=text
def GetText(self):return self.text
def GetChild(self,name):return self.children.setdefault(name,Widget())
def ClearDictionary(self):self.children={}
def SetAcceptEvent(self,event):self.accept=event
def SetCancelEvent(self,event):self.cancel=event
def SetEvent(self,event):self.event=event
def SetItemSlot(self,cell,vnum,count):self.slots[cell]=(vnum,count)
def ClearSlot(self,cell):self.slots.pop(cell,None)
def Open(self):self.Show()
def Close(self):self.Hide()
def __getattr__(self,name):return lambda *args:None
class OfflineWindowTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp=tempfile.TemporaryDirectory();p=pathlib.Path(cls.tmp.name);server=ROOT.parent/'metin2-server'
# The UI data generator tests real Store/View without fork. Full crash/race
# probes run separately; macOS system SQLite uses fork-unsafe os_signpost.
subprocess.run(['c++','-std=c++17','-DPORT_ECONOMY_NO_FORK','-I'+str(server),str(server/'tests/features/fixtures/economy_view_probe.cpp'),'-lsqlite3','-o',str(p/'view')],check=True)
subprocess.run([str(p/'view'),str(p/'db'),str(p/'frames')],check=True,stdout=subprocess.DEVNULL)
cls.frames=(p/'frames').read_text().splitlines()
@classmethod
def tearDownClass(cls):cls.tmp.cleanup()
def setUp(self):
self.now=10.;self.sent=[];self.notices=[];self.items={0:(100,5)};self.sockets={};self.attrs={};self.attached=False;self.name='seller'
names=('app','chat','game','item','localeInfo','mouseModule','net','os','player','ui','uiCommon','uiToolTip','mt_biolog')
self.old={n:sys.modules.get(n) for n in names};self.mods={n:types.ModuleType(n) for n in names};sys.modules.update(self.mods)
m=self.mods
m['app'].GetTime=lambda:self.now;m['app'].DIK_F11=11
m['chat'].CHAT_TYPE_INFO=1;m['chat'].AppendChat=lambda kind,text:self.notices.append(text)
class Game:
def Open(self):pass
def Close(self):pass
def OnUpdate(self):pass
def BINARY_ServerCommand_Run(self,line):return 0
m['game'].GameWindow=Game
m['localeInfo'].NumberToMoneyString=lambda n:format(n,',')
m['net'].SendChatPacket=self.sent.append
m['os'].urandom=lambda n:b'\x01'*n
m['player'].GetName=lambda:self.name;m['player'].GetItemIndex=lambda cell:self.items.get(cell,(0,0))[0];m['player'].GetItemCount=lambda cell:self.items.get(cell,(0,0))[1]
m['player'].GetItemMetinSocket=lambda cell,index:self.sockets.get((cell,index),0)
m['player'].GetItemAttribute=lambda cell,index:self.attrs.get((cell,index),(0,0))
m['player'].SLOT_TYPE_INVENTORY=1;m['player'].INVENTORY=1
mouse=types.SimpleNamespace(isAttached=lambda:self.attached,GetAttachedType=lambda:1,GetAttachedSlotNumber=lambda:0,DeattachObject=lambda:setattr(self,'attached',False))
m['mouseModule'].mouseController=mouse
m['ui'].ScriptWindow=Widget;m['ui'].TextLine=Widget;m['ui'].MakeButton=lambda *a:Widget();m['ui'].PythonScriptLoader=lambda:types.SimpleNamespace(LoadScriptFile=lambda *a:None)
m['uiCommon'].QuestionDialog2=Widget;m['uiCommon'].InputDialog=Widget;m['uiToolTip'].ItemToolTip=Widget
m['mt_biolog'].L=lambda text:text
self.ns={'long':int,'xrange':range};exec(SOURCE,self.ns);self.w=self.ns['Get']();self.w.Open()
def tearDown(self):
for name,value in self.old.items():
if value is None:sys.modules.pop(name,None)
else:sys.modules[name]=value
def deliver(self,frames=None):
seq=str(self.w.request[0]);frames=frames or self.frames
for line in frames:
words=line.split();words[2]=seq;self.w.Receive(words)
def test_actual_cpp_snapshot_populates_original_grids_atomically(self):
self.assertIn('/mt_economy ui 0 0 ',self.sent[0]);self.assertFalse(self.w.ready)
seq=str(self.w.request[0])
for line in self.frames[:-1]:
words=line.split();words[2]=seq;self.w.Receive(words)
self.assertFalse(self.w.ready);self.assertEqual(self.w.rows,{})
self.w.Receive(['MTECON1','end',seq]);self.assertTrue(self.w.ready)
self.assertEqual(self.w.grids[0].slots[0],(100,5));self.assertEqual(len(self.w.rows[0][1]),90)
def test_missing_or_duplicate_metadata_invalidates_the_whole_snapshot(self):
self.deliver([line for line in self.frames if ' meta ' not in line]);self.assertFalse(self.w.ready);self.assertEqual(self.w.cells,{})
self.now+=2;self.w.Refresh();frames=self.frames[:3]+[self.frames[2]]+self.frames[3:];self.deliver(frames);self.assertFalse(self.w.ready)
def test_stale_page_reply_cannot_reenable_old_actions(self):
oldseq=str(self.w.request[0]);self.w.Switch(1)
self.assertIsNone(self.w.request);self.now+=2;self.w.Tick();self.assertNotEqual(str(self.w.request[0]),oldseq)
for line in self.frames:self.w.Receive(line.split()[:2]+[oldseq]+line.split()[3:])
self.assertFalse(self.w.ready);self.assertEqual(self.w.rows,{})
def test_buy_confirmation_sends_one_receipt_without_local_wallet_or_item_changes(self):
self.deliver();self.w.Select(0,0,False);accept=self.w.confirm.accept;accept();accept()
mutations=[s for s in self.sent if '/mt_economy act ' in s]
self.assertEqual(len(mutations),1);self.assertIn(' buy ',mutations[0]);self.assertEqual(self.items,{0:(100,5)})
self.assertTrue(self.w.busy);self.assertFalse(self.w.ready)
def test_order_left_claim_right_refund_and_reserved_owned_listing_cannot_cancel(self):
for refund,action in ((False,'claim'),(True,'refund')):
self.now+=2;self.w.Switch(2);frames=[]
for line in self.frames:
words=line.split()
if words[1]=='begin':words[3]='2'
elif words[1]=='row':words[7]='2'
frames.append(' '.join(words))
self.deliver(frames);self.w.Select(0,0,refund);self.w.confirm.accept()
self.assertIn(' '+action+' ',self.sent[-1]);self.w.busy=False
self.now+=2;self.w.Switch(1);frames=[]
for line in self.frames:
words=line.split()
if words[1]=='begin':words[3]='1'
elif words[1]=='row':words[7]='1'
frames.append(' '.join(words))
self.deliver(frames);previous=len(self.sent);self.w.Select(0,0,False);self.assertEqual(len(self.sent),previous);self.assertIsNone(self.w.confirm)
def test_listing_rechecks_inventory_and_preserves_full_64bit_price(self):
self.deliver();self.attached=True;self.w.ListItem(0);dialog=self.w.priceDialog;dialog.SetText('2000000000000000');dialog.accept();self.w.confirm.accept()
self.assertTrue(self.sent[-1].endswith('list 0 2000000000000000 100 5'))
self.w.busy=False;self.now+=2;self.w.Refresh();self.deliver();self.attached=True;self.w.ListItem(0);dialog=self.w.priceDialog;dialog.SetText('750');self.items[0]=(200,5);previous=len(self.sent);dialog.accept();self.assertEqual(len(self.sent),previous);self.assertIsNone(self.w.confirm)
def test_listing_rechecks_extended_metadata_at_final_confirmation(self):
self.deliver()
for values,key,value in ((self.sockets,(0,7),123),(self.attrs,(0,14),(71,50))):
self.attached=True;self.w.ListItem(0);dialog=self.w.priceDialog;dialog.SetText('750');dialog.accept()
previous=len(self.sent);values[key]=value;self.w.confirm.accept()
self.assertEqual(len(self.sent),previous);self.assertFalse(self.w.busy)
self.assertIn('背包物品已变化',self.notices[-1]);values.clear()
def test_price_dialog_consumes_ime_return_on_success_error_and_stale_callback(self):
self.deliver();self.attached=True;self.w.ListItem(0);dialog=self.w.priceDialog
dialog.SetText('0');self.assertIs(dialog.accept(),True);self.assertIsNone(self.w.confirm)
dialog.SetText('750');accept=dialog.accept;self.assertIs(accept(),True);self.assertIsNotNone(self.w.confirm)
self.assertIs(accept(),True);self.assertFalse(any('/mt_economy act ' in line for line in self.sent))
self.w.CloseDialogs();self.attached=True;self.w.ListItem(0);self.assertIs(self.w.priceDialog.cancel(),True)
def test_timeout_and_failed_submission_never_resend_a_mutation(self):
self.now+=11;self.w.Tick();self.assertFalse(self.w.ready);self.assertIsNone(self.w.request)
self.now+=2;self.w.Refresh();self.deliver();self.w.Select(0,0,False);self.w.confirm.accept();token=self.ns['_receipt'][1]
self.w.Receive(['MTECON1','action_error',token,'rejected']);self.assertFalse(self.w.busy)
self.assertEqual(sum('/mt_economy act ' in s for s in self.sent),1)
def test_64bit_ids_and_prices_are_not_float_rounded(self):
frames=[]
for line in self.frames:
words=line.split()
if words[1]=='row':words[4]='9007199254740993';words[5]='2000000000000000'
frames.append(' '.join(words))
self.deliver(frames);self.w.Select(0,0,False);self.w.confirm.accept();self.assertTrue(self.sent[-1].endswith('buy 9007199254740993 2000000000000000'))
def test_close_removes_snapshot_and_dialog_events(self):
self.deliver();self.w.Select(0,0,False);question=self.w.confirm;self.w.Close()
self.assertIsNone(question.accept);self.assertFalse(self.w.ready);self.assertEqual(self.w.rows,{})
def test_owned_cancel_and_withdraw_use_distinct_confirmed_actions(self):
self.now+=2;self.w.Switch(1);frames=[]
for line in self.frames:
words=line.split()
if words[1]=='begin':words[3]='1';words[7]='2000000000000000'
frames.append(' '.join(words))
self.deliver(frames);self.w.Select(0,0,False);self.w.confirm.accept();self.assertIn(' cancel ',self.sent[-1])
self.w.busy=False;self.now+=2;self.w.Refresh();self.deliver(frames)
self.w.Withdraw();self.w.confirm.accept();self.assertTrue(self.sent[-1].endswith(' withdraw'))
def test_stale_confirmation_cannot_submit_after_a_refresh(self):
self.deliver();self.w.Select(0,0,False);previous=self.w.confirm.accept
self.now+=2;self.w.Refresh();self.deliver();count=len(self.sent);previous()
self.assertEqual(len(self.sent),count);self.assertFalse(self.w.busy)
def test_receipt_resumes_same_character_and_is_cleared_for_another(self):
self.deliver();self.w.Select(0,0,False);self.w.confirm.accept();token=self.ns['_receipt'][1]
game=self.mods['game'].GameWindow();game.interface=types.SimpleNamespace(wndInventory=Widget());game.onPressKeyDict={}
self.ns['Open'](game);self.w=self.ns['window'];self.assertTrue(self.sent[-1].endswith(token));self.assertEqual(game.onPressKeyDict[11],self.ns['Toggle'])
self.assertIsNotNone(game.interface.wndInventory.nativeOfflineButton.event)
self.name='different';self.ns['Open'](game);self.assertIsNone(self.ns['_receipt']);self.ns['Get']().Open();self.assertTrue(self.sent[-1].endswith('0'*32))
+22
View File
@@ -0,0 +1,22 @@
"""Non-PASS gate states must fail, including missing toolchain and unknown names."""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
class PortGateStatusTests(unittest.TestCase):
def run_gate(self,name,**overrides):
with tempfile.TemporaryDirectory() as tmp:
env=dict(os.environ,MT_PORT_GATE_DIR=tmp,**overrides)
return subprocess.run(['bash',str(ROOT/'scripts/port_gate.sh'),name],env=env,cwd=ROOT,capture_output=True,text=True)
def test_unknown_platform_is_not_success(self):
result=self.run_gate('planb_unknown')
self.assertNotEqual(result.returncode,0);self.assertIn('UNKNOWN',result.stdout)
def test_missing_ndk_is_not_success(self):
result=self.run_gate('android',ANDROID_NDK_ROOT='/nonexistent/planb-ndk',ANDROID_HOME='/nonexistent/planb-sdk')
self.assertNotEqual(result.returncode,0);self.assertIn('android BLOCKED',result.stdout)