352 lines
17 KiB
C++
352 lines
17 KiB
C++
// Native AVA2 interface integration; real server state and session cleanup.
|
||
static const char c_szAva2NativeInterfacesScript[]=R"PY(# -*- coding: utf-8 -*-
|
||
import app,chat,chr,constInfo,datetime,game,item,localeInfo,net,pack,player,struct,ui,uiCommon,weakref
|
||
import mt_battlepass,mt_calendar,mt_wiki,mt_ava2_native_data as data
|
||
import uiBattlePassEx as battle,uiEventCalendarNew as calendar,uiWiki as encyclopedia,WikiUI
|
||
from mt_biolog import L
|
||
bp=None;cal=None;icon=None;book=None;finder=None;_selected=None;_calNext=0;_calWaiting=False;_calTime=0;_period=0;_bpNext=0;_bpTries=0;_bpReady=False;_calError=False
|
||
|
||
# Date labels follow the synchronized server period/UTC schedule, never the desktop clock.
|
||
class BattleDate:
|
||
@staticmethod
|
||
def today():
|
||
p=_period
|
||
return datetime.datetime(p//100,p%100,1) if 200001<=p<=299912 and 1<=p%100<=12 else datetime.datetime.utcfromtimestamp(app.GetGlobalTimeStamp())
|
||
class CalendarDate:
|
||
@staticmethod
|
||
def today():return datetime.datetime.utcfromtimestamp(app.GetGlobalTimeStamp())
|
||
battle.datetime=type('NativeDate',(),{'datetime':BattleDate})
|
||
calendar.datetime=type('NativeDate',(),{'datetime':CalendarDate})
|
||
calendar.events_default_data[20]=['item_drop_event',L('圣诞袜掉落')]
|
||
localeInfo.NumberToMoneyStringNEW=lambda n:format(int(n),',')
|
||
for key,text in {'TARGET_INFO_RESIST_BELL':'铃铛抗性','TARGET_INFO_RESIST_BOW':'弓箭抗性','TARGET_INFO_RESIST_DAGGER':'匕首抗性','TARGET_INFO_RESIST_FAN':'扇子抗性','TARGET_INFO_RESIST_MAGIC':'魔法抗性','TARGET_INFO_RESIST_SWORD':'剑术抗性','TARGET_INFO_RESIST_TWOHAND':'双手武器抗性'}.items():setattr(localeInfo,key,L(text+':%d%%'))
|
||
|
||
# Keep the original finder interactions while localizing its literal Worldard labels.
|
||
import uiDropItem
|
||
_dropLoad=uiDropItem.DropItemWindows.LoadWindow
|
||
_dropInfo=uiDropItem.DropItemWindows.LoadInfo
|
||
_dropReady=uiDropItem.DropItemWindows.BINARY_DROP_ITEM_LOADING
|
||
_dropSearch=uiDropItem.DropItemWindows.SearchItem
|
||
def DropValue(self):
|
||
ui.EditLine.OnIMEUpdate(self.ItemNameValue)
|
||
text=self.ItemNameValue.GetText().strip();self.get_vnum=-1
|
||
dropdown=self.DropDownList;dropdown.Clear()
|
||
matches=[row for row in uiDropItem.ITEM_LIST if text and (row['name'].lower().startswith(text.lower()) or str(row['vnum'])==text)][:10]
|
||
for row in matches:
|
||
dropdown.AppendItem(row['name'],row['vnum'])
|
||
if str(row['vnum'])==text or row['name'].lower()==text.lower():self.get_vnum=row['vnum']
|
||
dropdown.DropList.SetViewItemCount(len(matches));dropdown.DropList.SetBasePos(0)
|
||
dropdown.dropped=int(bool(matches))
|
||
if matches:dropdown.Show()
|
||
else:dropdown.Hide()
|
||
def DropSearch(self):
|
||
if self.get_vnum<=0:return
|
||
import renderTarget
|
||
renderTarget.SetVisibility(self.RENDER_TARGET_INDEX,False)
|
||
self.ModelRender.Hide();self.ModelName1.SetText('');self.ModelName2.SetText('');data._data=[]
|
||
self.LoadInfo();self.TotalResultados.SetText(L('查询中…'));self.TotalResultados.Show()
|
||
_dropSearch(self)
|
||
def DropReady(self):
|
||
_dropReady(self);self.TotalResultados.SetText(L('共 %d 条')%max(0,self.total_dates))
|
||
self.TotalPages.SetText('%d/%d'%(1 if not self.total_dates else self.page_actual,max(1,(self.total_dates+self.pages_view-1)//self.pages_view)))
|
||
def DropFailed(self):self.TotalResultados.SetText(L('查询失败,请重试或重新连接'))
|
||
uiDropItem.DropItemWindows._DropItemWindows__OnValueUpdate=DropValue
|
||
uiDropItem.DropItemWindows.SearchItem=DropSearch
|
||
uiDropItem.DropItemWindows.BINARY_DROP_ITEM_LOADING=DropReady
|
||
uiDropItem.DropItemWindows.NativeQueryFailed=DropFailed
|
||
def DropLoad(self):
|
||
_dropLoad(self)
|
||
self.GetChild('TitleName').SetText(L('掉落查询'))
|
||
self.ButtonSearch.SetToolTipText(L('查询掉落来源'))
|
||
self.ButtonDelete.SetToolTipText(L('清空查询'))
|
||
def DropInfo(self):
|
||
_dropInfo(self)
|
||
for index in xrange(min(self.pages_view,max(0,self.total_dates-(self.page_actual-1)*self.pages_view))):
|
||
row=index+(self.page_actual-1)*self.pages_view
|
||
self.ButtonsSelect['Cantidad_Item_%d'%index].SetText(L('数量:%d')%self.FReturnInfo('count_item',row))
|
||
self.TotalResultados.SetText(L('共 %d 条')%max(0,self.total_dates))
|
||
uiDropItem.DropItemWindows.LoadWindow=DropLoad
|
||
uiDropItem.DropItemWindows.LoadInfo=DropInfo
|
||
|
||
# The classic text renderer has no AVA2 inline-emoji markup. Preserve the list bullet
|
||
# in the native wiki's two text builders rather than exposing markup to the player.
|
||
def WikiTextBuilder(original):
|
||
def append(self,box,text,x,y):return original(self,box,text.replace('|Eemoji/e_wiki|e',L('·')),x,y)
|
||
return append
|
||
encyclopedia.MonsterItemSpecial.AppendTextLine=WikiTextBuilder(encyclopedia.MonsterItemSpecial.AppendTextLine)
|
||
encyclopedia.MonsterStatics.AppendTextLine=WikiTextBuilder(encyclopedia.MonsterStatics.AppendTextLine)
|
||
for name,text in {'ANIMAL':'动物','DARK':'黑暗','DEVIL':'恶魔','EARTH':'大地','ELEC':'雷电','FIRE':'火焰','HUMAN':'半人','ICE':'冰霜','METIN':'陨石','MILGYO':'密教','ORC':'鬼族','UNDEAD':'亡灵','WIND':'风','ZODIAC':'黄道'}.items():setattr(localeInfo,'TARGET_INFO_RACE_'+name,L(text))
|
||
|
||
def ArticleOpen(name,mode='r'):
|
||
import cStringIO
|
||
return cStringIO.StringIO(pack.Get(name))
|
||
encyclopedia.open=ArticleOpen
|
||
# Preview only model types implemented by the current renderer; no empty fake model.
|
||
import mt_preview
|
||
WikiUI.IsCanModelPreview=lambda v:mt_preview.Previewable('item',v)
|
||
|
||
def RealVnum(vnum):
|
||
catalogue=data.Load();base=vnum;seen=set()
|
||
while base in data._parents and base not in seen:
|
||
seen.add(base);base=data._parents[base]
|
||
current=base;seen=set()
|
||
while current and current not in seen:
|
||
seen.add(current);record=catalogue.FindItem(current)
|
||
if not record:return vnum,False
|
||
following=record['refined']
|
||
# Native EquipmentItem uses contiguous IDs; non-contiguous stones have no such recipe table.
|
||
if following and following!=current+1:return vnum,False
|
||
current=following
|
||
return (base,True) if len(seen)>1 else (vnum,False)
|
||
WikiUI.getRealVnum=RealVnum
|
||
|
||
class NativePass(battle.BattlePassWindow):
|
||
def __init__(self):
|
||
self.confirm=None;self.pendingTicket=None
|
||
battle.BattlePassWindow.__init__(self)
|
||
def Toggle(self):self.Close() if self.IsShow() else self.Open()
|
||
def Open(self):
|
||
self.isSendPacket=False
|
||
battle.BattlePassWindow.Open(self)
|
||
def Close(self):
|
||
self.CloseConfirm();self.pendingTicket=None
|
||
if self.IsShow():net.SendChatPacket('/battle_pass close')
|
||
battle.BattlePassWindow.Close(self)
|
||
def CloseConfirm(self):
|
||
if self.confirm:
|
||
self.confirm.Close();self.confirm.SetAcceptEvent(None);self.confirm.SetCancelEvent(None);self.confirm=None
|
||
def OfferTicket(self,cell,vnum):
|
||
self.pendingTicket=(cell,vnum);self.Open()
|
||
def AskTicket(self,cell,vnum):
|
||
if self.battlePassStatus!=0 or player.GetItemIndex(cell)!=vnum:return
|
||
self.CloseConfirm();q=uiCommon.QuestionDialog();self.confirm=q
|
||
q.SetText(L('消耗战令票并激活本月战令?'))
|
||
def accept():
|
||
self.CloseConfirm()
|
||
if player.GetItemIndex(cell)==vnum:net.SendChatPacket('/battle_pass activate %d %d'%(cell,vnum))
|
||
q.SetAcceptEvent(accept);q.SetCancelEvent(self.CloseConfirm);q.Open()
|
||
def ClickShop(self):
|
||
# The original button opens AVA2's cash shop 15; current tickets already use
|
||
# the inventory confirmation flow, so it selects the actual current ticket.
|
||
month=_period%100
|
||
for cell in xrange(player.INVENTORY_PAGE_SIZE*player.INVENTORY_PAGE_COUNT):
|
||
vnum=player.GetItemIndex(cell)
|
||
if 25150<=vnum<=25161:
|
||
item.SelectItem(vnum)
|
||
if item.GetValue(0)==month:self.AskTicket(cell,vnum);return
|
||
chat.AppendChat(chat.CHAT_TYPE_INFO,L('请先获得当月战令票,再使用它激活。'))
|
||
|
||
def Pass():
|
||
global bp
|
||
if bp is None:
|
||
bp=NativePass();bp.Hide()
|
||
interface=constInfo.GetInterfaceInstance()
|
||
if interface:interface.wndBattlePassEx=bp
|
||
return bp
|
||
|
||
class PassFacade:
|
||
def Toggle(self):Pass().Toggle()
|
||
def IsShow(self):return bool(bp and bp.IsShow())
|
||
def Hide(self):
|
||
if bp:bp.Close()
|
||
def OfferTicket(self,cell,vnum):Pass().OfferTicket(cell,vnum)
|
||
def Destroy(self):
|
||
global bp
|
||
if bp:bp.Close();bp.Destroy();bp=None
|
||
|
||
def CalendarWindow():
|
||
global cal
|
||
if cal is None:
|
||
cal=calendar.EventCalendarWindow();cal.Hide()
|
||
interface=constInfo.GetInterfaceInstance()
|
||
if interface:interface.wndEventManager=cal
|
||
if _calError:cal.SetTitleName(L('活动日历 · 排期暂不可用'))
|
||
return cal
|
||
|
||
def CalendarToggle():
|
||
global _calNext
|
||
wnd=CalendarWindow()
|
||
if wnd.IsShow():wnd.Close()
|
||
else:wnd.Open();_calNext=0
|
||
|
||
def RefreshCalendar(now):
|
||
global cal,icon
|
||
date=datetime.datetime.utcfromtimestamp(now)
|
||
if calendar.server_event_data:CalendarWindow()
|
||
if cal:
|
||
if (cal.currentYear,cal.currentMonth)!=(date.year,date.month):
|
||
shown=cal.IsShow();cal.Close();cal.Destroy();cal=None;CalendarWindow()
|
||
if shown:cal.Open()
|
||
cal.SetTitleName(L('活动日历 · %d年%d月')%(date.year,date.month));cal.Refresh()
|
||
if calendar.server_event_data and icon is None:
|
||
icon=calendar.MovableImage()
|
||
interface=constInfo.GetInterfaceInstance()
|
||
if interface:interface.wndEventIcon=icon
|
||
if icon:icon.Refresh()
|
||
|
||
|
||
def Wiki():
|
||
global book
|
||
if book is None:
|
||
book=encyclopedia.EncyclopediaofGame()
|
||
def entry(x,label,callback):
|
||
button=ui.MakeButton(book,x,7,L(label),'d:/ymir work/ui/public/','small_button_01.sub','small_button_02.sub','small_button_03.sub')
|
||
button.SetText(L(label));button.SetEvent(callback);return button
|
||
book.nativeCalendar=entry(book.GetWidth()-180,'活动日历',CalendarToggle)
|
||
book.nativeDrops=entry(book.GetWidth()-110,'掉落查询',DropToggle)
|
||
return book
|
||
|
||
def DropToggle():
|
||
global finder
|
||
if finder is None:
|
||
import uiDropItem
|
||
# The archived Worldard destructor re-registers its window. Use the normal
|
||
# ScriptWindow destructor, and its actual native Show path instead.
|
||
uiDropItem.DropItemWindows.__del__=ui.ScriptWindow.__del__
|
||
uiDropItem.DropItemWindows.Open=lambda self:self.Show()
|
||
finder=uiDropItem.DropItemWindows();finder.Hide()
|
||
if finder.IsShow():finder.Close()
|
||
else:finder.Show();finder.SetTop()
|
||
|
||
_showInfo=encyclopedia.EncyclopediaofGame.ShowItemInfo
|
||
def WikiShowInfo(self,vnum,arg,isHistory=True):
|
||
global _selected
|
||
_selected=(vnum,arg) if arg in (0,1) else None
|
||
return _showInfo(self,vnum,arg,isHistory)
|
||
encyclopedia.EncyclopediaofGame.ShowItemInfo=WikiShowInfo
|
||
|
||
def RefreshBook():
|
||
if book and _selected and book.IsShow() and not book.selectArg:
|
||
scroll=book.children['resultpageListboxScrollbar'];position=scroll.GetPos()
|
||
book.ShowItemInfo(_selected[0],_selected[1],False);scroll.SetPos(position)
|
||
data._refresh=RefreshBook
|
||
|
||
def Show(vnum,arg):
|
||
global _selected
|
||
wnd=Wiki();wnd.Open();_selected=(vnum,arg);wnd.ShowItemInfo(vnum,arg)
|
||
|
||
class WikiFacade:
|
||
def __init__(self):self.catalogue=None
|
||
def Load(self):self.catalogue=data.Load()
|
||
def IsShow(self):return bool(book and book.IsShow())
|
||
def Hide(self):
|
||
if book:book.Close()
|
||
def Open(self,vnum=0):
|
||
self.Load()
|
||
if vnum:Show(vnum,0)
|
||
else:Wiki().Open()
|
||
def Select(self,mode,row):Show(row['id'],1 if mode=='mobs' else 0)
|
||
def QueryRemote(self,kind,vnum,offset=0):
|
||
if kind in ('mob','chest','sources'):Show(vnum,1 if kind=='mob' else 0)
|
||
def Destroy(self):
|
||
global book
|
||
if book:book.Close();book.Destroy();book=None
|
||
constInfo.SetMainParent(None);constInfo.SetListBox(None)
|
||
|
||
_event=struct.Struct('<HB I I BB 4I BB 25s25s')
|
||
def Events(self,raw):
|
||
global _calNext,_calWaiting,_calTime,cal,_calError
|
||
# Parse atomically before replacing visible data, including byte counts and duplicate IDs.
|
||
try:
|
||
if not 6<=len(raw)<=32763:raise ValueError('length')
|
||
sub,count,now=struct.unpack_from('<BBI',raw)
|
||
if sub!=0 or count>31:raise ValueError('header')
|
||
offset=6;nextData={};ids=set()
|
||
for unused in xrange(count):
|
||
day,size=struct.unpack_from('<BB',raw,offset);offset+=2
|
||
if not 1<=day<=31 or day in nextData:raise ValueError('day')
|
||
rows={};nextData[day]=rows
|
||
for i in xrange(size):
|
||
values=_event.unpack_from(raw,offset);offset+=_event.size
|
||
eid,kind,start,end,empire,channel=values[:6]
|
||
if not eid or eid in ids or kind not in calendar.events_default_data or not start<end or empire>3 or values[10] not in (0,1) or values[11] not in (0,1):raise ValueError('event')
|
||
ids.add(eid)
|
||
begin=values[12].split(b'\0',1)[0];finish=values[13].split(b'\0',1)[0]
|
||
# Exact field order expected by native SetServerData / tooltip.
|
||
rows[eid]=[day,eid,kind,begin,finish,empire,channel]+list(values[6:10])+[start,end,bool(values[10])]
|
||
if offset!=len(raw):raise ValueError('trailing')
|
||
except (ValueError,struct.error):
|
||
chat.AppendChat(chat.CHAT_TYPE_INFO,L('活动排期数据无效,请重新打开日历。'));return
|
||
calendar.server_event_data=nextData;_calTime=now;_calWaiting=False;_calNext=app.GetTime()+15
|
||
_calError=False;RefreshCalendar(now)
|
||
|
||
_open=game.GameWindow.Open;_close=game.GameWindow.Close;_command=game.GameWindow.BINARY_ServerCommand_Run;_update=game.GameWindow.OnUpdate
|
||
|
||
def Open(self):
|
||
global bp,_period,_calNext,_bpNext,_bpTries,_bpReady,_calError
|
||
_open(self)
|
||
if mt_battlepass.g_window:mt_battlepass.g_window.Destroy()
|
||
bp=None;mt_battlepass.g_window=PassFacade();mt_battlepass.g_pass.listener=None
|
||
if mt_wiki.g_window:mt_wiki.g_window.Destroy()
|
||
mt_wiki.g_window=WikiFacade()
|
||
_period=0;_calError=False;_calNext=app.GetTime()+1;_bpNext=app.GetTime()+1;_bpTries=0;_bpReady=False
|
||
data._refresh=RefreshBook
|
||
self.interface.wndBattlePassEx=bp
|
||
self.interface.OpenBattlePass=lambda:Pass().Toggle()
|
||
self.interface.OpenWikiWindow=lambda:mt_wiki.Toggle()
|
||
self.interface.OpenEventCalendar=CalendarToggle
|
||
# Both calendar and drop finder have native entry points, also accessible on desktop keys.
|
||
keys=getattr(self,'onPressKeyDict',{})
|
||
if app.DIK_F7 not in keys:keys[app.DIK_F7]=CalendarToggle
|
||
|
||
def Close(self):
|
||
global bp,cal,icon,book,finder,_selected,_calWaiting
|
||
if bp:bp.Close()
|
||
if cal:cal.Close();cal.Destroy();cal=None
|
||
if icon:icon.Clear();icon.Destroy();icon=None
|
||
if finder:finder.Close();finder=None
|
||
_selected=None;_calWaiting=False;calendar.server_event_data={};data.Clear()
|
||
result=_close(self);bp=None;book=None
|
||
return result
|
||
|
||
def Update(self):
|
||
global _calNext,_calWaiting,_bpNext,_bpTries
|
||
_update(self);data.Tick()
|
||
if not _bpReady and _bpTries<3 and app.GetTime()>=_bpNext:
|
||
net.SendChatPacket('/battle_pass info');_bpTries+=1;_bpNext=app.GetTime()+2.25
|
||
if app.GetTime()>=_calNext:
|
||
net.SendChatPacket('/event_manager info');_calWaiting=True;_calNext=app.GetTime()+15
|
||
|
||
def Command(self,line):
|
||
global _period,_calWaiting,_calNext,_bpReady,_calError
|
||
words=line.split()
|
||
if not words:return _command(self,line)
|
||
name=words[0]
|
||
if name=='EventCalendarError':
|
||
wasError=_calError;_calError=True
|
||
calendar.server_event_data={};_calWaiting=False;_calNext=app.GetTime()+15
|
||
if icon:icon.Clear()
|
||
if cal:cal.Refresh();cal.SetTitleName(L('活动日历 · 排期暂不可用'))
|
||
if not wasError and cal and cal.IsShow():chat.AppendChat(chat.CHAT_TYPE_INFO,L('服务器尚未发布有效活动排期。'))
|
||
return 1
|
||
if name=='BattlePassPeriod' and len(words)==2:
|
||
try:_period=int(words[1])
|
||
except ValueError:pass
|
||
return 1
|
||
if name.startswith('BattlePass'):
|
||
Pass()
|
||
try:
|
||
if name=='BattlePassClear' and len(words)==1:bp.BattlePassClear()
|
||
elif name=='BattlePassSetStatusEx' and len(words)==2:bp.SetBattlePassStatusEx(int(words[1]))
|
||
elif name=='BattlePassSetStatus' and len(words)==4:
|
||
_bpReady=True
|
||
bp.SetBattlePassStatus(int(words[1]),int(words[2]),'' if words[3]=='Empty' else words[3])
|
||
if bp.pendingTicket:
|
||
ticket=bp.pendingTicket;bp.pendingTicket=None;bp.AskTicket(*ticket)
|
||
elif name=='BattlePassSetMission' and len(words)==3:bp.SetMission(int(words[1]),int(words[2]))
|
||
elif name=='BattlePassAppendMission' and len(words)==7:bp.AppendMission(int(words[1]),words[2],int(words[3]),int(words[4]),int(words[5]),int(words[6]))
|
||
except (ValueError,IndexError):chat.AppendChat(chat.CHAT_TYPE_INFO,L('战令数据暂不可用,请重新打开。'))
|
||
return 1
|
||
if name=='MTBP1':
|
||
if len(words)==3 and words[1]=='error':chat.AppendChat(chat.CHAT_TYPE_INFO,L(mt_battlepass.ERRORS.get(words[2],'战令操作失败')))
|
||
return 1
|
||
return _command(self,line)
|
||
|
||
mt_calendar.Toggle=CalendarToggle
|
||
game.GameWindow.Open=Open;game.GameWindow.Close=Close;game.GameWindow.OnUpdate=Update
|
||
game.GameWindow.BINARY_ServerCommand_Run=Command
|
||
game.GameWindow.BINARY_Ava2Events=Events
|
||
game.GameWindow.BINARY_Ava2Drop=lambda self,*args:data.Receive(*args)
|
||
|
||
)PY";
|