Level 120 (L1-L5): AVA2 maps, drops, dungeons, dungeon timer UI

- tools/server/level-120: sbtest install of the 120 exp table and the
  unsigned exp column.
- tools/server/ava2-maps: the 10 AVA2 maps (pack, map data, regen, designed
  drops) for sbtest; Ava2MapsScript.inc, gr2 texture and mob_proto tests.
- tools/server/ava2-dungeons: snow / ship defence / Meley quests ported from
  AVA2 (make_quests.py + install.sh).
- mt_dungeon_timer (DungeonTimerScript.inc): AVA2 dungeon timer in place of
  the minimap (RefreshDungeonTimer) and the hydra mast HP bar (gethydrahp).
- Autohunt skips a target that is hit but takes no damage for 4 s (blocked
  Meley statues) and keeps it skipped for 60 s; FindCloseTarget now honours
  the skip list.

Meley full run passed on sbtest with the Mac client. Not deployed live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-17 08:13:32 +09:00
co-authored by Claude Opus 5.5
parent 657e49e52a
commit a1e7da68a4
28 changed files with 1671 additions and 6 deletions
+32 -1
View File
@@ -23,7 +23,7 @@ REPO = Path(__file__).resolve().parents[1]
DEFAULT_EN = REPO.parent / "40250/Server Client TMP4/Client/Eternexus/locale_en/locale/en" DEFAULT_EN = REPO.parent / "40250/Server Client TMP4/Client/Eternexus/locale_en/locale/en"
DEFAULT_ZH = REPO.parent / "server_extracted/client_locale/longju/locale/taiwan" DEFAULT_ZH = REPO.parent / "server_extracted/client_locale/longju/locale/taiwan"
DEFAULT_OUTPUT = REPO / "build/zh-locale/Client" DEFAULT_OUTPUT = REPO / "build/zh-locale/Client"
BUILD_DIRS = ("build/release", "build/native") BUILD_DIRS = ("build/release", "build/native", "build/switchbot-check")
LOCALE_CFG = "10002 936 zh\n" LOCALE_CFG = "10002 936 zh\n"
DEFAULT_NAMES = REPO / "data/zh_40250" DEFAULT_NAMES = REPO / "data/zh_40250"
FORMAT = re.compile(r"%(?:\([^)]*\))?[-+#0 ]*\d*(?:\.\d+)?[diouxXeEfFgGcrs%]") FORMAT = re.compile(r"%(?:\([^)]*\))?[-+#0 ]*\d*(?:\.\d+)?[diouxXeEfFgGcrs%]")
@@ -464,6 +464,36 @@ def build_ava2_items(output: Path, pack_tool: Path):
"locked": len(report["locked"]), "assets": report["assets"], "pack": "ava2items"} "locked": len(report["locked"]), "assets": report["assets"], "pack": "ava2items"}
def build_ava2_maps(output: Path, pack_tool: Path):
"""AVA2 maps/dungeons + their monsters, layered over ava2items (see tools/server/ava2-maps)."""
import importlib.util
root = REPO / "tools/server/ava2-maps"
ava = REPO.parent / "AVA2/TEST"
reader = REPO.parent / "metin2-server/src/server/db/src/ProtoReader.cpp"
if not (ava / "1. Client DEV/pack_maker").is_dir() or not reader.is_file():
raise ValueError("AVA2 maps need ../AVA2/TEST (pack_maker + extracted server tree) and ../metin2-server")
tools = [tool(name) for name in ("mob_proto_patch", "gr2_textures")]
if not all(path.is_file() for path in tools):
raise ValueError("build mob_proto_patch and gr2_textures before generating the Chinese client")
spec = importlib.util.spec_from_file_location("ava2_maps", root / "make_maps.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
stage = output.parent / "ava2-maps"
# Reads the effective pack chain (ava2items' locale/zh/mob_proto included), so it must run after build_ava2_items.
report = module.prepare(ava, reader, output, stage, tools[0].resolve(), tools[1].resolve(), pack_tool.resolve())
for extension in ("eix", "epk"):
shutil.copy2(stage / ("ava2maps." + extension), output / "pack" / ("ava2maps." + extension))
index = output / "pack/Index"
lines = index.read_bytes().replace(b"\r\n", b"\n").splitlines()
if b"ava2maps" in lines:
del lines[lines.index(b"ava2maps") - 1:lines.index(b"ava2maps") + 1]
at = lines.index(b"ava2items") - 1
lines[at:at] = [b"*", b"ava2maps"]
index.write_bytes(b"\r\n".join(lines) + b"\r\n")
return {"mobs": report["mobs"], "races": report["races"], "files": report["files"],
"misses": len(report["misses"]), "pack": "ava2maps"}
def build_wiki(output: Path, pack_tool: Path): def build_wiki(output: Path, pack_tool: Path):
"""A versioned public server catalogue; original script and proto packs stay intact.""" """A versioned public server catalogue; original script and proto packs stay intact."""
source = REPO / "data/wiki/catalogue.txt" source = REPO / "data/wiki/catalogue.txt"
@@ -505,6 +535,7 @@ def main():
report = json.loads(report_path.read_text()) report = json.loads(report_path.read_text())
report["biolog"] = build_biolog(args.output, args.pack_tool) report["biolog"] = build_biolog(args.output, args.pack_tool)
report["ava2_items"] = build_ava2_items(args.output, args.pack_tool) report["ava2_items"] = build_ava2_items(args.output, args.pack_tool)
report["ava2_maps"] = build_ava2_maps(args.output, args.pack_tool)
report["wiki"] = build_wiki(args.output, args.pack_tool) report["wiki"] = build_wiki(args.output, args.pack_tool)
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2)+"\n", encoding="utf-8") report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2)+"\n", encoding="utf-8")
print(f"Built {args.output / 'pack/locale_zh.eix'} (.epk), registered in pack/Index") print(f"Built {args.output / 'pack/locale_zh.eix'} (.epk), registered in pack/Index")
+32
View File
@@ -0,0 +1,32 @@
// PORT: AVA2 maps and dungeons (tools/server/ava2-maps), as module mt_ava2maps. npclist.txt is read from
// the root pack only, so the ava2maps pack ships locale/zh/mt_ava2maps.txt (gbk) instead; this script feeds
// it to RaceManager (race -> model folder, folder -> shared source folder), to the minimap zone names and
// to mt_boss's server map index table. Models, maps and the mob_proto rows ship in the same pack.
static const char c_szAva2MapsScript[] = R"PY(# -*- coding: utf-8 -*-
import chrmgr
import localeInfo
import pack
PATH='locale/zh/mt_ava2maps.txt'
def Load():
if not pack.Exist(PATH):return 0
zones=getattr(localeInfo,'MINIMAP_ZONE_NAME_DICT',None)
try:
import mt_boss
maps=mt_boss.MAPS
except (ImportError,AttributeError):
maps=None
count=0
for line in pack.Get(PATH).splitlines():
t=line.rstrip('\r').split('\t')
if len(t)!=3:continue
if t[0]=='race':chrmgr.RegisterRaceName(int(t[1]),t[2]);count+=1
elif t[0]=='src':chrmgr.RegisterRaceSrcName(t[1],t[2])
elif t[0]=='zone' and zones is not None:zones[t[1]]=t[2]
elif t[0]=='map' and maps is not None:maps[int(t[1])]=t[2]
return count
RACES=Load()
)PY";
@@ -0,0 +1,124 @@
// PORT: AVA2 dungeon timer (dracaryS_DUNGEON_LIB uidungeontimer.py + uiscript/map_info.py) and hydra mast HP
// (ENABLE_DEFENSAWESHIP uishipmasthp.py), as module mt_dungeon_timer. The AVA2 dungeon quests
// (tools/server/ava2-dungeons) send "RefreshDungeonTimer <floor> <seconds left>" on entry and on every stage,
// and the ship defence sends "gethydrahp <mast hp>". Like AVA2 the timer takes the minimap's place until the
// next map load. AVA2 sweeps the boss portrait with an image cool-time our ExpandedImageBox lacks, so the
// portrait is drawn whole. The back / portrait images ship in the ava2maps pack.
static const char c_szDungeonTimerScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import background
import game
import player
import ui
import wndMgr
L=player.AutoHuntLocalize
ROOT='d:/ymir work/ui/game/dungeontimer/'
# map -> image prefix (AVA2 uidungeontimer.py); others use devil_.
PREFIX={'metin2_map_n_flame_dungeon_01':'razador_','metin2_map_n_snow_dungeon_01':'nemere_','defensawe_hydra':'hydra_',
'metin2_map_n_flame_dragon':'meley_','metin2_map_dawnmist_dungeon_01':'jotun_'}
WAVE_MAPS=('defensawe_hydra',)
MAST_MAP='defensawe_hydra'
MAST_MAX=10000000
g_game=None
g_timer=None
g_mast=None
state={'floor':0,'end':0.}
def Image(parent,path,x,y):
i=ui.ExpandedImageBox();i.SetParent(parent);i.AddFlag('not_pick')
try:i.LoadImage(path)
except:pass
i.SetPosition(x,y);i.Show();return i
def Text(parent,x,y,color=None):
t=ui.TextLine();t.SetParent(parent);t.SetPosition(x,y);t.SetHorizontalAlignCenter();t.SetOutline()
if color:t.SetPackedFontColor(color)
t.Show();return t
class Timer(ui.Window):
def __init__(self,minimap):
ui.Window.__init__(self);self.SetWindowName('DungeonTimer');self.AddFlag('not_pick')
self.minimap=minimap;self.SetSize(136,161)
prefix=PREFIX.get(background.GetCurrentMapName(),'devil_')
self.back=Image(self,ROOT+prefix+'back.sub',0,0)
self.portrait=Image(self,ROOT+prefix+'timer.sub',9,18)
self.floor=Text(self,72,50,0xffffd40b)
self.left=Text(self,72,75)
def Refresh(self,floor,seconds):
state['floor']=floor;state['end']=app.GetTime()+seconds
self.floor.SetText(L(('第 %d 波' if background.GetCurrentMapName() in WAVE_MAPS else '第 %d 层')%floor))
self.OnUpdate();self.Show()
if self.minimap:self.minimap.Hide()
def OnUpdate(self):
left=max(0,int(state['end']-app.GetTime()+0.5))
self.left.SetText('%02d:%02d'%(left//60,left%60))
if self.minimap:
x,y=self.minimap.GetGlobalPosition();w=self.minimap.GetWidth()
self.SetPosition(x+w-136 if w>=136 else x,y)
class MastHP(ui.ThinBoard):
def __init__(self):
ui.ThinBoard.__init__(self);self.SetSize(120,40);self.SetPosition(wndMgr.GetScreenWidth()-130,225)
self.text=ui.TextLine();self.text.SetParent(self);self.text.SetPosition(10,5);self.text.SetOutline()
self.text.SetText(L('船桅'));self.text.Show()
self.gauge=ui.Gauge();self.gauge.SetParent(self);self.gauge.SetPosition(13,25);self.gauge.MakeGauge(95,'red');self.gauge.Show()
def SetHP(self,hp):
self.gauge.SetPercentage(max(0,min(hp,MAST_MAX)),MAST_MAX);self.Show()
def Destroy():
global g_game,g_timer,g_mast
for w in (g_timer,g_mast):
if w:w.Hide()
g_game=g_timer=g_mast=None
def GetTimer():
global g_timer
if not g_timer and g_game:
g_timer=Timer(getattr(getattr(g_game,'interface',None),'wndMiniMap',None))
return g_timer
_open=game.GameWindow.Open
_close=game.GameWindow.Close
_command=game.GameWindow.BINARY_ServerCommand_Run
def Open(self):
global g_game,g_mast
_open(self)
Destroy();g_game=self
if background.GetCurrentMapName()==MAST_MAP:g_mast=MastHP();g_mast.SetHP(MAST_MAX)
def Close(self):
Destroy()
_close(self)
def Command(self,line):
words=line.split()
if words and words[0]=='RefreshDungeonTimer' and len(words)>=3:
t=GetTimer()
if t:t.Refresh(int(words[1]),int(words[2]))
return 1
if words and words[0]=='gethydrahp' and len(words)>=2:
if g_mast:g_mast.SetHP(int(words[1]))
return 1
return _command(self,line)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
game.GameWindow.BINARY_ServerCommand_Run=Command
)PY";
+4
View File
@@ -1031,6 +1031,8 @@ namespace PythonBoot
#include "ArmorShapesScript.inc" #include "ArmorShapesScript.inc"
#include "SashScript.inc" #include "SashScript.inc"
#include "MountScript.inc" #include "MountScript.inc"
#include "Ava2MapsScript.inc"
#include "DungeonTimerScript.inc"
#include "CostumeAttrScript.inc" #include "CostumeAttrScript.inc"
#include "PendantScript.inc" #include "PendantScript.inc"
#include "RingsScript.inc" #include "RingsScript.inc"
@@ -1127,6 +1129,8 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
install_script_module("mt_shapes", c_szArmorShapesScript); install_script_module("mt_shapes", c_szArmorShapesScript);
install_script_module("mt_sash", c_szSashScript); install_script_module("mt_sash", c_szSashScript);
install_script_module("mt_mount", c_szMountScript); install_script_module("mt_mount", c_szMountScript);
install_script_module("mt_ava2maps", c_szAva2MapsScript);
install_script_module("mt_dungeon_timer", c_szDungeonTimerScript);
install_script_module("mt_costume_attr", c_szCostumeAttrScript); install_script_module("mt_costume_attr", c_szCostumeAttrScript);
install_script_module("mt_pendant", c_szPendantScript); install_script_module("mt_pendant", c_szPendantScript);
install_script_module("mt_rings", c_szRingsScript); install_script_module("mt_rings", c_szRingsScript);
+4
View File
@@ -347,6 +347,10 @@ if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
target_link_libraries(biolog_proto_patch PRIVATE port_platform) target_link_libraries(biolog_proto_patch PRIVATE port_platform)
add_executable(item_proto_patch ${PROJECT_SOURCE_DIR}/tests/port/item_proto_patch.cpp) add_executable(item_proto_patch ${PROJECT_SOURCE_DIR}/tests/port/item_proto_patch.cpp)
target_link_libraries(item_proto_patch PRIVATE port_platform) target_link_libraries(item_proto_patch PRIVATE port_platform)
add_executable(mob_proto_patch ${PROJECT_SOURCE_DIR}/tests/port/mob_proto_patch.cpp)
target_link_libraries(mob_proto_patch PRIVATE port_platform)
add_executable(gr2_textures ${PROJECT_SOURCE_DIR}/tests/port/gr2_textures.cpp)
target_link_libraries(gr2_textures PRIVATE mt::libgr2)
# Locale packs in the original format (scripts/build_zh_locale.py packs locale/zh with it). # Locale packs in the original format (scripts/build_zh_locale.py packs locale/zh with it).
add_executable(eterpack_pack ${PROJECT_SOURCE_DIR}/tests/port/eterpack_pack.cpp) add_executable(eterpack_pack ${PROJECT_SOURCE_DIR}/tests/port/eterpack_pack.cpp)
target_link_libraries(eterpack_pack PRIVATE port_platform) target_link_libraries(eterpack_pack PRIVATE port_platform)
+9 -1
View File
@@ -446,7 +446,7 @@ bool CNetworkStream::Connect(const CNetworkAddress& c_rkNetAddr, int limitSec)
if (error != WSAEWOULDBLOCK) if (error != WSAEWOULDBLOCK)
{ {
std::fprintf(stderr, "[network] connect socket=%d error=%d (%s)\n", m_sock, error, std::strerror(error)); std::fprintf(stderr, "[network] connect socket=%d %s:%d error=%d (%s)\n", m_sock, inet_ntoa(static_cast<const SOCKADDR_IN&>(m_addr).sin_addr), ntohs(static_cast<const SOCKADDR_IN&>(m_addr).sin_port), error, std::strerror(error));
Tracen("error != WSAEWOULDBLOCK"); Tracen("error != WSAEWOULDBLOCK");
Clear(); Clear();
OnConnectFailure(); OnConnectFailure();
@@ -783,6 +783,11 @@ int CNetworkStream::__GetSendBufferSize()
bool CNetworkStream::Send(int size, const char * pSrcBuf) bool CNetworkStream::Send(int size, const char * pSrcBuf)
{ {
// PORT: a packet queued while a warp reconnect is still connecting reached the new core before its
// handshake and got the socket closed ("Handshake phase does not handle packet"); drop it instead.
if (m_sock != INVALID_SOCKET && !m_isOnline)
return false;
int sendBufRestSize = m_sendBufSize - m_sendBufInputPos; int sendBufRestSize = m_sendBufSize - m_sendBufInputPos;
if ((size + 1) > sendBufRestSize) if ((size + 1) > sendBufRestSize)
return false; return false;
@@ -864,6 +869,9 @@ bool CNetworkStream::SendSequence()
if (!m_bUseSequence) if (!m_bUseSequence)
return true; return true;
if (m_sock != INVALID_SOCKET && !m_isOnline) // PORT: see Send(); keep the sequence index in step.
return false;
BYTE bSeq = m_kVec_bSequenceTable[m_iSequence++]; BYTE bSeq = m_kVec_bSequenceTable[m_iSequence++];
bool bRet = Send(sizeof(BYTE), &bSeq); bool bRet = Send(sizeof(BYTE), &bSeq);
@@ -283,6 +283,23 @@ void CPythonBackground::__CreateProperty()
m_PropertyManager.Initialize(candidates.front().c_str()); m_PropertyManager.Initialize(candidates.front().c_str());
} }
} }
// PORT: 40250 registers only the property pack's own index. Patch packs that bring new maps
// (tools/server/ava2-maps) list their extra property files here, one pack path per line.
CMappedFile kList;
LPCVOID pvList;
if (CEterPackManager::Instance().Get(kList, "property/mt_extra_list.txt", &pvList))
{
const char* text = static_cast<const char*>(pvList);
std::string line;
for (size_t i = 0; i <= kList.Size(); ++i)
{
const char c = i < kList.Size() ? text[i] : '\n';
if (c != '\n' && c != '\r') { line += c; continue; }
if (!line.empty()) m_PropertyManager.Register(line.c_str());
line.clear();
}
}
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@@ -937,6 +937,9 @@ bool CPythonNetworkStream::RecvWarpPacket()
__DirectEnterMode_Set(m_dwSelectedCharacterIndex); __DirectEnterMode_Set(m_dwSelectedCharacterIndex);
// PORT: the phase stays "Game" until the new core's GC_PHASE arrives, and a chat sent once the new socket
// was online but before that reached the core's handshake phase; leave "Game" now so PORT_IsGamePhase drops it.
m_strPhase = "Warp";
CNetworkStream::Connect((DWORD)kWarpPacket.lAddr, kWarpPacket.wPort); CNetworkStream::Connect((DWORD)kWarpPacket.lAddr, kWarpPacket.wPort);
return true; return true;
@@ -1180,6 +1183,9 @@ bool CPythonNetworkStream::SendChatPacket(const char * c_szChat, BYTE byType)
if (strlen(c_szChat) >= 512) if (strlen(c_szChat) >= 512)
return true; return true;
if (!PORT_IsGamePhase()) // PORT: timers (e.g. /bio status) kept firing during the warp handshake.
return false;
if (c_szChat[0] == '/') if (c_szChat[0] == '/')
{ {
if (1 == strlen(c_szChat)) if (1 == strlen(c_szChat))
@@ -2424,6 +2430,8 @@ bool CPythonNetworkStream::RecvDamageInfoPacket()
{ {
if(DamageInfoPacket.damage >= 0) if(DamageInfoPacket.damage >= 0)
pInstTarget->AddDamageEffect(DamageInfoPacket.damage,DamageInfoPacket.flag,bSelf,bTarget); pInstTarget->AddDamageEffect(DamageInfoPacket.damage,DamageInfoPacket.flag,bSelf,bTarget);
if (!bSelf)
CPythonPlayer::Instance().AutoHunt_OnDamage(DamageInfoPacket.dwVID, DamageInfoPacket.damage); // PORT
else else
TraceError("Damage is equal or below 0."); TraceError("Damage is equal or below 0.");
} }
+2
View File
@@ -1796,6 +1796,8 @@ CPythonPlayer::CPythonPlayer(void)
m_dwAutoHuntTargetVID = 0; m_dwAutoHuntTargetVID = 0;
m_fAutoHuntStateTime = 0.0f; m_fAutoHuntStateTime = 0.0f;
m_fAutoHuntProgressTime = 0.0f; m_fAutoHuntProgressTime = 0.0f;
m_fAutoHuntFirstHitTime = 0.0f;
m_fAutoHuntDamageTime = 0.0f;
m_fAutoHuntBestDistance = 0.0f; m_fAutoHuntBestDistance = 0.0f;
m_fAutoHuntNextActionTime = 0.0f; m_fAutoHuntNextActionTime = 0.0f;
m_fAutoHuntNextSkillTime = 0.0f; m_fAutoHuntNextSkillTime = 0.0f;
+3
View File
@@ -740,6 +740,7 @@ class CPythonPlayer : public CSingleton<CPythonPlayer>, public IAbstractPlayer
void AutoHunt_SetSkills(const std::vector<DWORD>& indices); void AutoHunt_SetSkills(const std::vector<DWORD>& indices);
void AutoHunt_OnDeath(); void AutoHunt_OnDeath();
void AutoHunt_OnHit(DWORD victim); // PORT: actual collision hit, not attack animation void AutoHunt_OnHit(DWORD victim); // PORT: actual collision hit, not attack animation
void AutoHunt_OnDamage(DWORD victim, int damage); // PORT: GC_DAMAGE_INFO of our own attack
int AutoHunt_GetMountState() const { return m_iAutoHuntMountState; } int AutoHunt_GetMountState() const { return m_iAutoHuntMountState; }
const SAutoHuntConfig& AutoHunt_GetConfig(); const SAutoHuntConfig& AutoHunt_GetConfig();
void AutoHunt_SetConfig(const SAutoHuntConfig& c_rkConfig); void AutoHunt_SetConfig(const SAutoHuntConfig& c_rkConfig);
@@ -796,6 +797,8 @@ class CPythonPlayer : public CSingleton<CPythonPlayer>, public IAbstractPlayer
DWORD m_dwAutoHuntTargetVID; DWORD m_dwAutoHuntTargetVID;
float m_fAutoHuntStateTime; // when the current target / item / state began float m_fAutoHuntStateTime; // when the current target / item / state began
float m_fAutoHuntProgressTime; // last time the target got closer or was hit float m_fAutoHuntProgressTime; // last time the target got closer or was hit
float m_fAutoHuntFirstHitTime; // first hit on the target, 0 before it
float m_fAutoHuntDamageTime; // last hit on the target that did damage
float m_fAutoHuntBestDistance; float m_fAutoHuntBestDistance;
float m_fAutoHuntNextActionTime; float m_fAutoHuntNextActionTime;
float m_fAutoHuntNextSkillTime; float m_fAutoHuntNextSkillTime;
@@ -37,6 +37,8 @@ const float c_fAutoHuntResumeDelay = 3.0f; // after the player's own input
const float c_fAutoHuntNoProgressTime = 4.0f; // neither closer to the target nor hitting it const float c_fAutoHuntNoProgressTime = 4.0f; // neither closer to the target nor hitting it
const float c_fAutoHuntTargetTimeout = 60.0f; const float c_fAutoHuntTargetTimeout = 60.0f;
const float c_fAutoHuntSkipTime = 30.0f; // an unreachable target is left alone this long const float c_fAutoHuntSkipTime = 30.0f; // an unreachable target is left alone this long
const float c_fAutoHuntNoDamageTime = 4.0f; // hitting a target that takes no damage (Meley's stone statues)
const float c_fAutoHuntImmuneSkipTime = 60.0f; // such a target stays immune until the stage moves on
const float c_fAutoHuntLootDelay = 0.6f; // drops land a moment after the kill const float c_fAutoHuntLootDelay = 0.6f; // drops land a moment after the kill
const float c_fAutoHuntLootTimeout = 15.0f; const float c_fAutoHuntLootTimeout = 15.0f;
const float c_fAutoHuntItemTimeout = 5.0f; // one ground item (someone else's, blocked path) const float c_fAutoHuntItemTimeout = 5.0f; // one ground item (someone else's, blocked path)
@@ -326,6 +328,7 @@ void CPythonPlayer::__AutoHunt_Engage(DWORD dwVID, float fNow)
m_eAutoHuntState = AUTO_HUNT_ENGAGE; m_eAutoHuntState = AUTO_HUNT_ENGAGE;
m_fAutoHuntStateTime = fNow; m_fAutoHuntStateTime = fNow;
m_fAutoHuntProgressTime = fNow; m_fAutoHuntProgressTime = fNow;
m_fAutoHuntFirstHitTime = m_fAutoHuntDamageTime = 0.0f;
m_fAutoHuntBestDistance = 1e9f; m_fAutoHuntBestDistance = 1e9f;
m_fAutoHuntNextActionTime = fNow + 0.5f; m_fAutoHuntNextActionTime = fNow + 0.5f;
@@ -349,8 +352,18 @@ bool CPythonPlayer::__AutoHunt_IsTargetAllowed(CInstanceBase& main, CInstanceBas
// PORT: local combat can interrupt loot/blocked pursuit without changing manual input. // PORT: local combat can interrupt loot/blocked pursuit without changing manual input.
void CPythonPlayer::AutoHunt_OnHit(DWORD victim) void CPythonPlayer::AutoHunt_OnHit(DWORD victim)
{ {
if (AutoHunt_IsEnabled() && m_eAutoHuntState == AUTO_HUNT_ENGAGE && victim == m_dwAutoHuntTargetVID) if (AutoHunt_IsEnabled() && m_eAutoHuntState == AUTO_HUNT_ENGAGE && victim == m_dwAutoHuntTargetVID) {
m_fAutoHuntProgressTime = CTimer::Instance().GetCurrentSecond(); m_fAutoHuntProgressTime = CTimer::Instance().GetCurrentSecond();
if (!m_fAutoHuntFirstHitTime) m_fAutoHuntFirstHitTime = m_fAutoHuntProgressTime;
}
}
// PORT: a blocked hit (the server's DAMAGE_BLOCK, damage 0) keeps the collision progress going but hurts nothing.
void CPythonPlayer::AutoHunt_OnDamage(DWORD victim, int damage)
{
if (!AutoHunt_IsEnabled() || victim != m_dwAutoHuntTargetVID) return;
AutoHuntTrace("damage %d on target %u", damage, unsigned(victim));
if (damage > 0) m_fAutoHuntDamageTime = CTimer::Instance().GetCurrentSecond();
} }
bool CPythonPlayer::__AutoHunt_CanAttackHere(CInstanceBase& main, CInstanceBase& target) bool CPythonPlayer::__AutoHunt_CanAttackHere(CInstanceBase& main, CInstanceBase& target)
@@ -364,12 +377,15 @@ bool CPythonPlayer::__AutoHunt_CanAttackHere(CInstanceBase& main, CInstanceBase&
DWORD CPythonPlayer::__AutoHunt_FindCloseTarget(CInstanceBase& main, int* count) DWORD CPythonPlayer::__AutoHunt_FindCloseTarget(CInstanceBase& main, int* count)
{ {
DWORD best = 0; float distance = 1e9f; int nearby = 0; DWORD best = 0; float distance = 1e9f; int nearby = 0;
const float now = CTimer::Instance().GetCurrentSecond();
auto& manager = CPythonCharacterManager::Instance(); auto& manager = CPythonCharacterManager::Instance();
for (auto i = manager.CharacterInstanceBegin(); i != manager.CharacterInstanceEnd(); ++i) { for (auto i = manager.CharacterInstanceBegin(); i != manager.CharacterInstanceEnd(); ++i) {
auto* actor = *i; auto* actor = *i;
if (!actor || !__AutoHunt_IsTargetAllowed(main, *actor) || actor->IsStone() || if (!actor || !__AutoHunt_IsTargetAllowed(main, *actor) || actor->IsStone() ||
main.GetDistance(actor) > c_fAutoHuntSkillDistance || main.GetDistance(actor) > c_fAutoHuntSkillDistance ||
!main.NEW_IsClickableDistanceDestInstance(*actor)) continue; !main.NEW_IsClickableDistanceDestInstance(*actor)) continue;
const auto skip = m_kMap_dwAutoHuntSkipVID.find(actor->GetVirtualID());
if (skip != m_kMap_dwAutoHuntSkipVID.end() && now < skip->second) continue; // PORT: immune / unreachable
if (!__AutoHunt_CanAttackHere(main, *actor)) continue; if (!__AutoHunt_CanAttackHere(main, *actor)) continue;
++nearby; ++nearby;
if (actor->GetVirtualID() == m_dwAutoHuntTargetVID) best = actor->GetVirtualID(); if (actor->GetVirtualID() == m_dwAutoHuntTargetVID) best = actor->GetVirtualID();
@@ -945,10 +961,13 @@ void CPythonPlayer::__Update_AutoHunt()
// Blocked path, a target out of reach, or a safe zone that refuses the attack. // Blocked path, a target out of reach, or a safe zone that refuses the attack.
const bool isBlockedBySafeZone = rkInstMain.IsInSafe() && rkInstMain.NEW_IsClickableDistanceDestInstance(*pkInstVictim); const bool isBlockedBySafeZone = rkInstMain.IsInSafe() && rkInstMain.NEW_IsClickableDistanceDestInstance(*pkInstVictim);
if (isBlockedBySafeZone || fNow - m_fAutoHuntProgressTime > c_fAutoHuntNoProgressTime || const bool isImmune = m_fAutoHuntFirstHitTime &&
fNow - std::max(m_fAutoHuntFirstHitTime, m_fAutoHuntDamageTime) > c_fAutoHuntNoDamageTime;
if (isBlockedBySafeZone || isImmune || fNow - m_fAutoHuntProgressTime > c_fAutoHuntNoProgressTime ||
fNow - m_fAutoHuntStateTime > c_fAutoHuntTargetTimeout) fNow - m_fAutoHuntStateTime > c_fAutoHuntTargetTimeout)
{ {
m_kMap_dwAutoHuntSkipVID[m_dwAutoHuntTargetVID] = fNow + 3.f; if (isImmune) AutoHuntTrace("target %u takes no damage; skipped", unsigned(m_dwAutoHuntTargetVID));
m_kMap_dwAutoHuntSkipVID[m_dwAutoHuntTargetVID] = fNow + (isImmune ? c_fAutoHuntImmuneSkipTime : 3.f);
m_fAutoHuntCrowdUntil = fNow + 3.f; m_fAutoHuntCrowdUntil = fNow + 3.f;
__ClearAutoAttackTargetActorID(); __ClearAutoAttackTargetActorID();
__ClearReservedAction(); __AutoHunt_ResetMovement(); rkInstMain.NEW_Stop(); __ClearReservedAction(); __AutoHunt_ResetMovement(); rkInstMain.NEW_Stop();
+15
View File
@@ -0,0 +1,15 @@
// PORT: lists the texture paths named by each Granny model, for staging map/mob packs (tools/server/ava2-maps).
// stdin: one model path per line; stdout: "TEX\t<model>\t<texture>" lines, then "OK\t<model>" or "ERR\t<model>\t<why>".
#include <gr2/gr2.h>
#include <cstdio>
#include <iostream>
#include <string>
int main() {
std::string path;
while(std::getline(std::cin,path)) {
gr2::LoadError e;auto f=gr2::File::load_path(path,&e);
if(!f){std::printf("ERR\t%s\t%s %s\n",path.c_str(),e.stage.c_str(),e.message.c_str());continue;}
for(auto& m:gr2::dump_materials(*f))for(auto& t:m.all_textures)std::printf("TEX\t%s\t%s\n",path.c_str(),t.c_str());
std::printf("OK\t%s\n",path.c_str());std::fflush(stdout);
}
}
+98
View File
@@ -0,0 +1,98 @@
// PORT: adds or replaces whole mob_proto records (TMobTable, 40250 layout); untouched records stay byte-identical.
// Row: vnum type rank battle_type level size gold_min gold_max exp max_hp regen_cycle regen_pct def
// ai_flag race_flag immune_flag str dex con int dam_min dam_max attack_speed move_speed aggressive_hp_pct
// aggressive_sight attack_range enchant0..5 resist0..10 resurrection_vnum drop_item_vnum mount_capacity
// on_click empire dam_multiply summon drain_sp color polymorph_item (skill_vnum skill_level)x5
// berserk stoneskin godspeed deathblow revive \t folder \t name
#include "GameLib/StdAfx.h"
#include "UserInterface/StdAfx.h"
#include "UserInterface/PythonNonPlayer.h"
#include "EterBase/lzo.h"
#include <array>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <vector>
using Mob=CPythonNonPlayer::TMobTable;
static constexpr std::array<DWORD,4> mob_key{{4813894,18955,552631,6822045}};
static constexpr size_t kFields=69;
static std::vector<BYTE> read_file(const char* path){
std::ifstream stream(path,std::ios::binary);
if(!stream)throw std::runtime_error("cannot read proto");
return {std::istreambuf_iterator<char>(stream),std::istreambuf_iterator<char>()};
}
static DWORD word(const std::vector<BYTE>& data,size_t offset){
if(offset+4>data.size())throw std::runtime_error("truncated proto");
DWORD value;std::memcpy(&value,data.data()+offset,4);return value;
}
static void put_word(std::vector<BYTE>& data,size_t offset,DWORD value){std::memcpy(data.data()+offset,&value,4);}
static void dump(const Mob& r){
std::printf("%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %d %d %u %u %u",r.dwVnum,r.bType,r.bRank,r.bBattleType,r.bLevel,r.bSize,
r.dwGoldMin,r.dwGoldMax,r.dwExp,r.dwMaxHP,r.bRegenCycle,r.bRegenPercent,r.wDef,r.dwAIFlag,r.dwRaceFlag,r.dwImmuneFlag,
r.bStr,r.bDex,r.bCon,r.bInt,r.dwDamageRange[0],r.dwDamageRange[1],r.sAttackSpeed,r.sMovingSpeed,r.bAggresiveHPPct,r.wAggressiveSight,r.wAttackRange);
for(auto value:r.cEnchants)std::printf(" %d",int(value));
for(auto value:r.cResists)std::printf(" %d",int(value));
std::printf(" %u %u %u %u %u %g %u %u %u %u",r.dwResurrectionVnum,r.dwDropItemVnum,r.bMountCapacity,r.bOnClickType,r.bEmpire,
r.fDamMultiply,r.dwSummonVnum,r.dwDrainSP,r.dwMonsterColor,r.dwPolymorphItemVnum);
for(const auto& skill:r.Skills)std::printf(" %u %u",skill.dwVnum,skill.bLevel);
std::printf(" %u %u %u %u %u\t%.*s\t%.*s\n",r.bBerserkPoint,r.bStoneSkinPoint,r.bGodSpeedPoint,r.bDeathBlowPoint,r.bRevivePoint,
int(strnlen(r.szFolder,sizeof(r.szFolder))),r.szFolder,int(strnlen(r.szLocaleName,sizeof(r.szLocaleName))),r.szLocaleName);
}
static Mob parse(const std::string& line){
auto second=line.rfind('\t');if(second==std::string::npos||second==0)throw std::runtime_error("mob row without name");
auto first=line.rfind('\t',second-1);if(first==std::string::npos)throw std::runtime_error("mob row without folder");
const std::string name=line.substr(second+1),folder=line.substr(first+1,second-first-1);
std::istringstream stream(line.substr(0,first));std::array<double,kFields> f{};
for(auto& value:f)if(!(stream>>value))throw std::runtime_error("mob row: "+line.substr(0,40));
double extra;if(stream>>extra)throw std::runtime_error("mob row has extra columns");
if(name.size()>CHARACTER_NAME_MAX_LEN)throw std::runtime_error("mob name too long");
if(folder.size()>64)throw std::runtime_error("mob folder too long");
Mob r{};size_t i=0;auto n=[&]{return static_cast<long long>(f[i++]);};
r.dwVnum=n();r.bType=n();r.bRank=n();r.bBattleType=n();r.bLevel=n();r.bSize=n();
r.dwGoldMin=n();r.dwGoldMax=n();r.dwExp=n();r.dwMaxHP=n();r.bRegenCycle=n();r.bRegenPercent=n();r.wDef=n();
r.dwAIFlag=n();r.dwRaceFlag=n();r.dwImmuneFlag=n();r.bStr=n();r.bDex=n();r.bCon=n();r.bInt=n();
r.dwDamageRange[0]=n();r.dwDamageRange[1]=n();r.sAttackSpeed=n();r.sMovingSpeed=n();r.bAggresiveHPPct=n();
r.wAggressiveSight=n();r.wAttackRange=n();
for(auto& value:r.cEnchants)value=n();
for(auto& value:r.cResists)value=n();
r.dwResurrectionVnum=n();r.dwDropItemVnum=n();r.bMountCapacity=n();r.bOnClickType=n();r.bEmpire=n();
r.fDamMultiply=float(f[i++]);r.dwSummonVnum=n();r.dwDrainSP=n();r.dwMonsterColor=n();r.dwPolymorphItemVnum=n();
for(auto& skill:r.Skills){skill.dwVnum=n();skill.bLevel=n();}
r.bBerserkPoint=n();r.bStoneSkinPoint=n();r.bGodSpeedPoint=n();r.bDeathBlowPoint=n();r.bRevivePoint=n();
std::memcpy(r.szName,name.data(),name.size());std::memcpy(r.szLocaleName,name.data(),name.size());
std::memcpy(r.szFolder,folder.data(),folder.size());
return r;
}
int main(int argc,char** argv) {
const bool dumping=argc==3&&!std::strcmp(argv[1],"--dump");
if(argc!=4&&!dumping){std::fprintf(stderr,"usage: mob_proto_patch in_proto rows.tsv out_proto | --dump proto\n");return 2;}
if(dumping)argv[1]=argv[2];
try {
static CLZO lzo; auto key=mob_key;
auto input=read_file(argv[1]);
if(input.size()<12 || std::memcmp(input.data(),"MMPT",4))throw std::runtime_error("mob proto signature");
CLZObject decoded;
if(!CLZO::Instance().Decompress(decoded,input.data()+12,key.data()))throw std::runtime_error("mob proto decode");
if(decoded.GetSize()!=size_t(word(input,4))*sizeof(Mob))throw std::runtime_error("proto count/size mismatch");
std::map<DWORD,Mob> rows;
for(DWORD i=0;i<word(input,4);++i){Mob r;std::memcpy(&r,decoded.GetBuffer()+i*sizeof(Mob),sizeof(Mob));rows[r.dwVnum]=r;}
if(dumping){for(const auto& pair:rows)dump(pair.second);return 0;}
std::ifstream file(argv[2],std::ios::binary);std::string line;size_t added=0,replaced=0;
while(std::getline(file,line)) {
if(line.empty())continue;
const Mob r=parse(line);
(rows.count(r.dwVnum)?replaced:added)++;rows[r.dwVnum]=r;
}
std::vector<BYTE> plain;for(const auto& pair:rows){const BYTE* bytes=reinterpret_cast<const BYTE*>(&pair.second);plain.insert(plain.end(),bytes,bytes+sizeof(Mob));}
CLZObject encoded;if(!CLZO::Instance().CompressEncryptedMemory(encoded,plain.data(),plain.size(),key.data()))throw std::runtime_error("encode");
std::vector<BYTE> result(input.begin(),input.begin()+12);put_word(result,4,rows.size());put_word(result,8,encoded.GetSize());
result.insert(result.end(),encoded.GetBuffer(),encoded.GetBuffer()+encoded.GetSize());
CLZObject verified;if(!CLZO::Instance().Decompress(verified,result.data()+12,key.data()) || verified.GetSize()!=plain.size() || std::memcmp(verified.GetBuffer(),plain.data(),plain.size()))throw std::runtime_error("round-trip");
std::ofstream out(argv[3],std::ios::binary|std::ios::trunc);
if(!out.write(reinterpret_cast<const char*>(result.data()),result.size()))throw std::runtime_error("cannot write proto");
std::printf("mobs added=%zu replaced=%zu total=%zu; verified round-trip\n",added,replaced,rows.size());return 0;
}catch(const std::exception& e){std::fprintf(stderr,"%s\n",e.what());return 1;}
}
+68
View File
@@ -0,0 +1,68 @@
# AVA2 地下城任务(sbtest)
把 AVA2 的三个地下城任务移植到 203:冰雪地下城(奈梅尔瞭望塔)、九头蛇船防、赤龙巢穴。地图和怪物掉落在 `../ava2-maps`(L2/L3/L5),这里是 L4,说明见 metin2-server `docs/FEATURE-LEVEL-120.md`。现在只装在 sbtest 的 channel5 上。
| 任务 | AVA2 源文件 | 入口 NPC | 等级 | 钥匙 | 冷却 | 出口 |
|---|---|---|---|---|---|---|
| `snow_dungeon` | snow.lua | 20395,map_n_snowm_01(61) | ≥90 | 25168 | 60 分钟 | 61:4319,1647 |
| `ShipDefense` | shipdefense.lua | 9009,Metin2_map_CapeDragonHead(301) | 100–120 | 25169 | 3 小时 | 301:11082,17824 |
| `MeleyDungeon` | meleylair.lua | 20441,metin2_map_n_flame_01(62) | ≥110 | 25170 | 3 小时 | 62:5986,6573 |
GM 测试:`/level 120`,`/item 25168`(或 25169、25170),再 `/warp` 到入口 NPC 旁:冰雪 `4319 1641`,船防 `11078 17827`,赤龙 `7364 6239`。点 NPC,选任务名 → 单人进入 → 是。赤龙巢穴的冷却没有 GM 豁免。
服务端需要 metin2-server 的 L4 改动:`port_ava2_dungeon.cpp`(新增的 quest 函数)、QUEST_ATTACK_EVENT(`<vnum>.attack`,赤龙每次被打时触发)、赤龙和九头蛇的 HP 辅助函数。另外,龙之雕像(6230)一下打不死,最多剩 1 HP,只有任务的 `npc.dead_by_vnum` 能杀死它。AVA2 原版没有这层保护:第 8 层的阈值是 30000 HP,暴击高的玩家可能一下把雕像打死,副本就卡住了。
自动狩猎能打赤龙巢穴:雕像石化后,攻击只会显示“格挡”(伤害 0);如果连续 4 秒都打不出伤害,就换下一个目标,并在 60 秒内不再选它。
## 文件
| 文件 | 作用 |
|---|---|
| `make_quests.py` | 从 AVA2 生成 stage:三个任务(UTF-8)、`data/dungeon/{ice_dungeon,hydra,meley}`、赤龙怪物组、入口 NPC、新 quest 函数名。补丁都带计数断言,AVA2 源文件一改就会报错。 |
| `install.sh` | 在 203 上从 stage 目录运行,装进 sbtest 的 locale/data,可以重复运行,每次都先备份 |
`make_quests.py` 对 AVA2 任务的改动:
- `lc_quest("KEY")` 和任务提示编号换成中文(203 的任务直接写字符串);`NO_CH2` 改成 203 的格式。
- `GetMissionInfo(level, seconds)` 换成 `cmdchat("RefreshDungeonTimer ...")`。客户端的 `mt_dungeon_timer`(`src/platform/ScriptLib/DungeonTimerScript.inc`)收到后,在小地图的位置显示 AVA2 的副本计时器:Boss 头像、第几层(船防是第几波)和倒计时。船防地图里还会显示 `gethydrahp` 发来的船桅血条。计时器图片在 `../ava2-maps` 打的 ava2maps 包里。
- 去掉 203 没有的战令任务(`do_battlepass_mission`)、地下城追踪(`d.track_update`)和 `DUNGEON_COOLDOWN_EVENT` 分支,普通冷却保留。
- 203 没有 `time_str`,改成秒数。
- 九头蛇地图从 AVA2 的 972800,153600 搬到了 3276800,0,入口 10049,1652 改成 33089,116。
- 修 AVA2 的两个 bug:冰雪任务 `nemere_full_timer` / `nemere_dead_timer` 里的 `index` 没有定义;赤龙 `6230.attack` 的 `set_meley_hp` 同样。
- 删掉非 ASCII 的注释行(土耳其语、韩语注释在 GBK 下会出问题)。
## 安装到 sbtest
在本机:
```sh
python3 tools/server/ava2-dungeons/make_quests.py /tmp/ava2-dungeons # 第二个参数可以指定 AVA2 srv1 目录
cp tools/server/ava2-dungeons/install.sh /tmp/ava2-dungeons/
COPYFILE_DISABLE=1 tar czf /tmp/ava2-dungeons.tgz --no-xattrs --no-mac-metadata -C /tmp ava2-dungeons
scp /tmp/ava2-dungeons.tgz root@192.168.21.203:/usr/metin2/server/sbtest/stage/
```
在 203 上:
```sh
cd /usr/metin2/server/sbtest/stage && tar xzf ava2-dungeons.tgz && sh ava2-dungeons/install.sh
sh /usr/metin2/server/sbtest/tools/restart.sh
```
`install.sh` 依次:
1. 确认 channel5 的 locale/data 指向 sbtest(`../ava2-maps/sbtest_locale.sh`)。
2. 把 `quest/`、`data/dungeon/` 和地图 61、62 的目录从“指向线上的符号链接”换成真正的副本,免得改到线上。
3. 备份到 `sbtest/backup-conf/ava2-dungeons-<时间>`。
4. 核对怪物组、NPC 和钥匙的 vnum 都在 sbtest 的 proto 里。
5. 追加缺少的赤龙怪物组、入口 NPC 和 quest 函数名(qc 不认识的函数会编译失败;还补上了 203 列表里缺的 `table.remove`)。
6. 把任务转成 GBK(GBK 尾字节如果是 0x5C,qc 会当成反斜杠,所以遇到就停下),在独立目录里用 qc 编译,然后只替换这三个任务的 object,并加进 `locale_list`。
7. 复制地下城的 regen 数据。
channel5 的 CONFIG 里 MAP_ALLOW 要有入口地图 61、62、301,以及地下城地图 212、352、355。
- 钥匙和任务物品 25170、30331–30333 的中文名在 `../ava2-items/names_zh.tsv`;sbtest 的 item_proto 里只装了这 4 行,以免覆盖已解锁的 proto。
- qc 用 `%g` 输出数字(2129999 → 2.13e+06),这不影响运行。
- AVA2 的 regen 还引用了 6226、6227、20444 这三个组,AVA2 自己也没有,保持原样。
上线前要单独批准,见 `../ava2-maps/README.md`。
+103
View File
@@ -0,0 +1,103 @@
#!/bin/sh
# Installs the AVA2 dungeons (README.md) into the sbtest locale/data that channel5 uses; never the live ones.
# Run on 203 from the uploaded stage dir (make_quests.py output + this script): sh install.sh, then restart channel5.
# - makes real copies of the farm's quest/, data/dungeon/ and the map 61/62 dirs (sbtest_locale.sh links them to live);
# - appends the Meley groups, the entrance NPCs and the new quest function names that are missing;
# - compiles the three quests in an isolated stage and replaces only their objects.
# Idempotent; every run backs up what it changes.
set -eu
SB=${SB:-/usr/metin2/server/sbtest}
CORE=${CORE:-/usr/metin2/server/channel5/first}
LOC=$SB/share/locale/newcibn
QUEST=$LOC/quest
DATA=$SB/share/data
CONF=$SB/db
HERE=$(cd "$(dirname "$0")" && pwd)
BACKUP=$SB/backup-conf/ava2-dungeons-$(date +%Y%m%d%H%M%S)
QUESTS="snow_dungeon ShipDefense MeleyDungeon"
export LC_ALL=C
[ "$(readlink "$CORE/locale")" = "$SB/share/locale" ] || { echo "$CORE/locale is not the sbtest farm; run sbtest_locale.sh" >&2; exit 1; }
[ "$(readlink "$CORE/data")" = "$DATA" ] || { echo "$CORE/data is not the sbtest data; run sbtest_locale.sh" >&2; exit 1; }
real() # <farm entry>: replace a symlink to the live tree with a copy of it
{
[ -L "$1" ] || return 0
t=$(cd "$1" && pwd -P)
case $t in "$SB"/*) return 0 ;; esac
rm "$1" && cp -pR "$t" "$1" && echo "$1: copied from $t"
}
real "$QUEST"
real "$DATA/dungeon"
mkdir -p "$DATA/dungeon"
while IFS=" " read -r map row; do real "$LOC/map/$map"; done < "$HERE/npc.tsv"
mkdir -p "$BACKUP"
cp -p "$QUEST/locale_list" "$QUEST/quest_functions" "$LOC/group.txt" "$BACKUP/"
while IFS=" " read -r map row; do cp -p "$LOC/map/$map/npc.txt" "$BACKUP/$map.npc.txt"; done < "$HERE/npc.tsv"
echo "backup: $BACKUP"
# Every monster the groups and NPC rows name, and the dungeon keys and quest items, must be in the sbtest protos.
python3.9 - "$HERE" "$CONF" <<'EOF'
import re,sys
here,conf=sys.argv[1:]
def vnums(p):return {int(l.split(b'\t',1)[0]) for l in open(p,'rb') if l.split(b'\t',1)[0].strip().isdigit()}
mobs,items=vnums(conf+'/mob_proto.txt'),vnums(conf+'/item_proto.txt')
need={int(v) for v in re.findall(rb'^\t(?:Leader|\d+)\t\S+\t(\d+)',open(here+'/group.txt','rb').read(),re.M)}
need|={int(l.split('\t')[-1]) for l in open(here+'/npc.tsv')}
bad=['mob %d'%v for v in sorted(need-mobs)]+['item %d'%v for v in (25168,25169,25170,30331,30332,30333) if v not in items]
if bad:sys.exit('not in %s: %s'%(conf,' '.join(bad)))
EOF
# Meley groups: append the vnums group.txt lacks.
python3.9 - "$HERE/group.txt" "$LOC/group.txt" <<'EOF'
import re,sys
src,dst=sys.argv[1:]
have={int(v) for v in re.findall(rb'Vnum\s+(\d+)',open(dst,'rb').read())}
add=[b for b in re.findall(rb'Group\t\S+\r\n\{.*?\}\r\n',open(src,'rb').read(),re.S) if int(re.search(rb'Vnum\t(\d+)',b).group(1)) not in have]
if add:
t=open(dst,'rb').read()
open(dst,'ab').write((b'' if t.endswith(b'\n') else b'\r\n')+b''.join(add))
print('group.txt: %d groups added'%len(add))
EOF
# Entrance NPCs.
while IFS=" " read -r map row; do
f=$LOC/map/$map/npc.txt
vnum=${row##* }
if awk -v v="$vnum" '{ sub(/[\t\r ]+$/, "") } $1 == "m" && $NF == v { f = 1 } END { exit !f }' "$f"; then
echo "$map: npc $vnum already placed"
else
[ -z "$(tail -c 1 "$f")" ] || printf '\r\n' >> "$f"
printf '%s\r\n' "$row" >> "$f" && echo "$map: npc $vnum added"
fi
done < "$HERE/npc.tsv"
# Quest function names (qc rejects calls it does not know).
while read -r fn; do grep -qx "$fn" "$QUEST/quest_functions" || { echo "$fn" >> "$QUEST/quest_functions"; echo "quest_functions: $fn"; }; done < "$HERE/quest_functions"
# Compile in isolation; a GBK trail byte 0x5C would be a backslash to qc.
STAGE=$BACKUP/stage
mkdir -p "$STAGE"
cp "$QUEST/quest_functions" "$STAGE/"
for q in $QUESTS; do
iconv -f UTF-8 -t GBK "$HERE/quest/$q.quest" > "$STAGE/$q.quest"
if grep -q '\\' "$STAGE/$q.quest"; then echo "$q.quest: backslash byte in GBK" >&2; exit 1; fi
(cd "$STAGE" && "$QUEST/qc" "$q.quest") > "$BACKUP/qc-$q.log" 2>&1 || { cat "$BACKUP/qc-$q.log" >&2; exit 1; }
test -s "$STAGE/object/state/$q"
done
# Replace only these quests' objects.
for q in $QUESTS; do
find "$QUEST/object" -type f \( -name "$q.*" -o -path "*/state/$q" \) -exec rm {} +
cp "$STAGE/$q.quest" "$QUEST/$q.quest"
grep -qx "$q.quest" "$QUEST/locale_list" || echo "$q.quest" >> "$QUEST/locale_list"
done
(cd "$STAGE/object" && tar cf - .) | (cd "$QUEST/object" && tar xpf -)
echo "objects: $(cd "$STAGE/object" && find . -type f | wc -l) files"
# Regen data (local coordinates).
for d in ice_dungeon hydra meley; do
rm -rf "$DATA/dungeon/$d"
cp -pR "$HERE/data/dungeon/$d" "$DATA/dungeon/$d"
done
echo "done; restart channel5 (sh $SB/tools/restart.sh)"
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Stage AVA2's three new dungeons for the 203 server: quests, regen data, monster groups and entrance NPCs.
The quests are AVA2's quest/Mazmorras/{snow,shipdefense,meleylair}.lua with asserted patches (every patch must
match, so a changed source fails loudly):
- lc_quest("KEY") and the mission notice numbers become zh text (the 203 quests carry their strings inline);
- GetMissionInfo(level, seconds) becomes d.command("RefreshDungeonTimer ...") (the client ignores it for now);
- the battle pass / dungeon tracker calls and the DUNGEON_COOLDOWN_EVENT branch go (203 has neither; the normal
cooldown stays: snow 60 min, ship and Meley 3 h);
- time_str, which 203 lacks, becomes seconds;
- the hydra map entry moves with the map (AVA2 972800,153600 -> 203 3276800,0: entry 10049,1652 -> 33089,116);
- two AVA2 bugs: an undefined `index` in snow's nemere_full_timer / nemere_dead_timer warps and in Meley's
6230.attack set_meley_hp.
Output (UTF-8; install.sh converts the quests to GBK):
<stage>/quest/<name>.quest snow_dungeon, ShipDefense, MeleyDungeon
<stage>/data/dungeon/{ice_dungeon,hydra,meley}/ AVA2 regen files (local coordinates, unchanged)
<stage>/group.txt AVA2 Meley groups 6220/6223-6225 (install.sh appends the ones 203 lacks)
<stage>/npc.tsv entrance NPC rows: <map dir> <npc.txt row>
<stage>/quest_functions new quest function names (port_ava2_dungeon.cpp)
Usage: make_quests.py <stage dir> [<AVA2 srv1 dir>]
"""
import re,shutil,sys
from pathlib import Path
HERE=Path(__file__).resolve().parent
SRV1=Path(sys.argv[2]) if len(sys.argv)>2 else HERE.parents[3]/'AVA2/TEST/2. Backup SF+SRC and SQL/home/srv1'
stage=Path(sys.argv[1])
MAZ=SRV1/'share/locale/germany/quest/Mazmorras'
QUESTS={'snow_dungeon':'snow.lua','ShipDefense':'shipdefense.lua','MeleyDungeon':'meleylair.lua'}
LC={'10':'剩余时间:','11':'秒','12':'确定要开始吗?','29':'顺序不正确!','30':'奈梅尔瞭望塔','31':'开始副本',
'32':'确定要开始副本吗?','33':'冰块消失了。','50':'船只防御战','50_1':'需要等待:','51':'守住桅杆,别让它们摧毁!',
'71':'赤龙巢穴','BACK_DUNGEON':'返回副本','BACK_QUESTION':'要回到之前所在的副本吗?',
'CANT_BACK':'只能在5分钟内重新进入,已超时!','COOLDOWN':'以下玩家仍需等待:','DUNGEON_REMOVE':'副本已关闭,请从头开始。',
'ENTER_DUNGEON':'要进入副本吗?','GROUP':'要组队进入吗?','INDIVIDUAL':'单人进入','LEVEL_ERROR':'你的等级不足,无法进入此副本!',
'LOW_LEVEL':'以下玩家等级不足:','NO_CH':'副本不在本频道开启。','NO_KEY':'你没有进入副本的钥匙!',
'NO_MEMBER_KEY':'以下玩家没有钥匙:','NO_PARTY':'你不在队伍中!','NO_PARTY_MEMBER':'附近的队员不足!','PARTY':'组队进入',
'YES':'是','CANCEL':'取消'}
NOTICE={'1003':'副本完成!即将传送出去。','1019':'消灭所有怪物。','1020':'任务完成!','1021':'摧毁寒冰之石。',
'1022':'找出正确的钥匙。','1023':'钥匙不对。','1024':'按正确的顺序解开冰块。','1025':'摧毁北方龙柱。','1026':'击败奈梅尔!',
'1027':'击败艾斯特尔继续前进。','1047':'你登上了被九头蛇和它的爪牙占领的船!','1048':'准备迎接海战!','1049':'守卫船只!',
'1050':'你成功守住了桅杆!准备迎接下一波。','1051':'……但战斗还没有结束','1052':'……去领取你的宝箱奖励!',
'1053':'九头蛇和它的军队有备而来,保护船只!','1054':'它们不知疲倦地进攻,继续守卫船只!','1102':'摧毁龙之雕像!',
'1103':'摧毁所有龙蛋!','1104':'击败变异怪物!'}
# (quest, old, new, expected count)
FIXES=[
('snow_dungeon','1647*100,index,60)','1647*100,get_server_timer_arg(),60)',2),
('ShipDefense','time_str(r_cooldown)','r_cooldown.."秒"',1),
('ShipDefense','d.new_jump(355, 10049*100,1652*100)','d.new_jump(355, 33089*100,116*100)',1),
('ShipDefense','d.new_jump_party(355, 10049, 1652)','d.new_jump_party(355, 33089, 116)',1),
('ShipDefense','d.jump_all(10049,1652)','d.jump_all(33089,116)',1),
('ShipDefense','pc.warp(10049*100,1652*100, dungeonMapIndex)','pc.warp(33089*100,116*100, dungeonMapIndex)',1),
('MeleyDungeon','npc.set_meley_hp(index,6230,','npc.set_meley_hp(d.get_map_index(),6230,',8),
('MeleyDungeon','say("Bileti olmayan \xfcyeler: ")','say("以下玩家没有钥匙:")',1),
]
NEW_FUNCTIONS=['d.mission_notice','d.global_warp_all_to_base','d.new_kill_all','d.command','d.dungeon_remove_all',
'd.kill_area','d.spawn_mob_new','npc.get_protect_time','npc.set_protect_time','npc.set_statu_affect',
'npc.set_statu_clear_aff','npc.show_statu','npc.set_meley_hp','npc.show_end_statu','npc.set_protect_flag2',
'npc.dead_by_vnum','npc.set_hp','npc.get_hp',
'table.remove'] # a Lua 5.0 builtin the 203 list lacks
# Entrance NPCs AVA2 places on the 203 maps (snow: 冰原守卫 on map 61; Meley: 守望者多纳尔 on map 62).
# ShipDefense's fisherman 9009 already stands on 301 (838,1187).
NPCS=[('map_n_snowm_01','m\t735\t105\t0\t0\t0\t5\t1m\t100\t1\t20395'),
('metin2_map_n_flame_01','m\t1476\t95\t0\t0\t0\t5\t1m\t100\t1\t20441')]
GROUPS=(6220,6223,6224,6225)
def sub(text,pattern,repl,where,flags=0,min_count=1):
out,n=re.subn(pattern,repl,text,flags=flags)
if n<min_count:raise SystemExit('%s: no match for %r'%(where,pattern))
return out
def mission_info(text,where):
"""GetMissionInfo(a,b) -> d.command(string.format("RefreshDungeonTimer %d %d",a,b)); args may nest calls."""
out=[];i=0;n=0
while True:
j=text.find('GetMissionInfo(',i)
if j<0:break
k=j+len('GetMissionInfo(');depth=1;args=k
while depth:
depth+={'(':1,')':-1}.get(text[k],0);k+=1
line_start=text.rfind('\n',0,j)+1
commented=text[line_start:j].lstrip().startswith('--')
out.append(text[i:j])
out.append(text[j:k] if commented else 'd.command(string.format("RefreshDungeonTimer %%d %%d",%s))'%text[args:k-1])
n+=not commented;i=k
if not n:raise SystemExit(where+': no GetMissionInfo')
return ''.join(out)+text[i:]
def convert(name,src):
# AVA2's Turkish comments (latin1-decoded) have no GBK form
t=''.join(l for l in src.splitlines(True) if not (l.lstrip().startswith('--') and not l.isascii()))
for q,old,new,count in FIXES:
if q!=name:continue
if t.count(old)!=count:raise SystemExit('%s: %r found %d times, expected %d'%(name,old,t.count(old),count))
t=t.replace(old,new)
t=re.sub(r'lc_quest\(string\.format\("NO_CH2 %d ?",(\w+)\)\)',r'string.format("请切换到 %d 频道。",\1)',t)
def lc(m):
k=m.group(1).strip()
if k not in LC:raise SystemExit('%s: lc_quest key %r has no zh text'%(name,k))
return '"%s"'%LC[k]
t=re.sub(r'lc_quest\("([^"]*)"\)',lc,t)
def notice(m):
k=m.group(2).strip()
if k not in NOTICE:raise SystemExit('%s: notice %r has no zh text'%(name,k))
return '%s"%s")'%(m.group(1),NOTICE[k])
t=re.sub(r'(d\.mission_notice\([^,()]+(?:\(\))?,)"(\d+ ?)"\)',notice,t)
t=re.sub(r'(d\.notice\()"(\d+)"\)',notice,t)
t=mission_info(t,name)
# AVA2 systems 203 does not have: battle pass missions, the dungeon tracker, DUNGEON_COOLDOWN_EVENT.
t=re.sub(r'[ \t]*do_battlepass_mission\([^\n]*\n','',t)
t=re.sub(r'[ \t]*d\.track_update\([^\n]*\n','',t)
t=re.sub(r'[ \t]*if game\.check_event\([^\n]*\n[^\n]*\n[ \t]*else[ \t]*\n([^\n]*\n)[ \t]*end[ \t]*\n',r'\1',t)
for bad in ('lc_quest','GetMissionInfo(','do_battlepass_mission','track_update','check_event','time_str'):
if bad in t.replace('--GetMissionInfo(','').replace('-- GetMissionInfo(',''):
raise SystemExit('%s: %s left'%(name,bad))
if not re.search(r'^quest %s begin'%re.escape(name),t,re.M):raise SystemExit(name+': quest name changed')
return t
def main():
(stage/'quest').mkdir(parents=True,exist_ok=True)
for name,lua in QUESTS.items():
src=(MAZ/lua).read_bytes().decode('latin1').replace('\r\n','\n')
text=convert(name,src)
text='-- AVA2 quest/Mazmorras/%s for 203, generated by tools/server/ava2-dungeons/make_quests.py\n%s'%(lua,text)
(stage/'quest'/(name+'.quest')).write_text(text,encoding='utf-8')
text.encode('gbk') # every string must have a GBK form
data=stage/'data/dungeon'
for d in ('ice_dungeon','hydra','meley'):
if (data/d).exists():shutil.rmtree(data/d)
(data/d).mkdir(parents=True)
for f in sorted((SRV1/'share/data/dungeon'/d).glob('*.txt')):shutil.copy2(f,data/d/f.name)
blocks={}
for b in re.finditer(r'Group[ \t]+(\S+)\s*\{(.*?)\}',(SRV1/'share/locale/germany/group.txt').read_bytes().decode('latin1'),re.S):
v=re.search(r'Vnum\s+(\d+)',b.group(2))
if v and int(v.group(1)) in GROUPS:blocks[int(v.group(1))]=b.group(2)
if sorted(blocks)!=sorted(GROUPS):raise SystemExit('group.txt: missing '+str(set(GROUPS)-set(blocks)))
out=[]
for v in GROUPS:
body=[l.strip() for l in blocks[v].replace('\r','').split('\n') if l.strip()]
rows=[re.findall(r'"[^"]*"|\S+',l) for l in body]
# member names are only labels; AVA2's quoted English ones contain spaces
out+=['Group\tAVA2Meley_%d'%v,'{']+['\t'+'\t'.join(r if r[0]=='Vnum' else [r[0],'mob%s'%r[-1],r[-1]]) for r in rows]+['}']
(stage/'group.txt').write_bytes(('\r\n'.join(out)+'\r\n').encode('latin1'))
(stage/'npc.tsv').write_text(''.join('%s\t%s\n'%r for r in NPCS))
(stage/'quest_functions').write_text('\n'.join(NEW_FUNCTIONS)+'\n')
print('staged %d quests, %d data files, %d groups, %d npcs -> %s'%(len(QUESTS),sum(1 for _ in data.rglob('*.txt')),len(GROUPS),len(NPCS),stage))
if __name__=='__main__':main()
+4
View File
@@ -28,8 +28,12 @@
25167 拉扎多尔入场券 25167 拉扎多尔入场券
25168 奈梅尔入场券 25168 奈梅尔入场券
25169 九头蛇护身符 25169 九头蛇护身符
25170 赤龙巢穴入场券
28444 破碑之石+4 28444 破碑之石+4
28445 克首领之石+4 28445 克首领之石+4
30331 冰霜钥匙
30332 北极星
30333 霜花钥匙
30400 盖亚宝石 30400 盖亚宝石
30600 图样 30600 图样
30601 铠甲设计图 30601 铠甲设计图
1 # AVA2 drop items imported as 40250 items (vnum<TAB>zh name). 54001-54267 are named by range in make_items.py.
28 25167
29 25168
30 25169
31 25170
32 28444
33 28445
34 30331
35 30332
36 30333
37 30400
38 30600
39 30601
+1 -1
View File
@@ -117,7 +117,7 @@ class ConvertTests(unittest.TestCase):
def test_names_cover_ranges(self): def test_names_cover_ranges(self):
n=m.names();self.assertEqual(len(n),514+6*200+4*9+14);self.assertEqual(n[54100],'武器外观强化石') n=m.names();self.assertEqual(len(n),518+6*200+4*9+14);self.assertEqual(n[54100],'武器外观强化石')
self.assertEqual([n[v] for v in (21210,21219,21279)],['暗龙铠甲+0','暗龙铠甲+9','神龙铠甲+9']) self.assertEqual([n[v] for v in (21210,21219,21279)],['暗龙铠甲+0','暗龙铠甲+9','神龙铠甲+9'])
self.assertTrue(all(len(v.encode('gbk'))<=24 for v in n.values())) self.assertTrue(all(len(v.encode('gbk'))<=24 for v in n.values()))
+66
View File
@@ -0,0 +1,66 @@
# AVA2 新地图和地下城(sbtest)
把 AVA2 的 100–125 级地图、地下城和其中的怪物移植到 203。说明见 metin2-server `docs/FEATURE-LEVEL-120.md` 的 L2–L5。现在只装在 sbtest 的 channel5 上。
| 地图 | index | 中文名 | `/warp x y`(全局米) |
|---|---|---|---|
| plechito_desert_map_01 | 57 | 法老沙漠 | 6509 23952 |
| metin2_map_elemental_04_rework | 37 | 元素圣地 | 9320 4107 |
| metin2_map_eastplain_01 | 129 | 东间平原 | 10629 4767 |
| metin2_map_eastplain_02 | 130 | 西间荒原 | 12142 4781 |
| metin2_map_eastplain_03 | 131 | 南间深渊 | 12776 4407 |
| metin2_map_empirecastle | 132 | 皇城 | 5375 4930 |
| metin2_map_dawnmist_dungeon_01 | 210 | 晨雾地下城 | 8167 15050 |
| metin2_map_n_flame_dragon | 212 | 赤龙巢穴 | 3200 15290 |
| metin2_map_n_snow_dungeon_01 | 352 | 冰雪地下城 | 5291 1814 |
| defensawe_hydra | 355 | 九头蛇船防 | 33089 116(入口) |
- `/goto #<index>` 对新地图不可用,请用 `/warp`。
- 九头蛇在 AVA2 中的位置是 972800,153600,和 203 的地图重叠,所以搬到了 3276800,0。AVA2 任务里的坐标要按 Δ = (+2304000, −153600) 换算。地图中心那一格不能走,所以 `/warp` 到地图中心时,服务器会把人放到 3276800,0。
## 文件
| 文件 | 作用 |
|---|---|
| `make_maps.py` | 从 AVA2 生成服务端 stage(`mobs-server.tsv`、group、地图目录、动作数据)和客户端 ava2maps 包。由 `scripts/build_zh_locale.py` 调用。 |
| `names_zh.tsv` | 新怪物的中文名 |
| `drops_maps.tsv` | 新怪物的掉落设计,按档次(普通 / 精英 / 首领 / 石头 / 金怪),并可按地图或 vnum 范围追加 |
| `make_drops_maps.py` | 把 `drops_maps.tsv` 写成 stage 里的 `mob_drop_item.txt`,并核对 item_proto |
| `install_maps.py` | 把 stage 装进一个 locale + conf,可以重复运行 |
| `sbtest_locale.sh` | 给 channel5 建独立的 locale/data 目录,避免安装时改到线上的 |
## 掉落
AVA2 只给其中 8 只怪(6401 6402 6410 6411 8059 8061 9018 20442)配了掉落,203 上已有这些掉落组,保持不变。其他怪的掉落按 `drops_maps.tsv` 生成。
- 表里的“几率 %”指:角色与怪同级,没有 premium 或夺宝手套时,每杀一只的掉落几率。premium 或夺宝手套会让几率翻倍,等级差按 PERCENT_LVDELTA 表折算(首领按 PERCENT_LVDELTA_BOSS)。
- 换算公式:文件中的 pct = 几率 / 0.375。依据是 `ITEM_MANAGER::GetDropPct`:非 premium 时几率 ×1.5,随机范围是 4000000。
- 地下城的怪由任务刷出,不在 regen 里,所以地下城的特色掉落用 `mob:<first>-<last>` 指定:6222–6231 赤龙巢穴,6401–6411 冰雪地下城,6802–6812 九头蛇船防。
- 如果有未知物品,核心会拒绝加载整个 mob_drop_item.txt,所以 `make_drops_maps.py` 和 `install_maps.py` 都会先核对 vnum。
## 安装到 sbtest
在本机:
```sh
python3 scripts/build_zh_locale.py # stage 在 build/zh-locale/ava2-maps,也可以手动运行 make_maps.py
S=build/zh-locale/ava2-maps/server
python3 tools/server/ava2-maps/make_drops_maps.py $S tools/server/ava2-maps/drops_maps.tsv <sbtest 的 item_proto.txt>
scp -r $S root@192.168.21.203:/usr/metin2/server/sbtest/stage/ava2-maps/
scp tools/server/ava2-maps/{install_maps.py,sbtest_locale.sh} root@192.168.21.203:/usr/metin2/server/sbtest/tools/
```
在 203 上:
```sh
T=/usr/metin2/server/sbtest
sh $T/tools/sbtest_locale.sh
python3.9 $T/tools/install_maps.py $T/share/locale/newcibn $T/db $T/stage/ava2-maps/server \
$T/backup-conf/ava2-maps-$(date +%Y%m%d%H%M%S) $T/share/data
# 再把 channel5 CONFIG 的 MAP_ALLOW 加上 57 37 129 130 131 132 210 212 352 355
sh $T/tools/restart.sh
```
- 被修改的文件会先备份到 `backup-conf/ava2-maps-<时间>`。
- `../sbtest/rollback.sh` 会恢复 channel5 原来的 locale/data 链接。
- 如果目标 locale 里的 group.txt、group_group.txt、mob_drop_item.txt、map/ 或 map/index 是符号链接(也就是和线上共用),`install_maps.py` 会拒绝安装。
+109
View File
@@ -0,0 +1,109 @@
# Drops of the AVA2 new-map monsters (make_drops_maps.py). AVA2 itself gives almost none of them drops.
# tier item vnum count chance % (item name, comment)
# chance % = per kill, killer at the mob's level, no premium / thief glove (those double it; level gaps scale it
# by the PERCENT_LVDELTA table, bosses by PERCENT_LVDELTA_BOSS).
# Tiers: normal (PAWN/S_PAWN/KNIGHT), elite (S_KNIGHT), boss (BOSS/KING monster), stone (metin stones),
# gold (the gold mobs 4062-4067). map:<map dir> rows are added to every monster its regen files spawn,
# mob:<vnum> or mob:<first>-<last> rows to those monsters (dungeon monsters are spawned by quests, not regen:
# 6222-6231 赤龙巢穴, 6401-6411 冰雪地下城, 6802-6812 九头蛇船防).
normal 71084 1 3 物品属性转换秘籍
normal 39072 1 3 绿色碎片
normal 39073 1 1 黄色碎片
normal 27992 1 1 白珍珠
normal 27993 1 0.5 蓝珍珠
normal 27994 1 0.2 炎珍珠
normal 30625 1 1 帕德玛刚玉
normal 30626 1 1 蓝晶石
normal 30610 1 1 秘银
normal 30270 1 1 龙魂石碎片
normal 77918 1 1 青铜宝箱
normal 77921 1 1 青铜钥匙
normal 71302 1 0.5 护符强化道具
normal 72064 1 0.3 小型扩充券
elite 71084 3 15 物品属性转换秘籍
elite 71085 1 2 追加物品属性秘籍
elite 39073 1 5 黄色碎片
elite 27993 1 2 蓝珍珠
elite 27994 1 1 炎珍珠
elite 50255 1 3 龙魂原石
elite 30270 2 5 龙魂石碎片
elite 77919 1 3 白银宝箱
elite 77922 1 3 白银钥匙
elite 71302 1 2 护符强化道具
elite 100300 1 1 绿龙豆
elite 21210 1 0.1 暗龙铠甲 (lv115)
elite 21230 1 0.1 风龙铠甲 (lv115)
elite 21250 1 0.1 魔龙铠甲 (lv115)
elite 21270 1 0.1 神龙铠甲 (lv115)
boss 71084 30 100 物品属性转换秘籍
boss 71085 5 50 追加物品属性秘籍
boss 77920 1 50 黄金宝箱
boss 77923 1 50 黄金钥匙
boss 27992 2 50 白珍珠
boss 27993 1 30 蓝珍珠
boss 27994 1 20 炎珍珠
boss 50255 10 100 龙魂原石
boss 30270 5 100 龙魂石碎片
boss 100300 1 30 绿龙豆
boss 100400 1 15 蓝龙豆
boss 80008 5 30 黄金锭
boss 72066 1 10 大型扩充券
boss 71302 5 50 护符强化道具
boss 30627 1 30 神之果实
boss 30628 1 30 神圣之花
boss 30629 1 10 众神灵药
boss 70043 1 2 夺宝手套
boss 70005 1 2 护佑戒指
boss 21210 1 3 暗龙铠甲 (lv115)
boss 21230 1 3 风龙铠甲 (lv115)
boss 21250 1 3 魔龙铠甲 (lv115)
boss 21270 1 3 神龙铠甲 (lv115)
boss 320 1 1.5 守护者之剑 (lv120)
boss 340 1 1.5 守护者之刃 (lv120)
boss 1190 1 1.5 守护者匕首 (lv120)
boss 2210 1 1.5 守护者之弓 (lv120)
boss 3230 1 1.5 守护者大刀 (lv120)
boss 5170 1 1.5 守护者之铃 (lv120)
boss 7310 1 1.5 守护者之扇 (lv120)
boss 17560 1 5 青玉耳环 (lv100)
boss 16560 1 5 青玉项链 (lv100)
boss 14560 1 5 青玉手镯 (lv100)
boss 15460 1 3 锆石之鞋 (lv110)
boss 15470 1 3 孔雀石之鞋 (lv110)
boss 18080 1 2 灵魂腹带
stone 71084 20 100 物品属性转换秘籍
stone 80008 3 50 黄金锭
stone 27987 1 40 珍珠蚌
stone 39073 2 100 黄色碎片
stone 30270 3 80 龙魂石碎片
stone 71302 3 60 护符强化道具
stone 50255 3 60 龙魂原石
stone 30626 2 40 蓝晶石
stone 77919 1 30 白银宝箱
stone 77922 1 30 白银钥匙
stone 72065 1 10 中型扩充券
stone 72066 1 5 大型扩充券
stone 70043 1 1 夺宝手套
stone 70005 1 1 护佑戒指
gold 80003 1 20 银砖(5万两)
gold 80004 1 10 银砖(10万两)
gold 80005 1 3 金砖(50万两)
gold 80006 1 1 金砖(100万两)
gold 71084 1 5 物品属性转换秘籍
mob:6222-6231 30620 1 2 红龙之角
mob:6222-6231 30621 1 2 红龙鳞片
mob:6231 30620 5 100 红龙之角 (赤龙)
mob:6231 30621 5 100 红龙鳞片 (赤龙)
mob:6231 30630 1 30 龙之翼 (赤龙)
mob:6401-6411 71123 1 2 水龙鳞片
mob:6401-6411 71129 1 2 水龙爪
mob:6802-6812 71123 1 3 水龙鳞片
mob:6802-6812 71129 1 3 水龙爪
mob:6812 71123 5 100 水龙鳞片 (九头蛇)
mob:6812 71129 5 100 水龙爪 (九头蛇)
1 # Drops of the AVA2 new-map monsters (make_drops_maps.py). AVA2 itself gives almost none of them drops.
2 # tier item vnum count chance % (item name, comment)
3 # chance % = per kill, killer at the mob's level, no premium / thief glove (those double it; level gaps scale it
4 # by the PERCENT_LVDELTA table, bosses by PERCENT_LVDELTA_BOSS).
5 # Tiers: normal (PAWN/S_PAWN/KNIGHT), elite (S_KNIGHT), boss (BOSS/KING monster), stone (metin stones),
6 # gold (the gold mobs 4062-4067). map:<map dir> rows are added to every monster its regen files spawn,
7 # mob:<vnum> or mob:<first>-<last> rows to those monsters (dungeon monsters are spawned by quests, not regen:
8 # 6222-6231 赤龙巢穴, 6401-6411 冰雪地下城, 6802-6812 九头蛇船防).
9 normal 71084 1 3 物品属性转换秘籍
10 normal 39072 1 3 绿色碎片
11 normal 39073 1 1 黄色碎片
12 normal 27992 1 1 白珍珠
13 normal 27993 1 0.5 蓝珍珠
14 normal 27994 1 0.2 炎珍珠
15 normal 30625 1 1 帕德玛刚玉
16 normal 30626 1 1 蓝晶石
17 normal 30610 1 1 秘银
18 normal 30270 1 1 龙魂石碎片
19 normal 77918 1 1 青铜宝箱
20 normal 77921 1 1 青铜钥匙
21 normal 71302 1 0.5 护符强化道具
22 normal 72064 1 0.3 小型扩充券
23 elite 71084 3 15 物品属性转换秘籍
24 elite 71085 1 2 追加物品属性秘籍
25 elite 39073 1 5 黄色碎片
26 elite 27993 1 2 蓝珍珠
27 elite 27994 1 1 炎珍珠
28 elite 50255 1 3 龙魂原石
29 elite 30270 2 5 龙魂石碎片
30 elite 77919 1 3 白银宝箱
31 elite 77922 1 3 白银钥匙
32 elite 71302 1 2 护符强化道具
33 elite 100300 1 1 绿龙豆
34 elite 21210 1 0.1 暗龙铠甲 (lv115)
35 elite 21230 1 0.1 风龙铠甲 (lv115)
36 elite 21250 1 0.1 魔龙铠甲 (lv115)
37 elite 21270 1 0.1 神龙铠甲 (lv115)
38 boss 71084 30 100 物品属性转换秘籍
39 boss 71085 5 50 追加物品属性秘籍
40 boss 77920 1 50 黄金宝箱
41 boss 77923 1 50 黄金钥匙
42 boss 27992 2 50 白珍珠
43 boss 27993 1 30 蓝珍珠
44 boss 27994 1 20 炎珍珠
45 boss 50255 10 100 龙魂原石
46 boss 30270 5 100 龙魂石碎片
47 boss 100300 1 30 绿龙豆
48 boss 100400 1 15 蓝龙豆
49 boss 80008 5 30 黄金锭
50 boss 72066 1 10 大型扩充券
51 boss 71302 5 50 护符强化道具
52 boss 30627 1 30 神之果实
53 boss 30628 1 30 神圣之花
54 boss 30629 1 10 众神灵药
55 boss 70043 1 2 夺宝手套
56 boss 70005 1 2 护佑戒指
57 boss 21210 1 3 暗龙铠甲 (lv115)
58 boss 21230 1 3 风龙铠甲 (lv115)
59 boss 21250 1 3 魔龙铠甲 (lv115)
60 boss 21270 1 3 神龙铠甲 (lv115)
61 boss 320 1 1.5 守护者之剑 (lv120)
62 boss 340 1 1.5 守护者之刃 (lv120)
63 boss 1190 1 1.5 守护者匕首 (lv120)
64 boss 2210 1 1.5 守护者之弓 (lv120)
65 boss 3230 1 1.5 守护者大刀 (lv120)
66 boss 5170 1 1.5 守护者之铃 (lv120)
67 boss 7310 1 1.5 守护者之扇 (lv120)
68 boss 17560 1 5 青玉耳环 (lv100)
69 boss 16560 1 5 青玉项链 (lv100)
70 boss 14560 1 5 青玉手镯 (lv100)
71 boss 15460 1 3 锆石之鞋 (lv110)
72 boss 15470 1 3 孔雀石之鞋 (lv110)
73 boss 18080 1 2 灵魂腹带
74 stone 71084 20 100 物品属性转换秘籍
75 stone 80008 3 50 黄金锭
76 stone 27987 1 40 珍珠蚌
77 stone 39073 2 100 黄色碎片
78 stone 30270 3 80 龙魂石碎片
79 stone 71302 3 60 护符强化道具
80 stone 50255 3 60 龙魂原石
81 stone 30626 2 40 蓝晶石
82 stone 77919 1 30 白银宝箱
83 stone 77922 1 30 白银钥匙
84 stone 72065 1 10 中型扩充券
85 stone 72066 1 5 大型扩充券
86 stone 70043 1 1 夺宝手套
87 stone 70005 1 1 护佑戒指
88 gold 80003 1 20 银砖(5万两)
89 gold 80004 1 10 银砖(10万两)
90 gold 80005 1 3 金砖(50万两)
91 gold 80006 1 1 金砖(100万两)
92 gold 71084 1 5 物品属性转换秘籍
93 mob:6222-6231 30620 1 2 红龙之角
94 mob:6222-6231 30621 1 2 红龙鳞片
95 mob:6231 30620 5 100 红龙之角 (赤龙)
96 mob:6231 30621 5 100 红龙鳞片 (赤龙)
97 mob:6231 30630 1 30 龙之翼 (赤龙)
98 mob:6401-6411 71123 1 2 水龙鳞片
99 mob:6401-6411 71129 1 2 水龙爪
100 mob:6802-6812 71123 1 3 水龙鳞片
101 mob:6802-6812 71129 1 3 水龙爪
102 mob:6812 71123 5 100 水龙鳞片 (九头蛇)
103 mob:6812 71129 5 100 水龙爪 (九头蛇)
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Install the AVA2 maps stage (make_maps.py output/server) into a server locale + conf.
- mobs-server.tsv -> conf/mob_proto.txt + mob_names.txt, rows replaced by vnum.
- group.txt / group_group.txt: blocks whose Vnum is missing are appended; existing vnums are kept.
- map/<dir> copied (an existing real dir is moved to the backup first; a symlink is refused).
- map/index: missing "<index> <dir>" lines appended; an index used by another map is refused.
- data/monster/<folder> (optional 5th arg = the core's data dir): only folders it lacks are added.
- mob_drop_item.txt (make_drops_maps.py output): the group of each monster that has no drop group yet is appended;
every item vnum must be in conf/item_proto.txt (the core refuses the whole file on an unknown item).
- Then every regen group and mob reference is checked against the installed tables.
Rerunning is idempotent. Runs on 203 (python3.9). The core reads the locale at boot and the db reads
conf at boot: restart db and the core afterwards.
Usage: install_maps.py <locale dir> <conf dir> <stage server dir> <fresh backup dir> [<data dir>]
"""
import re,shutil,sys
from pathlib import Path
locale,conf,stage,backup=map(Path,sys.argv[1:5])
data=Path(sys.argv[5]) if len(sys.argv)>5 else None
if backup.exists():raise SystemExit('use a fresh backup directory')
backup.mkdir(parents=True)
def lines(raw):return [l for l in raw.replace(b'\r\n',b'\n').split(b'\n') if l.strip()]
def newline(raw):return b'\r\n' if b'\r\n' in raw else b'\n'
def write(path,data):
tmp=path.with_name(path.name+'.tmp');tmp.write_bytes(data);tmp.replace(path)
def save(path):
dest=backup/path.relative_to(path.parents[1]) if path.parent.name=='map' else backup/path.name
dest.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dest)
# mob_proto.txt + mob_names.txt
rows={int(l.split(b'\t',1)[0]):l for l in lines((stage/'mobs-server.tsv').read_bytes())}
for name,row in (('mob_proto.txt',lambda v:rows[v]),('mob_names.txt',lambda v:str(v).encode()+b'\t'+rows[v].split(b'\t')[1])):
path=conf/name;raw=path.read_bytes();save(path)
kept=[l for l in lines(raw) if not (l.split(b'\t',1)[0].isdigit() and int(l.split(b'\t',1)[0]) in rows)]
write(path,newline(raw).join(kept+[row(v) for v in sorted(rows)])+newline(raw))
mobs={int(l.split(b'\t',1)[0]) for l in lines((conf/'mob_proto.txt').read_bytes()) if l.split(b'\t',1)[0].isdigit()}
# group.txt / group_group.txt
BLOCK=re.compile(rb'Group[ \t]+\S+\s*\{.*?\}',re.S)
def blocks(raw):return {int(re.search(rb'Vnum\s+(\d+)',b).group(1)):b for b in BLOCK.findall(raw)}
appended={}
for name in ('group.txt','group_group.txt'):
path=locale/name
if path.is_symlink():raise SystemExit('%s is a symlink (shared with the live locale?)'%path)
raw=path.read_bytes();have=blocks(raw);new=blocks((stage/name).read_bytes())
missing=[new[v] for v in sorted(new) if v not in have];appended[name]=len(missing)
if missing:
save(path);nl=newline(raw)
write(path,raw.rstrip(b'\r\n')+nl+nl.join(b.replace(b'\r\n',b'\n').replace(b'\n',nl) for b in missing)+nl)
groups=blocks((locale/'group.txt').read_bytes());ggroups=blocks((locale/'group_group.txt').read_bytes())
# map dirs + index
mapdir=locale/'map';index_path=mapdir/'index'
if index_path.is_symlink() or mapdir.is_symlink():raise SystemExit('%s is shared with the live locale'%mapdir)
raw=index_path.read_bytes();index={}
for l in lines(raw):
t=l.split()
if len(t)>=2 and t[0].isdigit():index[int(t[0])]=t[1].decode()
add=[]
for l in lines((stage/'index.txt').read_bytes()):
i,m=int(l.split()[0]),l.split()[1].decode()
if index.get(i,m)!=m:raise SystemExit('map index %d is %s on the server, not %s'%(i,index[i],m))
if i not in index:add.append(b'%d %s'%(i,m.encode()))
dst=mapdir/m
if dst.is_symlink():raise SystemExit('%s is a symlink'%dst)
if dst.exists():(backup/'map').mkdir(exist_ok=True);shutil.move(str(dst),str(backup/'map'/m))
shutil.copytree(str(stage/'map'/m),str(dst))
if add:save(index_path);write(index_path,raw.rstrip(b'\r\n')+newline(raw)+newline(raw).join(add)+newline(raw))
# server motion data
motion_added=0
if data:
if (data/'monster').is_symlink() or data.is_symlink():raise SystemExit('%s is shared with the live data'%data)
for f in sorted((stage/'data/monster').iterdir()):
dst=data/'monster'/f.name
if not (dst.exists() or dst.is_symlink()):shutil.copytree(str(f),str(dst));motion_added+=1
# mob drops
drops_added=0;errors=[]
if (stage/'mob_drop_item.txt').exists():
path=locale/'mob_drop_item.txt'
if path.is_symlink():raise SystemExit('%s is a symlink (shared with the live locale?)'%path)
raw=path.read_bytes();nl=newline(raw)
DROP=re.compile(rb'Group[ \t]+(\S+)\s*\{(.*?)\}',re.S)
names={n.lower() for n,_ in DROP.findall(raw)}
have={int(m.group(1)) for n,b in DROP.findall(raw) if re.search(rb'Type\s+drop',b,re.I)
for m in [re.search(rb'Mob\s+(\d+)',b)] if m}
items={int(l.split(b'\t',1)[0]) for l in lines((conf/'item_proto.txt').read_bytes()) if l.split(b'\t',1)[0].isdigit()}
add_drops=[]
for m in DROP.finditer((stage/'mob_drop_item.txt').read_bytes()):
mob=int(re.search(rb'Mob\s+(\d+)',m.group(2)).group(1))
if mob in have:continue
if m.group(1).lower() in names:raise SystemExit('drop group name %s already used'%m.group(1).decode())
for v in re.findall(rb'\n\s*\d+\s+(\d+)\s+\d+\s+[\d.]+',m.group(0)):
if int(v) not in items:errors.append('drop group %s: item %s not in item_proto'%(m.group(1).decode(),v.decode()))
if mob not in mobs:errors.append('drop group %s: mob %d missing'%(m.group(1).decode(),mob))
add_drops.append(m.group(0).replace(b'\r\n',b'\n').replace(b'\n',nl))
if errors:raise SystemExit('\n'.join(sorted(set(errors)))+'\nmob_drop_item.txt not changed')
if add_drops:
save(path);write(path,raw.rstrip(b'\r\n')+nl+nl.join(add_drops)+nl);drops_added=len(add_drops)
# checks
for v in map(int,(stage/'mob_refs.txt').read_text().split()):
if v not in mobs:errors.append('mob %d missing from mob_proto'%v)
for l in lines((stage/'index.txt').read_bytes()):
m=l.split()[1].decode()
for f in ('regen.txt','npc.txt','boss.txt','stone.txt','dungeon.txt'):
for r in lines((mapdir/m/f).read_bytes()):
t=r.split()
if not t or t[0].startswith(b'/'):continue
kind=t[0][:1].lower();v=int(t[-1]) if len(t)>=11 and t[-1].isdigit() else None
if v is None:continue
if kind==b'g' and v not in groups:errors.append('%s/%s: group %d missing'%(m,f,v))
if kind==b'r' and v not in ggroups:errors.append('%s/%s: group_group %d missing'%(m,f,v))
if kind in (b'm',b's') and v not in mobs:errors.append('%s/%s: mob %d missing'%(m,f,v))
for v,b in blocks((stage/'group.txt').read_bytes()).items():
for mob in re.findall(rb'\n\s*(?:Leader|\d+)\s+\S+\s+(\d+)',groups[v]):
if int(mob) not in mobs:errors.append('group %d: mob %s missing'%(v,mob.decode()))
print('AVA2 maps installed: mobs=%d groups+=%d group_groups+=%d index+=%d motion+=%d drops+=%d backup=%s'%(len(rows),appended['group.txt'],appended['group_group.txt'],len(add),motion_added,drops_added,backup))
if errors:
print('\n'.join(sorted(set(errors))));raise SystemExit('%d reference errors'%len(set(errors)))
print('references OK')
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Write mob_drop_item groups for the AVA2 new-map monsters from drops_maps.tsv.
Each monster in the stage's mobs-server.tsv gets its tier's rows (by rank and type, see drops_maps.tsv),
plus the map:<dir> rows of every map that spawns it (regen/boss/stone/dungeon.txt, directly or via
group.txt / group_group.txt) and the mob:<vnum> / mob:<first>-<last> rows covering it.
NPCs, warps and buildings get nothing.
The chance column is converted to the file's pct: per kill = pct*10000 * delta% * 1.5 (no premium) / 4000000,
so pct = chance% / 0.375 at delta 100. Every item vnum is checked against the given item_proto files.
Output: <stage server dir>/mob_drop_item.txt (one 'drop' group per monster); install_maps.py appends the
groups of monsters the server has no drop group for.
Usage: make_drops_maps.py <stage server dir> <drops_maps.tsv> <item_proto.txt>...
"""
import collections,re,sys
from pathlib import Path
stage,table=Path(sys.argv[1]),Path(sys.argv[2])
GOLD=range(4062,4068)
known=set()
for p in sys.argv[3:]:
for l in Path(p).read_bytes().splitlines():
h=l.split(b'\t',1)[0].strip()
if h.isdigit():known.add(int(h))
rows=collections.defaultdict(list);bad=[]
for n,l in enumerate(table.read_text(encoding='utf-8').splitlines(),1):
if not l.strip() or l.startswith('#'):continue
t=l.split('\t')
tier,vnum,count,chance=t[0],int(t[1]),int(t[2]),float(t[3])
if vnum not in known:bad.append('%s:%d: item %d not in item_proto'%(table.name,n,vnum))
if not 0<chance<=100 or count<1:bad.append('%s:%d: bad count/chance'%(table.name,n))
rows[tier].append((vnum,count,chance))
if bad:raise SystemExit('\n'.join(bad))
mobs={}
for l in (stage/'mobs-server.tsv').read_bytes().splitlines():
t=l.split(b'\t');mobs[int(t[0])]=(t[2].decode(),t[3].decode())
def tier(vnum):
rank,kind=mobs[vnum]
if vnum in GOLD:return 'gold'
if kind=='STONE':return 'stone'
if kind!='MONSTER':return None
return {'S_KNIGHT':'elite','BOSS':'boss','KING':'boss'}.get(rank,'normal')
# which maps spawn each monster
BLOCK=re.compile(rb'Group[ \t]+\S+\s*\{(.*?)\}',re.S)
def members(path):
r={}
for b in BLOCK.findall(path.read_bytes()):
v=int(re.search(rb'Vnum\s+(\d+)',b).group(1))
r[v]=[int(m) for m in re.findall(rb'\n\s*(?:Leader|\d+)\s+\S+\s+(\d+)',b)]
return r
groups=members(stage/'group.txt');ggroups=members(stage/'group_group.txt')
maps=collections.defaultdict(set)
for d in (stage/'map').iterdir():
for f in ('regen.txt','boss.txt','stone.txt','dungeon.txt'):
if not (d/f).exists():continue
for r in (d/f).read_bytes().splitlines():
t=r.split()
if len(t)<11 or t[0].startswith(b'/') or not t[-1].isdigit():continue
kind,v=t[0][:1].lower(),int(t[-1])
spawned=[v] if kind in (b'm',b's') else groups.get(v,[]) if kind==b'g' else \
[m for g in ggroups.get(v,[]) for m in groups.get(g,[])] if kind==b'r' else []
for m in spawned:maps[m].add(d.name)
out=[];count=collections.Counter()
for v in sorted(mobs):
t=tier(v)
if not t:continue
items=list(rows[t])
for m in sorted(maps[v]):items+=rows['map:'+m]
for k in rows:
if k.startswith('mob:'):
lo,_,hi=k[4:].partition('-')
if int(lo)<=v<=int(hi or lo):items+=rows[k]
if len(items)>255:raise SystemExit('mob %d: %d rows (max 255)'%(v,len(items)))
out+=['Group\tAVA2MAP_%d'%v,'{','\tMob\t%d'%v,'\tType\tdrop']
out+=['\t%d\t%d\t%d\t%s'%(i,vnum,n,('%.4f'%(c/0.375)).rstrip('0').rstrip('.')) for i,(vnum,n,c) in enumerate(items,1)]
out+=['}'];count[t]+=1
(stage/'mob_drop_item.txt').write_bytes(('\r\n'.join(out)+'\r\n').encode())
unused=[k for k in rows if k.startswith('map:') and k[4:] not in {m for s in maps.values() for m in s}]
unused+=[k for k in rows if k.startswith('mob:') and not any(int(k[4:].partition('-')[0])<=v<=int(k[4:].partition('-')[2] or k[4:]) for v in mobs)]
print('drop groups: %d (%s) -> %s'%(sum(count.values()),', '.join('%s %d'%kv for kv in sorted(count.items())),stage/'mob_drop_item.txt'))
if unused:raise SystemExit('rows for no monster: '+' '.join(unused))
+379
View File
@@ -0,0 +1,379 @@
#!/usr/bin/env python3
"""Stage AVA2's level 100-125 maps and dungeon maps for the 203 server and the zh client
(metin2-server docs/FEATURE-LEVEL-120.md L2/L3).
Server (install_maps.py): mobs-server.tsv (AVA2-only monsters, stones, NPCs with zh names), group.txt /
group_group.txt blocks, the map directories and their map/index lines.
Client: the ava2maps pack = locale/zh/mob_proto with the new rows, every map / model / property file the zh
client lacks, locale/zh/atlasinfo.txt with the new maps, property/mt_extra_list.txt (read by
CPythonBackground::__CreateProperty) and locale/zh/mt_ava2maps.txt (race names and zone names for the
mt_ava2maps script). Usage: see build_zh_locale.build_ava2_maps and --help.
"""
import argparse,json,re,shutil,subprocess,sys
from collections import Counter
from pathlib import Path
HERE=Path(__file__).resolve().parent
REPO=HERE.parents[2]
sys.path.insert(0,str(REPO/'tools/epk_scan'))
import epk_scan
# Map directory -> (AVA2 server map index, zh zone name). None of the indexes is used on 203.
MAPS={'plechito_desert_map_01':(57,'法老沙漠'),
'metin2_map_elemental_04_rework':(37,'元素圣地'),
'metin2_map_eastplain_01':(129,'东间平原'),
'metin2_map_eastplain_02':(130,'西间荒原'),
'metin2_map_eastplain_03':(131,'南间深渊'),
'metin2_map_empirecastle':(132,'皇城'),
'metin2_map_dawnmist_dungeon_01':(210,'晨雾地下城'),
'metin2_map_n_flame_dragon':(212,'赤龙巢穴'),
'metin2_map_n_snow_dungeon_01':(352,'冰雪地下城'),
'defensawe_hydra':(355,'九头蛇船防')}
# The zh client already ships these maps (files and atlasinfo row).
CLIENT_HAS={'metin2_map_n_snow_dungeon_01'}
# AVA2 leaves these Town.txt files empty (players would land at the map's corner): the 10107 warp landing.
TOWN={'metin2_map_eastplain_01':b'133\t415\r\n'}
# defensawe_hydra (972800,153600 2x2) is 203's metin2_map_empirewar03; this corner is free on 203 and in
# the zh atlas. The shipdefense quest (L4) must shift its coordinates by the same delta.
RELOCATE={'defensawe_hydra':(3276800,0)}
# Server map files; stone2.txt is appended to stone.txt.
MAP_FILES=('Setting.txt','Town.txt','server_attr','regen.txt','npc.txt','boss.txt','stone.txt','dungeon.txt')
REGEN_FILES=('regen.txt','npc.txt','boss.txt','stone.txt','stone2.txt','dungeon.txt')
# Yohara (AVA2 levels 119-125): AVA2 gives them the plechito level 101 exp; rescale geometrically to the
# level 120 value of the plechito curve, bosses x10.
YOHARA=range(6686,6732)
def yohara_exp(level,rank):return round(83333*(117005/83333)**((level-101)/19)*(10 if rank=='BOSS' else 1))
# Rows of the Yohara NPCs that AVA2 wrote with one column out of place (EMPIRE holds the immune flags) are
# rebuilt from this ordinary NPC (vnum, name and folder kept).
NPC_TEMPLATE=20016
ON_CLICK_TALK='2'
# Mob model folders RaceManager searches.
MODEL_DIRS=('monster','monster2','npc','npc2')
TIMER_BOSSES=('nemere','hydra','meley','razador','jotun','devil')
# Files the closure follows (text) and the reference pattern (closure of AVA2 packs).
NAMES=re.compile(rb'[\w \-:./\\]+?\.(?:dds|tga|jpg|bmp|png|mde|mse|gr2|spt|msf|wav|mp3|mss|msa|msm|msenv|prb|prt|pre|prd|pra|sub|txt|atr|raw|wtr|obv)(?=["\s\x00]|$)',re.I)
TEXT=('.mse','.mde','.msm','.msa','.mss','.msenv','.prb','.prt','.pre','.prd','.pra','.sub','.txt','.msf','.spt')
EXTRA_PROPERTY_DIR='property/mt_ava2/'
def mob_enums(proto_reader):
src=proto_reader.read_text(encoding='latin1');src=src[src.index('arRank[]')-32:]
arr=lambda name:re.findall(r'"([^"]+)"',re.search(r'string\s+'+name+r'\[\]\s*=\s*\{(.*?)\};',src,re.S).group(1))
return {k:arr(v) for k,v in (('rank','arRank'),('type','arType'),('battle','arBattleType'),('size','arSize'),
('ai','arAIFlag'),('race','arRaceFlag'),('immune','arImmuneFlag'))}
def norm(path):return path.strip().strip('"').lower().replace('\\','/')
def number(text):
try:return float(text)
except ValueError:return 0.0
def names():
out={}
for line in (HERE/'names_zh.tsv').read_text().splitlines():
if line and not line.startswith('#'):v,n=line.split('\t');out[int(v)]=n
return out
class Pack:
"""The client's effective pack files (pack/Index order, first registered pack wins), without `skip`."""
def __init__(self,client,skip):
_,self.keys,order,packs,_=epk_scan.load(client,epk_scan.refroot.reference_root())
self.index={}
for name,_ in order:
p=packs.get(name)
if name==skip or not p or p['missing']:continue
for e in p['entries']:self.index.setdefault(norm(e['name']),(p,e))
def __contains__(self,path):return path in self.index
def get(self,path):
p,e=self.index[path]
with open(p['epk'],'rb') as f:
f.seek(e['pos']);stored=f.read(e['size'])
if e['type']==0:return stored
f.seek(e['pos']);data=f.read(epk_scan.lz_object_len(stored[:16]))
return epk_scan.lz_object(data,self.keys['s_adwEterPackSecurityKey'] if e['type']==2 else None)
def ava_index(pack_maker):
"""ArchivedPath (lowercase) -> source file, first pack in AVA2 pack/Index wins.
CEterFileDict is a multimap and GetItem returns the earliest registration,
so a duplicate path resolves to the pack listed first in Index (e.g. Maps
before Patch_dungeon_meley), not to the alphabetically first manifest."""
xmls={x.name[:-len('_create.xml')].lower():x for x in pack_maker.glob('*_create.xml')}
order=[l.strip().lower() for l in (pack_maker.parent/'pack/Index').read_text(encoding='latin1').splitlines() if l.strip()]
order=[n for n in order if n in xmls]+sorted(set(xmls)-set(order))
index={}
for name in order:
for archived,source in re.findall(r'ArchivedPath="([^"]+)"><!\[CDATA\[([^\]]+)\]\]>',xmls[name].read_text(encoding='latin1')):
index.setdefault(archived.lower().replace('\\','/'),pack_maker.parent/source)
return index
def proto_rows(path):
rows={}
for line in path.read_bytes().splitlines():
cols=[c.strip() for c in line.decode('latin1').split('\t')]
if cols[0].isdigit():rows[int(cols[0])]=cols
return rows
def server_row(cols,zh,E,template):
"""AVA2 db/mob_proto.txt columns -> 203 server row (str columns, zh name)."""
c=list(cols)+['0']*(71-len(cols))
if not re.fullmatch(r'-?\d*',c[11]): # shifted NPC row
c=list(template);c[0],c[12]=cols[0],cols[12];c[13]=ON_CLICK_TALK
c[1]=zh
for i,k in ((7,'ai'),(9,'race'),(10,'immune')):
c[i]=','.join(t for t in (x.strip() for x in c[i].split(',')) if t in E[k])
try:float(c[51])
except ValueError:c[51]=c[51].split('.')[0] # AVA2 "2.000.000"
if int(c[0]) in YOHARA and c[3]=='MONSTER':c[25]=str(yohara_exp(int(c[5]),c[2]))
return c[:71]
def client_row(c,E):
"""Server row -> mob_proto_patch fields (tests/port/mob_proto_patch.cpp order)."""
idx=lambda k,v:E[k].index(v) if v in E[k] else 0
bits=lambda k,v:sum(1<<E[k].index(t) for t in v.split(',') if t in E[k])
n=lambda i:number(c[i])
f=[int(c[0]),idx('type',c[3]),idx('rank',c[2]),idx('battle',c[4]),n(5),E['size'].index(c[6])+1 if c[6] in E['size'] else 0,
n(23),n(24),n(25),n(20),n(21),n(22),n(26),bits('ai',c[7]),bits('race',c[9]),bits('immune',c[10]),
n(14),n(15),n(16),n(17),n(18),n(19),n(27),n(28),n(29),n(30),n(31)]
f+=[n(i) for i in range(34,40)]+[n(i) for i in range(40,51)]
f+=[n(33),n(32),n(8),n(13),n(11),n(51),n(52),n(53),n(54),n(55)]
for k in range(5):f+=[n(57+2*k),n(56+2*k)]
f+=[n(i) for i in range(66,71)]
assert len(f)==69
text=' '.join(('%g'%x if isinstance(x,float) and x!=int(x) else str(int(x))) for x in f)
# Warps carry "<place> <x> <y>" for the server; the client shows the place only.
name=c[1].split(' ')[0] if c[3]=='WARP' else c[1]
return (text+'\t'+c[12]+'\t'+name).encode('gbk')
def blocks(raw,member):
"""group.txt / group_group.txt -> {vnum: (block bytes, [member vnums])}; member(tokens) -> vnum or None."""
out={};lines=raw.replace(b'\r\n',b'\n').split(b'\n');i=0
while i<len(lines):
t=lines[i].split()
if t and t[0].lower()==b'group':
j=i
while j<len(lines) and not lines[j].strip().startswith(b'}'):j+=1
body=lines[i:j+1];vnum=None;members=[]
for l in body[1:]:
t=l.split()
if len(t)>=2 and t[0].lower()==b'vnum':vnum=int(t[1])
elif t and t[0]!=b'{' and t[0]!=b'}':
m=member(t)
if m is not None:members.append(m)
if vnum is not None:out.setdefault(vnum,(b'\r\n'.join(l.rstrip() for l in body),members))
i=j
i+=1
return out
def regen_lines(raw):
"""Regen file -> [(line, kind, vnum)] (kind m/g/r..., None for blank/unknown lines)."""
out=[]
for line in raw.replace(b'\r\n',b'\n').split(b'\n'):
t=line.split()
if len(t)>=10 and t[-1].isdigit() and t[0][:1].isalpha():out.append((line.rstrip(),t[0][:1].decode().lower(),int(t[-1])))
elif line.strip():out.append((line.rstrip(),None,None))
return out
def prepare(ava,proto_reader,client,output,mob_tool,gr2_tool,packer):
srv=ava/'2. Backup SF+SRC and SQL/home/srv1';pack_maker=ava/'1. Client DEV/pack_maker'
loc=srv/'share/locale/germany'
if not (loc/'map').is_dir() or not (srv/'db/mob_proto.txt').is_file():
raise SystemExit('AVA2 maps need the extracted server tree (AVA2/TEST/2. Backup SF+SRC and SQL/home/srv1)')
E=mob_enums(proto_reader);zh=names();AP=proto_rows(srv/'db/mob_proto.txt')
assert zh.keys()<=AP.keys(),sorted(zh.keys()-AP.keys())
report={'warnings':[]};warn=report['warnings'].append
output.mkdir(parents=True,exist_ok=True)
stage=output/'server'
if stage.exists():shutil.rmtree(stage)
(stage/'map').mkdir(parents=True)
# ---------------------------------------------------------------- server: mob rows
template=AP[NPC_TEMPLATE]
srows={v:server_row(AP[v],zh[v],E,template) for v in sorted(zh)}
(stage/'mobs-server.tsv').write_bytes(b''.join('\t'.join(r).encode('gbk')+b'\n' for r in srows.values()))
report['mobs']=len(srows)
# ---------------------------------------------------------------- server: map dirs + groups
G=blocks((loc/'group.txt').read_bytes(),lambda t:int(t[-1]) if t[-1].isdigit() and (t[0].isdigit() or t[0].lower()==b'leader') else None)
GG=blocks((loc/'group_group.txt').read_bytes(),lambda t:int(t[1]) if t[0].isdigit() and t[1].isdigit() else None)
groups=set();ggroups=set();mobs=set()
def add_mob(v):
if v in mobs:return
mobs.add(v);r=srows.get(v) or AP.get(v)
if r is None:return
if r[3]=='STONE':
lo,hi=sorted((int(number(r[27])),int(number(r[28]))))
if hi-lo<50:
for g in range(lo,hi+1):
if g in G:add_group(g)
if number(r[33]):add_mob(int(number(r[33])))
def add_group(g):
if g in groups:return
groups.add(g)
for m in G[g][1]:add_mob(m)
index_lines=[];origin={}
for m,(index,_) in MAPS.items():
src=loc/'map'/m;dst=stage/'map'/m;dst.mkdir()
dropped=Counter()
for f in MAP_FILES:
raw=(src/f).read_bytes() if (src/f).is_file() else b''
if f=='stone.txt' and (src/'stone2.txt').is_file():raw=raw.rstrip(b'\r\n')+b'\r\n'+(src/'stone2.txt').read_bytes()
if f=='Town.txt' and m in TOWN:raw=TOWN[m]
if f=='Setting.txt' and m in RELOCATE:
raw=re.sub(rb'BasePosition\s+\d+\s+\d+',b'BasePosition\t%d\t%d'%RELOCATE[m],raw);assert b'\t%d\t'%RELOCATE[m][0] in raw
if f=='Setting.txt':origin[m]=tuple(map(int,re.search(rb'BasePosition\s+(\d+)\s+(\d+)',raw).groups()))
if f in REGEN_FILES:
kept=[]
for line,kind,v in regen_lines(raw):
if kind=='g' and v not in G or kind=='r' and v not in GG:dropped[(kind,v)]+=1;continue
if kind=='g':add_group(v)
elif kind=='r':
ggroups.add(v)
for g in GG[v][1]:
if g in G:add_group(g)
elif kind:add_mob(v)
kept.append(line)
raw=b'\r\n'.join(kept)+(b'\r\n' if kept else b'')
if f=='Town.txt' and not raw.strip() and m not in TOWN:warn('%s: empty Town.txt (map corner)'%m)
if f in ('Setting.txt','server_attr') and not raw:raise SystemExit('%s/%s missing'%(m,f))
(dst/f).write_bytes(raw)
for (kind,v),n in sorted(dropped.items()):warn('%s: dropped %d regen lines of missing %s %d'%(m,n,'group' if kind=='g' else 'groupgroup',v))
index_lines.append(b'%d %s'%(index,m.encode()))
(stage/'index.txt').write_bytes(b'\n'.join(index_lines)+b'\n')
(stage/'group.txt').write_bytes(b''.join(G[g][0]+b'\r\n' for g in sorted(groups)))
(stage/'group_group.txt').write_bytes(b''.join(GG[g][0]+b'\r\n' for g in sorted(ggroups)))
# Every regen / group member must be a 203 mob or one of ours; install_maps.py checks the rest on the server.
(stage/'mob_refs.txt').write_text(''.join('%d\n'%v for v in sorted(mobs)))
# Server motion data (data/monster/<folder>: motlist.txt + .msa timing); install_maps.py adds only folders 203 lacks.
# The core opens the folder exactly as spelled (FreeBSD); mob_proto spellings that differ only in case
# resolve to the one real folder here, so each is copied once under its on-disk name.
motion=srv/'share/data/monster';real={d.name.lower():d.name for d in motion.iterdir() if d.is_dir()};folders=set()
for v in mobs|set(srows):
r=srows.get(v) or AP.get(v)
if r and r[12].lower() in real:folders.add(real[r[12].lower()])
for f in sorted(folders):
shutil.copytree(motion/f,stage/'data/monster'/f,ignore=lambda d,names:[n for n in names if n.lower().endswith(('.dds','.gr2','.tga','.jpg'))])
report['motion_folders']=len(folders)
report.update(groups=len(groups),group_groups=len(ggroups),mob_refs=len(mobs))
# ---------------------------------------------------------------- client
have=Pack(client,'ava2maps');files=ava_index(pack_maker)
assets=output/'assets'
if assets.exists():shutil.rmtree(assets)
target=assets/'locale/zh';target.mkdir(parents=True)
crows=[client_row(srows[v],E) for v in sorted(srows)]
(output/'mobs-client.tsv').write_bytes(b'\n'.join(crows)+b'\n')
(output/'base_mob_proto').write_bytes(have.get('locale/zh/mob_proto'))
subprocess.run([str(mob_tool),str(output/'base_mob_proto'),str(output/'mobs-client.tsv'),str(target/'mob_proto')],check=True)
# atlasinfo: the locale file the client reads first (CPythonBackground::Initialize), from the root one.
base=have.get('locale/zh/atlasinfo.txt') if 'locale/zh/atlasinfo.txt' in have else have.get('atlasinfo.txt')
atlas=[l for l in base.replace(b'\r\n',b'\n').split(b'\n') if l.strip()]
atlas_names={l.split()[0] for l in atlas}
for m in MAPS:
if m in CLIENT_HAS:continue
setting=files[m+'/setting.txt'].read_bytes()
# The server Setting is authoritative: AVA2's Maps pack shadows Patch_dungeon_meley's
# flame_dragon setting.txt with BasePosition 0 0, which would misplace the client terrain.
bx,by=origin[m]
w,h=map(int,re.search(rb'MapSize\s+(\d+)\s+(\d+)',setting).groups())
if m.encode() in atlas_names:raise SystemExit('zh atlasinfo already lists %s'%m)
atlas.append(b'%s\t%d\t%d\t%d\t%d'%(m.encode(),bx,by,w,h))
(target/'atlasinfo.txt').write_bytes(b'\r\n'.join(atlas)+b'\r\n')
# Properties: AVA2-only CRCs placed on the new maps.
def crc_of(raw):
t=raw.split(b'\n',2)
return int(t[1].strip()) if raw[:4]==b'YPRT' and len(t)>1 and t[1].strip().isdigit() else None
zh_crc={crc_of(have.get(p)) for p in have.index if p.startswith('property/') and p!='property/reserve'}
ava_crc={}
for p in files:
if p.startswith('property/') and p!='property/reserve':
c=crc_of(files[p].read_bytes())
if c is not None:ava_crc.setdefault(c,p)
placed=set()
for m in MAPS:
if m in CLIENT_HAS:continue
for p in files:
if p.startswith(m+'/') and p.endswith(('/areadata.txt','/areaambiencedata.txt')):
t=files[p].read_bytes().decode('latin1').split('\n')
placed|={int(t[i+2].strip()) for i,l in enumerate(t) if l.startswith('Start Object')}
extra=[];missing_props=[]
for c in sorted(placed-zh_crc):
if c not in ava_crc:missing_props.append(c);continue
p=ava_crc[c];dest=p if p not in have else EXTRA_PROPERTY_DIR+p[len('property/'):]
extra.append((p,dest))
report.update(properties=len(extra),properties_missing=missing_props)
# Mob models: AVA2 npclist rows of the races the zh npclist lacks.
def npclist(raw):
race={};alias={}
for l in raw.decode('latin1').splitlines():
t=l.split()
if len(t)>=2 and t[0].isdigit():
if t[0]=='0' and len(t)>=3:alias[t[1].lower()]=norm(t[2])
elif t[0]!='0':race[int(t[0])]=norm(t[1])
return race,alias
AR,AA=npclist(files['npclist.txt'].read_bytes());ZR,_=npclist(have.get('npclist.txt'))
races=[];srcs={};model_seeds=[]
for v in sorted(zh):
if v in ZR:continue
name=AR.get(v)
if not name:warn('race %d: no AVA2 npclist row'%v);continue
src=AA.get(name,name);races.append((v,name))
if src!=name:srcs[name]=src
found=[p for d in MODEL_DIRS for p in files if p.startswith('d:/ymir work/%s/%s/'%(d,src))]
if not found:warn('race %d: no AVA2 model folder %s'%(v,src))
model_seeds+=found
# Closure over the map, atlas, property and model files.
seeds=[p for m in MAPS if m not in CLIENT_HAS for p in files if p.startswith(m+'/')]
seeds+=[p for m in MAPS if m not in CLIENT_HAS for p in ('d:/ymir work/ui/atlas/%s/atlas.sub'%m,) if p in files]
seeds+=[p for p,_ in extra]+model_seeds
# Dungeon timer images (DungeonTimerScript.inc, the AVA2 dungeons of ../ava2-dungeons) and their timer.tga.
seeds+=['d:/ymir work/ui/game/dungeontimer/%s_%s.sub'%(b,k) for b in TIMER_BOSSES for k in ('back','timer')]
need=set();misses=Counter();gr2=[]
def refs(a):
out=[]
if a.endswith(TEXT) and not a.endswith('/motlist.txt'):
for n in NAMES.findall(files[a].read_bytes()):
n=norm(n.decode('latin1'))
if not n:continue
if n.startswith('d:/') or n in files or n in have:out.append(n)
elif a.endswith('.sub'):out.append('d:/ymir work/ui/'+n)
elif n.endswith('.msenv'):out.append('d:/ymir work/environment/'+n.rsplit('/',1)[-1])
else:out.append(a.rsplit('/',1)[0]+'/'+n)
if a.endswith('.gr2'):gr2.append(a)
return out
def visit(q,frm):
if q in have or q in need:return
if q not in files:
same=frm.rsplit('/',1)[0]+'/'+q.rsplit('/',1)[-1]
if same!=q and (same in have or same in files):visit(same,frm)
else:misses[q]+=1
return
need.add(q)
for r in refs(q):visit(r,q)
for s in seeds:visit(s,'seed')
done=set()
while len(done)<len(gr2):
batch=[a for a in gr2 if a not in done];done|=set(batch)
back={str(files[a]):a for a in batch}
out=subprocess.run([str(gr2_tool)],input='\n'.join(back)+'\n',capture_output=True,text=True,check=True).stdout
for l in out.splitlines():
t=l.split('\t')
if t[0]=='TEX':visit(norm(t[2]),back[t[1]])
elif t[0]=='ERR':warn('gr2 %s: %s'%(back[t[1]],t[2]))
property_dest=dict(extra)
for q in sorted(need):
dest=assets/property_dest.get(q,q);dest.parent.mkdir(parents=True,exist_ok=True)
raw=files[q].read_bytes()
if q.endswith('/setting.txt') and q.split('/')[0] in origin:
raw=re.sub(rb'BasePosition\s+\d+\s+\d+',b'BasePosition\t%d\t%d'%origin[q.split('/')[0]],raw)
dest.write_bytes(raw)
(assets/'property').mkdir(exist_ok=True)
(assets/'property/mt_extra_list.txt').write_bytes(b''.join(d.encode()+b'\r\n' for _,d in extra))
report.update(files=len(need),bytes=sum(files[q].stat().st_size for q in need),misses=sorted(misses))
# mt_ava2maps data (gbk): race names, source folders, zone names, server map indexes.
lines=['race\t%d\t%s'%r for r in races]+['src\t%s\t%s'%kv for kv in sorted(srcs.items())]
lines+=['zone\t%s\t%s'%(m,z) for m,(_,z) in MAPS.items()]+['map\t%d\t%s'%(i,m) for m,(i,_) in MAPS.items()]
(target/'mt_ava2maps.txt').write_bytes('\n'.join(lines).encode('gbk')+b'\n')
report['races']=len(races)
subprocess.run([str(packer),str(output/'ava2maps'),str(assets),''],check=True)
(output/'maps.json').write_text(json.dumps(report,indent=1,ensure_ascii=False)+'\n')
return report
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
for a in ('ava','proto_reader','client','output','mob_tool','gr2_tool','packer'):p.add_argument(a,type=Path)
a=p.parse_args()
r=prepare(a.ava,a.proto_reader,a.client,a.output,a.mob_tool.resolve(),a.gr2_tool.resolve(),a.packer.resolve())
print(json.dumps({k:(len(v) if isinstance(v,list) and k not in ('warnings',) else v) for k,v in r.items()},indent=1,ensure_ascii=False))
+135
View File
@@ -0,0 +1,135 @@
# AVA2 map/dungeon monsters, stones and NPCs that 203 lacks (vnum<TAB>zh name). Warp names keep AVA2's "<place> <x> <y>" (server sscanf).
4062 诅咒之书
4063 黄金僵尸
4064 宝石魔像
4065 陷阱宝箱
4066 金币守护者
4067 黄金狮身人面像
4111 沙漠蜻蜓
4112 沙丘甲虫
4113 毒甲虫
4114 石龙
4115 蜥蜴斥候
4116 蜥蜴斗士
4117 蜥蜴战士
4118 龙人圣骑士
4119 安度尔战士
4120 安度尔萨满
4121 安度尔刺客
4122 那伽斥候
4123 那伽骑兵
4124 蛇人斗士
4125 蛇人术士
4126 蛇人战士
4127 岩石魔像
4128 远古魔像
4129 木乃伊
4130 狂暴木乃伊
4131 法老守卫
4132 法老祭司
4133 法老
4134 奥西里斯仆从
4135 阿努比斯仆从
6222 熔岩雪人
6223 熔岩魔像
6224 熔岩虫
6225 岩浆魔像
6226 炽热水晶
6227 熔岩飞龙
6228 龙之守卫伊达尔
6230 龙之雕像
6231 龙后美莉
6401 恩泰战士
6402 恩泰斗士
6406 恩泰毁灭者
6410 强壮的恩泰战士
6411 强壮的恩泰斗士
6686 金兵
6687 枪兵
6688 矛兵
6689 弓兵
6690 前线术士
6693 金兵
6694 枪兵
6695 矛兵
6696 弓兵
6697 前线术士
6699 宝王
6700 地狱猎犬
6701 巨魔士兵
6702 巨魔战士
6703 巨魔弓手
6704 巨魔萨满
6710 怨灵
6711 地狱猎犬
6712 巨魔士兵
6713 巨魔战士
6714 巨魔弓手
6715 巨魔萨满
6716 纳塔南
6717 阿尔戈斯
6718 米尔族步兵
6719 米尔族劳工
6720 米尔族魔像
6721 米尔族战士
6722 米尔族术士
6723 米尔族老兵
6724 米尔族首领
6730 米尔族老兵
6731 米尔族首领
6801 桅杆
6802 河童首领
6803 河童
6804 河童
6805 河童
6806 人鱼蛇兵
6807 人鱼毒蛇
6808 小九头蛇
6809 人鱼海妖
6810 九头蛇
6811 九头蛇
6812 九头蛇
8058 寒冰之石
8059 树木之石
8061 森林之石
8062 警戒之石
8063 珍爱之石
8067 警戒之石
8469 沙漠之石
8470 荆棘之石
8471 木乃伊之石
8625 巨魔前哨
8626 米尔族前哨
8627 米尔族前哨
9015 船舵
9016 力场
9018 九头蛇宝箱
9566 变异蜜蜂
9571 变异蛇
9577 变异蝎子
9578 烈焰龙
10107 东间平原 10629 4767
10127 东间平原 10551 4881
10129 南间深渊 12780 4411
10130 西间荒原 12144 5555
20397 冰狮
20398 寒冰魔方
20399 北龙之柱
20409 森林守卫
20410 森林密探
20411 森林斥候
20440 龙之门
20441 守望者多纳尔
20442 龙之宝藏
20444 龙蛋
20480 商会管理员
20800 伤员
20802 雄原巡守
20803 雄原守卫
20810 柴吉拉布
20812 安格穆尔提督
20823 池大师
20831 雄原指挥官
20836 戟兵
20850 神秘祭坛
60003 西奥瓦丹
Can't render this file because it contains an unexpected character in line 1 and column 104.
+58
View File
@@ -0,0 +1,58 @@
#!/bin/sh
# Give the sbtest channel5 core its own locale and data dir so install_maps.py never touches the live ones.
# sbtest/share/locale/newcibn = symlinks to every live newcibn entry, except real copies of
# group.txt, group_group.txt, mob_drop_item.txt and a real map/ dir (symlinks to each live map dir + a copied index).
# sbtest/share/data = symlinks to the live data entries, except a real monster/ dir (symlinks per live folder).
# Idempotent: existing entries are kept, so a rerun only adds what the live locale gained since.
# Run on 203: sh sbtest_locale.sh (restart channel5 afterwards)
set -e
LIVE=/usr/metin2/server/share/locale
SB=/usr/metin2/server/sbtest/share/locale
CORE=/usr/metin2/server/channel5/first
LIVEMAP=$(cd "$LIVE/newcibn/map" && pwd -P)
LIVEDATA=/usr/metin2/server/share/data
SBDATA=/usr/metin2/server/sbtest/share/data
mkdir -p "$SB/newcibn/map"
[ -e "$SB/english" ] || ln -s "$LIVE/english" "$SB/english"
for e in "$LIVE"/newcibn/*; do
n=${e##*/}
case $n in map) continue ;; esac
[ -e "$SB/newcibn/$n" ] || [ -L "$SB/newcibn/$n" ] && continue
case $n in
group.txt|group_group.txt) cp -p "$e" "$SB/newcibn/$n" ;;
*) ln -s "$e" "$SB/newcibn/$n" ;;
esac
done
# entries made into copies after the farm was first built
for n in group.txt group_group.txt mob_drop_item.txt; do
[ -L "$SB/newcibn/$n" ] && rm "$SB/newcibn/$n" && cp -p "$LIVE/newcibn/$n" "$SB/newcibn/$n" && echo "$n copied"
done
for e in "$LIVEMAP"/*; do
n=${e##*/}
[ -e "$SB/newcibn/map/$n" ] || [ -L "$SB/newcibn/map/$n" ] && continue
case $n in
index) cp -p "$e" "$SB/newcibn/map/index" ;;
*) ln -s "$e" "$SB/newcibn/map/$n" ;;
esac
done
mkdir -p "$SBDATA/monster"
for e in "$LIVEDATA"/*; do
n=${e##*/}
[ "$n" = monster ] || [ -e "$SBDATA/$n" ] || [ -L "$SBDATA/$n" ] || ln -s "$e" "$SBDATA/$n"
done
for e in "$LIVEDATA"/monster/*; do
[ -e "$SBDATA/monster/${e##*/}" ] || [ -L "$SBDATA/monster/${e##*/}" ] || ln -s "$e" "$SBDATA/monster/${e##*/}"
done
repoint() # <link> <target>
{
[ "$(readlink "$1")" = "$2" ] && return 0
echo "$1 was $(readlink "$1")"
rm "$1" && ln -s "$2" "$1"
}
repoint "$CORE/locale" "$SB"
repoint "$CORE/data" "$SBDATA"
echo "channel5 locale -> $(readlink "$CORE/locale"); $(ls "$SB/newcibn" | wc -l) entries, $(ls "$SB/newcibn/map" | wc -l) map entries"
echo "channel5 data -> $(readlink "$CORE/data"); $(ls "$SBDATA/monster" | wc -l) monster folders"
+5
View File
@@ -0,0 +1,5 @@
-- 105-119 now need up to 4.2e9 exp (game/src/constants.cpp exp_table_common), above the signed INT limit
-- of 2147483647. The db writes "exp = %u" and MySQL (sql_mode without STRICT) silently clamps, so make the
-- columns unsigned. Run against the player schema (player on live, player_sb on the sbtest cluster).
ALTER TABLE player MODIFY exp INT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE player_deleted MODIFY exp INT UNSIGNED NOT NULL DEFAULT 0;
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Level cap 120 on the sbtest cluster (../sbtest/README.md): unsigned exp columns in player_sb and
# MAX_LEVEL 120 in channel5's CONFIG (CONFIG.livedb stays at 105, so rollback.sh brings back 105).
# The game binary must already carry the new exp table (constants.cpp).
# Usage (on the server): sh install_sbtest.sh <dir holding exp_unsigned.sql>
set -eu
STAGE=$(cd "$1" && pwd)
C5=/usr/metin2/server/channel5/first
grep -q '^DB_PORT: 15040' $C5/CONFIG || { echo "channel5 is not on the sbtest db" >&2; exit 1; }
mysql -uroot player_sb < $STAGE/exp_unsigned.sql
mysql -uroot -N -e "select table_name,column_type from information_schema.columns where table_schema='player_sb' and column_name='exp' and table_name like 'player%'"
sed -i '' 's/^MAX_LEVEL: .*/MAX_LEVEL: 120/' $C5/CONFIG
grep '^MAX_LEVEL' $C5/CONFIG
+3
View File
@@ -18,6 +18,9 @@ done
cp $C5/CONFIG.livedb $C5/CONFIG cp $C5/CONFIG.livedb $C5/CONFIG
[ -e $C5/game.livedb ] && { rm -f $C5/game; mv $C5/game.livedb $C5/game; } [ -e $C5/game.livedb ] && { rm -f $C5/game; mv $C5/game.livedb $C5/game; }
# ../ava2-maps/sbtest_locale.sh points channel5 at the sbtest locale + data; the live db lacks their mobs
[ "$(readlink $C5/locale)" = ../../share/locale ] || { rm -f $C5/locale; ln -s ../../share/locale $C5/locale; }
[ "$(readlink $C5/data)" = ../../share/data ] || { rm -f $C5/data; ln -s ../../share/data $C5/data; }
daemon -f sh -c "cd $C5 && exec ./game > stdout 2>&1"; sleep 12 daemon -f sh -c "cd $C5 && exec ./game > stdout 2>&1"; sleep 12
grep -E '^DB_PORT' $C5/CONFIG; ls -l $C5/game grep -E '^DB_PORT' $C5/CONFIG; ls -l $C5/game
sockstat -l | grep -E ':(13040) ' sockstat -l | grep -E ':(13040) '