diff --git a/docs/AVA2-PARITY-PLAN.md b/docs/AVA2-PARITY-PLAN.md new file mode 100644 index 00000000..a9b77f31 --- /dev/null +++ b/docs/AVA2-PARITY-PLAN.md @@ -0,0 +1,132 @@ +# AVA2 客户端对齐计划 + +日期:2026-10-16。用户要求把现有实现改成按 AVA2 客户端的方式实现。这改变了 `AVA2-FEATURE-MIGRATION-PLAN.md` 的原则:那份计划只把 AVA2 当参考,用聊天命令(`/mt_*`)和自建窗口适配当前服务器。 + +本文是差异清单和计划,不代表功能已实现或已授权部署。 + +## 1. 对齐的含义 + +对每个系统都使用 AVA2 自己的实现,参考源码如下: + +| 层 | AVA2 来源 | 当前做法 | 对齐后 | +|---|---|---|---| +| 界面 | `pack_maker/uiscript/uiscript/*.py` + `pack_maker/root/ui*.py` | `ScriptLib/*Script.inc` 里自建窗口 | 原样载入 AVA2 uiscript 和 ui*.py,只补当前客户端缺的接口(沿用 m2 UI 窗口模板) | +| Python 模块 | `3. Source BIN/Client/UserInterface/Python*.cpp`(PythonSwitchbot、PythonBattlePass、PythonWiki、PythonDropItem、PythonDungeonInfo…) | 无,状态都在脚本里 | 移植对应 C++ 模块,模块名和接口与 AVA2 相同 | +| 协议 | AVA2 `Packet.h` 的功能包头 | `/mt_ 1 …` 聊天命令 | 改用 AVA2 功能包头和包结构;基础包仍是 40250 | +| 服务端 | `2. Backup SF+SRC and SQL/home/Ava2_src/Srcs/Server` | 自写 `port_*.h` | 按 AVA2 服务端源码移植逻辑 | +| 数据 | AVA2 配置与 SQL | 自定义 TSV/表 | 按 AVA2 的 SQL 读写还原表结构,编写迁移脚本 | + +AVA2 功能包头号在当前服务端基本空闲,可以直接沿用: +- CG 侧空闲:57、58、143、171、213、215、216、220、221、230、235。 +- GC 侧空闲:66、171、214、216、217、220、224、230。 +- 已经占用且号码与 AVA2 相同:CG 211 / GC 215(肩带)、110(副本)、GC 121(频道)。 + +**不在范围内**(除非另外决定):AVA2 的底层结构,包括 8 个 socket、15 条属性、64 位金币、250 级、征服者等级、角色槽数,以及 40250 基础包号和加密方式。这些会改动物品、角色、DB 和每一个基础包,相当于换一套底座(见 `AVA2-40250-COMPARISON.md` §3–§5、§11)。 + +## 2. 差异清单 + +### 2.1 已上线 203 的系统 + +| 系统 | AVA2 | 当前实现 | 主要差异 | +|---|---|---|---| +| 自动洗练 | `uiswitchbot.py` + `switcher.py`,`PythonSwitchbot`,CG/GC 171,`new_switchbot.cpp`;独立 SWITCHBOT 窗口,5 个物品槽 + 1 个道具槽,0.1 秒/次,换线后通过 P2P 转移继续洗 | `/mt_switchbot`,物品留在背包,一次只洗 1 件,0.25 秒/次,每次调用原 `UseItem`;换线或下线即停止 | 窗口、物品存放(新增窗口类型 = 物品位置枚举和 DB)、协议、速度、换线续洗。**2026-10-16 已在 feature/ava2-unlock 按 AVA2 实现,未部署**(`docs/AVA2-SWITCHBOT.md`、服务端 `FEATURE-SWITCHBOT.md`) | +| 属性锁定 | `ENABLE_LOCK_ATTR`:把 50348/50349 拖到装备上,选择属性;锁定信息存在属性数组第 7、8 位;物品提示里显示锁定 | 独立表 `mt_item_attr_lock`;入口是洗练窗口里的 5 个锁定按钮;main 的 `2222885` 已加入 50348/50349 的消耗 | 入口和提示改成 AVA2 的方式;存储继续用独立表(7 条属性的结构放不下)。洗练窗口里的锁定按钮和锁定命令已删,50348/50349 走服务端 UseItemEx;AVA2 选槽位界面和提示未做 | +| 批量开箱 | `/chest_drop`,Ctrl + 右键弹出滑块,Ctrl + Z + 右键开整叠;`AutoGiveItemChest`,单次最多 1000 | `/mt_chest`,固定 1/10/50/全部,单次最多 200,逐个调用原 `UseItem` | 窗口、按键、命令、单次上限、发奖路径 | +| 批量拾取 | CG 235 `ITEMS_PICKUP`;70002 自动拾取状态 | `/mt_pickup`,自建 8 类分类窗口,只在按 Z 时触发 | 包、自动拾取状态、分类方式 | +| 世界 Boss | `uitrack.py`(世界 Boss + 副本两页) | `mt_boss` 自建窗口;main 已加入传送 | 窗口改为 uitrack,补上副本页 | +| 战令 | `uiBattlePassEx` + CG/GC 230,`battlepass.cpp` / `questlua_battlepass`,任务类型以 AVA2 为准;门票 25150–25161 | TSV 赛季 + 自建窗口;main 已加入门票激活 | 窗口、包、任务类型、表结构 | +| VIP 卡 | 待查 AVA2 是否有对应实现 | 自建 | 先确认 AVA2 有没有对应实现 | +| 生物学家 | — | 2026-10-14 已按 AVA2 实现 | 已对齐 | + +### 2.2 已实现、未上线的系统(main) + +| 系统 | AVA2 | 当前实现 | 主要差异 | +|---|---|---|---| +| 百科 | `uiWiki` + `PythonWiki`(本地资料) | `mt_wiki` 自建窗口 + 只读查询协议 | 窗口与模块整体替换 | +| 掉落查询 | `uitarget` InfoBoard、`PythonDropItem`、CG 215 / GC 220 | `/mt_features REQUEST mob…` | 包与目标栏入口 | +| 宝箱预览 | `uiChestDropInfo` + GC 66 | 查询协议 | 窗口与包 | +| 角色详细属性 | `uicharacterdetails.py` | 自建面板 + 查询 | 窗口 | +| 副本信息 | `uiDungeonInfo` + `uiDungeonTimer`、CG 213 / GC 217、`dungeon_info`,含排名和传送 | 只有龙穴和周任务 | 副本范围、排名、计时、包 | +| 活动日历 | `uiEventCalendarNew` + CG 220 / GC 214、216,`char_event_calendar` | 只支持月光宝箱和圣诞袜两种活动 | 活动类型、窗口、GM 管理包 | +| 显示开关 | 包括摆摊、宠物、坐骑的显示范围 | 没有这三项 | 补齐 | +| 换线 | 服务端把角色传送到目标频道(GC 121) | 客户端走 `/logout` 再重新登录 | AVA2 服务端源码在本机,可以移植服务端换线 | +| 模型预览 | `uiRenderTarget` | 已按 AVA2 实现(Vulkan) | 基本已对齐 | + +### 2.3 `feature/ava2-unlock` P1–P8 + +| 系统 | 与 AVA2 的差异 | +|---|---| +| 肩带 | 窗口已用 AVA2 的 uisash 和 uiscript;入口放在 NPC 20016 的任务里,AVA2 是 NPC 60003 | +| 坐骑时装 / 外观 | 基本一致;缺坐骑显示范围 | +| 时装强化石 | 武器时装、肩带外观、特效槽三类强化石仍锁着,因为这三个系统还没移植 | +| 护符 | 53996/53997 改成了护符道具,AVA2 里是通用洗练/加持道具;没有元素目标包(目标血条上的元素图标);没有 `uielementchange` / `uielementspelladd`;加入了冰元素,AVA2 没有 | +| 新戒指 | 没有 `item_attr_rare_rings` | +| 龙甲、守护武器 | 要求等级 115–120,203 上限 105 级,没人能穿 | + +### 2.4 尚未开始 + +- P9 宠物(`uiPetSystemNew`、`New_PetSystem`) +- P10 技能书 50569–50575 +- P11 第 6/7 条属性(`uiAttr67Add`、72319/72320) +- 其他 AVA2 系统,只列出不排期:离线商店、商店搜索、特殊背包/仓库、宝石、卡牌、任务、十二生肖、元素技能、帝国战争。 + +## 3. 计划 + +每一步都做到:两端各自提交,并附测试、macOS 联机记录和 Android 真机记录。部署 203 每次单独批准。 + +### 阶段 0:准备(先做) + +1. 在 203 开发目录完整编译合并后的 `feature/ava2-unlock`(server `c6813cd`),并编译客户端(macOS + Android),确认合并没问题。 +2. 为每个系统列出 AVA2 的追踪清单:入口、宏、uiscript/ui*.py、Python 模块方法、包结构、服务端处理、SQL。确认实际生效的那一版(old / ex / copia 等多版本并存)。 +3. 建立通用加载方式:AVA2 uiscript 和 ui*.py 原样放进资源包,用 `interfacemodule` 的方式接入;当前客户端缺的 `app.ENABLE_*` 宏、常量和方法统一补在一个地方。 + +### 阶段 1:已上线系统改成 AVA2 实现 + +改动玩家正在用的系统,旧版和新版需要同时切换,并有回滚方案。 + +1. 自动洗练(已完成代码,待联机测试和部署)+ 属性锁定(界面未做):SWITCHBOT 窗口类型、CG/GC 171、`new_switchbot` 和 `PythonSwitchbot`、`uiswitchbot`;锁定改成拖 50348/50349 并在物品提示里显示,存储继续用独立表。 +2. 批量开箱:`/chest_drop`、滑块、Ctrl + Z、`AutoGiveItemChest`。 +3. 批量拾取:CG 235、70002 自动拾取。 +4. 世界 Boss / 副本追踪:uitrack。 +5. 战令:`uiBattlePassEx`、CG/GC 230、AVA2 任务类型和表结构;需要迁移现有进度。 + +### 阶段 2:main 上未上线的系统 + +1. 百科、掉落查询、宝箱预览:`uiWiki` + `PythonWiki`,`PythonDropItem`(CG 215 / GC 220),`uiChestDropInfo`(GC 66)。原有 `/mt_features` 查询协议可以退役。 +2. 角色详细属性:`uicharacterdetails`。 +3. 副本信息和计时:`uiDungeonInfo` + `uiDungeonTimer`,CG 213 / GC 217;只列 203 实际存在的副本。 +4. 活动日历:`uiEventCalendarNew`,CG 220 / GC 214、216,`char_event_calendar`。 +5. 换线改为服务端传送;显示开关补上摆摊、宠物、坐骑范围。 + +### 阶段 3:P1–P8 收尾 + +1. 肩带入口改到 NPC 60003(203 上没有这个 NPC,需要新增 NPC 和刷新点)。 +2. 护符:53996/53997 按 AVA2 用途处理,元素目标包,`uielementchange` / `uielementspelladd`,去掉冰元素。 +3. 戒指稀有属性 `item_attr_rare_rings`。 +4. 武器时装、肩带外观、特效槽三个系统,以及对应的强化石。 +5. 解决 MAX_LEVEL 问题。 + +### 阶段 4:P9–P11 + +宠物、技能书、第 6/7 条属性,直接按 AVA2 实现。 + +### 部署 + +- 阶段 1 每个系统都会改动线上协议,客户端和服务端必须一起更新。旧客户端连不上新服务端,需要准备客户端更新包和公告。 +- 沿用 `20261016-ava2-drops/deploy.sh` 模板:先停服,再备份二进制、配置和数据,最后启动 db 并检查。 + +## 4. 协议约定(2026-10-16 已同意) + +- **包头号**:沿用 AVA2 的号码(见 §1 的空闲号列表)。40250 基础包不动。注册方式照肩带:服务端 `packet.h` + `packet_info.cpp` 的 `Set(...)` + `input_main.cpp` 的 case;客户端 `PythonNetworkStream.cpp` 的 `Set(HEADER, TPacketType(size, STATIC/DYNAMIC_SIZE_PACKET))` + `PythonNetworkStreamPhaseGame.cpp` 分发。 +- **包结构**:header、subheader、字段顺序照抄 AVA2。内嵌的物品数据按当前结构(3 个 socket、7 条属性、32 位金币),与 `TPacketGCItemSet` 一致。 +- **类型宽度**:只用固定宽度类型,不用 `long`(服务端 i386 上 4 字节,客户端 arm64 上 8 字节);客户端沿用 `LONG`(32 位)加 “PORT: LONG, the 32-bit Win32 long” 注释。`#pragma pack(1)`,两端都写 sizeof 测试(参照 `test_sash.py` 和 `tests/port/classic/wire_classic.h`)。 +- **变长包**:header + size + subheader,两端都注册为动态长度。 +- **旧客户端**:未知包头会让任一端断开。做法(自动洗练起):新客户端在 `CG_CLIENT_VERSION` 的 timestamp 里发 `mt<日期>`(现为 `mt20261016`),服务端只给日期够新的客户端发新包,旧客户端照常能玩、只是没有新功能。是否再恢复 `CG_CLIENT_VERSION2` 强制更新(`config.cpp` 约 1336–1339 行目前注释掉了)留到全部切完时决定。 +- **聊天命令退役**:每个系统切到 AVA2 包后,删掉对应的 `/mt_*` 命令和客户端解析;全部切完后 `/mt_features` 能力协商也不再需要。 +- **服务端逻辑**:按 AVA2 移植。是否保留 40250 原有检查和 ItemLog 见 §5 第 2 项。 + +## 5. 待决定 + +1. **底层结构**:8 个 socket、15 条属性、64 位金币、等级上限等是否也要对齐?建议不对齐,等级上限单独决定。 +2. **经济规则**:自动洗练已按“AVA2 的流程和 0.1 秒速度 + 保留现有检查和 ItemLog”实现;批量开箱单次 1000 待定。 +3. **顺序**:已定,先做阶段 1,从自动洗练开始。自动洗练代码已完成,下一个是批量开箱。 diff --git a/docs/AVA2-SWITCHBOT.md b/docs/AVA2-SWITCHBOT.md index 8342ea4c..f2c37e30 100644 --- a/docs/AVA2-SWITCHBOT.md +++ b/docs/AVA2-SWITCHBOT.md @@ -1,74 +1,56 @@ -# AVA2 自动洗练适配进度(v1 + 属性锁定) +# AVA2 自动洗练(按 AVA2 移植) -2026-10-15。修改了 metin2-client 和 metin2-server,AVA2 代码只作参考。服务端规则和协议见 `metin2-server/docs/FEATURE-SWITCHBOT.md`。 +2026-10-16 起替换 v1(`/mt_switchbot` / `MTSB1`)。服务端规则和协议见 `metin2-server/docs/FEATURE-SWITCHBOT.md`,计划见 `docs/AVA2-PARITY-PLAN.md` 阶段 1。 -## 与 AVA2 的差异 +## 和 AVA2 相同的部分 -| 项目 | AVA2 | 本实现 | -| --- | --- | --- | -| 窗口 | 新增 SWITCHBOT 物品窗口,5 个物品槽加 1 个道具槽 | 不新增窗口类型,物品留在背包,按物品 ID 绑定;每个角色同一时间只洗 1 件 | -| 洗练执行 | 自己实现消耗和 ChangeAttribute,绕过手动检查和 ItemLog | 每次都调用原 `UseItem`,检查、概率、日志、扣道具都和手动洗练一样;71151/76023 仍只能洗等级上限 ≤40 的武器和衣服 | -| 速度 | 0.1 秒一次 | 0.25 秒一次(约 4 次/秒) | -| 物品被移动 | 拦截移动、交易、出售等路径 | 每次洗练前重新检查:物品不在背包、已装备、易主时停止(item_gone);交易、商店、仓库、合成界面打开时停止(busy) | -| 换线 / 下线 | 通过 P2P 转移,继续洗 | 直接停止,不离线洗练 | +- **C++** + - `PythonSwitchbot.{h,cpp}`:`switchbot` 模块,接口和 AVA2 相同。 + - `PythonNetworkStreamPhaseGameSwitchbot.cpp`:收发代码照搬 AVA2。 + - `Packet.h`:CG/GC 171,subheader 和字段顺序同 AVA2。物品按本服结构:3 个孔、7 条属性。 + - `GameType.h`:`SWITCHBOT = 7` 窗口、`SLOT_TYPE_SWITCHBOT`。 + - `PythonPlayer`:`aSwitchbotItem`。 + - `RecvItemSetPacket`:收到 SWITCHBOT 窗口的物品时刷新洗练窗口。 +- 结构体都是 `pack(1)`,两端都用 `static_assert` 固定大小:220 / 15 / 9 / 40 / 7。 +- **脚本**:`mt_switchbot`(`src/platform/ScriptLib/SwitchbotScript.inc`)。 + - 主体是 AVA2 `root/uiswitchbot.py` 原文:SwitchbotItemTab、SwitchbotAttribute、SwitchbotWindow、SearchListWindow、ConfigurationWindow。方案用 pickle 存在 `switchbot.inf`。 + - 再补上 AVA2 放在别的文件里、用 `ENABLE_SWITCHBOT` 包起来的部分: + - `ui.ThinBoardCircle`、`ListBoxEx.GetItems`; + - `uitooltip.SetSwitchBotItem`; + - mouseModule / uiinventory 的 `SLOT_TYPE_SWITCHBOT`(拖回背包时发 `SendItemMovePacket(SWITCHBOT → INVENTORY)`); + - interfacemodule 的 Toggle / Refresh / HideAllWindows / `__HideWindows`; + - game.py 的 `RefreshSwitchbotWindow` / `RefreshSwitchbotItem`。 +- **图片**:`d:/ymir work/ui/switchbot/` 和 `ui/pattern/thinboardcircle/`。`tools/server/ava2-items/make_items.py` 的 `SWITCHBOT_UI` 把它们打进 ava2items 包。 -匹配规则和 AVA2 相同:最多 2 套方案,每套 1–5 条“属性 ≥ 阈值”;任意一套全部达标就停止,只看前 5 条普通属性。 +## 和 AVA2 不同的地方 -## 客户端 +| 项目 | AVA2 | 本实现 | 原因 | +| --- | --- | --- | --- | +| 第 6 格(洗练道具格) | 显示,放 71084 | 隐藏(`attrTab.Hide()`) | 服务端从背包取道具,不用第 5 号格 | +| 入口 | 扩展任务栏按钮 + F9 | 小地图旁“洗练”按钮(y+148,原 v1 按钮的位置) | 40250 没有扩展任务栏;F9/F8 已给自动狩猎,触屏也要能点 | +| 结束 / 停止提示 | locale_string 864 / 865 | 服务端命令 `switchbot_end/stop/error`,脚本转成中文聊天提示 | 见服务端文档 | +| “Alternativen:” | 德文写死 | `localeInfo.SWITCHBOT_ALTERNATIVES`(备选方案:) | 原文没走 locale | +| 文字 | locale_game.txt | 脚本里补中文 `SWITCHBOT_*`(`player.AutoHuntLocalize` 转码) | 本服 locale 没有这些条目 | +| 版本 | — | `CG_CLIENT_VERSION` 的 timestamp 发 `mt20261016`(原为 `__TIMESTAMP__`) | 服务端只给新客户端发 GC_SWITCHBOT | -- 模块 `mt_switchbot`(`src/platform/ScriptLib/SwitchbotScript.inc`),在 `PythonBoot.cpp` 中安装。入口是小地图旁“百科”按钮下方的“洗练”按钮。 -- 物品:扫描背包里至少有一条属性的武器和防具,用 `<` `>` 切换。洗练道具:扫描子类型为 USE_CHANGE_ATTRIBUTE 的道具,显示数量。次数上限可选 10、50、100、200、500、1000。 -- 可选属性和最大值由服务端 `attrs` 下发,客户端不自己推算。添加属性时分页点选;阈值用 -/+ 调整,步长为最大值的 1/5,默认取最大值。 -- 运行时锁定所有设置,实时显示次数、剩余道具、停止原因和当前 5 条属性。停止时在聊天框提示;达标时如果窗口已关闭,会自动打开。 -- 命令间隔至少 0.3 秒,同一时间只有一个请求在等待回复。4 秒没有回复就显示“服务器尚未启用自动洗练”。`attrs` 只接受完整、连续的回复,不完整的整批丢弃。 -- 文字都用 GBK 可编码的字符(不用 ◀/▶/⚠)。 +没有移植 AVA2 的 `uiswitch.DopadorMenu/DopadorManual`(另一套手动洗练菜单)。 -## 属性锁定(2026-10-15) - -- 服务端规则、存储和协议见 `metin2-server/docs/FEATURE-ATTR-LOCK.md`。锁定的槽位在所有洗练方式下都保持不变:手动用道具、自动洗练、GM 命令。 -- 窗口底部“开始/停止”右边有 5 个按钮,每条有属性的普通槽一个:`锁N` 表示未锁,`【锁N】` 表示已锁。点击切换。选属性时和洗练中不能点。 -- 当前属性行里,已锁的属性前面加 `[锁]`。状态行提示“已锁定的属性在每次洗练中保持不变”。 -- 服务端在 `attrs_end` 之后下发 `MTSB1 lock CELL VNUM MASK`。旧服务端不发这一行,所以不显示按钮。 -- 错误提示:`slot`(该条属性不能锁定),`max`(最多锁定 2 条,且至少留 1 条可洗),`db`(保存失败)。 -- 与 AVA2 的差异: - - 锁定免费。AVA2 每次锁定或解锁消耗 50348/50349,203 的 item_proto 里没有这两个道具。 - - 锁定状态存在服务端独立表里,不占属性槽。 - - 不要求物品正好有 5 条属性,但至少要留 1 条不锁。 -- 联机测试(channel5 13040,盔甲 11209,背包 19 格): - - 锁第 2、4 条后,自动洗 10 次,这两条每次都不变,其余 3 条每次都变; - - 锁第 3 组时提示 max; - - 重新登录后锁定状态仍在; - - 解锁后表里的行被删除。 +右键使用 50348/50349 不再打开洗练窗口。服务端仍支持把这两个道具用到物品上来锁定或解锁属性(槽位取道具的 socket 0),但 AVA2 选槽位的界面和物品提示还没做。 ## 证据 -- `tests/wiki/test_switchbot.py`(CTest:`port.switchbot`)共 7 项通过(第 7 项是锁定协议和按钮),覆盖: - - 请求节流和合并; - - 不完整的 attrs 回复被拒绝; - - start 命令的拼装和校验; - - state/error 解析和超时; - - 和服务端的原因码、错误码、上限一致; - - 窗口流程:扫描 → 读取属性 → 选属性 → 开始 → 达标提示。 -- 脚本能在 Python 2.7 下编译。`tests/wiki/test_service.py` 仍然通过。 -- 2026-10-15 联机测试(203 额外开的测试核心 channel5/first,端口 13040,使用隔离编译的 game;macOS 原生客户端,账号 admin,物品为背包 33 格的剑 279,道具 71084): - - 上限 10 次:洗满 10 次后停止(limit),约 4 次/秒。 - - 两套方案、阈值 1:第 18 次达标(matched)。 - - 已经达标的物品:0 次就停止,不扣道具。 - - 洗练中把物品从 33 格移到 90 格:继续洗,窗口跟到 90 格;点停止后显示 stopped。 - - 洗练中退出客户端:服务端立即停止。 - - log.log 中 CHANGE_ATTRIBUTE 共 72 行,和总次数一致。 - - busy:洗练中摆摊(先给 50200 摊位包袱;没有它 `OpenMyShop` 会提前返回、摊位不会开,第一次测试就是这样误判的),摊位开出约 1 秒后停止(busy),共洗 6 次。 - - no_scroll:用 76014(共 6 张)、上限 10,洗 6 次后停止(no_scroll),道具剩 0。 - - rejected:对 90 级剑用 71151(原路径只允许等级 <= 40):0 次就停止(rejected),道具未扣。 - - 截图里窗口布局正常。仓库自带的 `Client` 是英文 cp1252 locale,所以中文显示为 `????`;需要 zh locale 客户端才能看到中文。 -- 联机测试发现并修复了两个窗口问题,`test_switchbot.py` 已加回归用例: - - 洗练中移动物品后,选中项会跳到别的物品:现在按服务端报告的格子跟随。 - - 空闲时移动物品后选中项丢失:现在退而按相同 vnum 匹配。 -- 服务端 `tests/features/test_switchbot.py` 和 `test_queries.py` 通过。203 的隔离目录 `/root/metin2-features-dev` 完整编译通过。 +- `tests/wiki/test_switchbot.py`(CTest `port.switchbot`),5 项: + - 窗口代码和 AVA2 原文逐字相同(只有上表两处替换); + - ThinBoardCircle、文字、`USERDATA_DIRECTORY`、5 个标签页的宽度; + - 服务端命令提示,其他命令照常传下去; + - 从洗练窗口拖回背包; + - interface / game 钩子。 +- `tests/wiki/test_item_actions.py` 已更新:50348/50349 走原来的使用流程。 +- 脚本能在 Python 2.7 下编译。macOS 构建(`build/switchbot-check`,关闭 MeshPort)通过,ctest 52 项全过(7 项跳过,和之前一样)。 +- 服务端 `tests/features/test_switchbot.py` 同时检查客户端 `Packet.h`、`PythonSwitchbot.h` 和版本字符串。 ## 未完成 -- Android 真机测试。 -- macOS 构建需要 `-DMT_40250_SOURCE=<含 EterPack/EterPack.cpp 的源码目录>` 来生成 pack 密钥,否则 system.py 读不出来(RunMain Error)。本机没有 40250 源码,这次用的是 AVA2 的 `TEST/3. Source BIN/Client`,两者密钥相同。 -- 服务端还没有部署到 203 正式环境。 -- 属性锁定已完成(见上),2026-10-15 16:08 已部署到 203 正式环境(服务端 dc71593),CH1 联机验收通过。 +- 联机测试:channel5 或部署后的 CH1。203 正式环境还是 v1,服务端和客户端要一起部署。 +- Android 构建和真机测试。 +- 属性锁定界面(AVA2 拖 50348/50349,并在物品提示里显示锁定)。 diff --git a/src/platform/ScriptLib/ItemActionsScript.inc b/src/platform/ScriptLib/ItemActionsScript.inc index 4e453864..7e8fcdad 100644 --- a/src/platform/ScriptLib/ItemActionsScript.inc +++ b/src/platform/ScriptLib/ItemActionsScript.inc @@ -93,10 +93,6 @@ def UseItemSlot(self,slot): import mt_battlepass if mt_battlepass.g_window:mt_battlepass.g_window.OfferTicket(cell,vnum) return - if vnum in (50348,50349): - import mt_switchbot - if mt_switchbot.g_window:mt_switchbot.g_window.Open() - return return _use(self,slot) uiInventory.InventoryWindow.UseItemSlot=UseItemSlot diff --git a/src/platform/ScriptLib/PythonBoot.cpp b/src/platform/ScriptLib/PythonBoot.cpp index c7386391..31a91edd 100644 --- a/src/platform/ScriptLib/PythonBoot.cpp +++ b/src/platform/ScriptLib/PythonBoot.cpp @@ -38,6 +38,7 @@ #include "UserInterface/PythonMessenger.h" #include "UserInterface/PythonSafeBox.h" #include "UserInterface/PythonSash.h" +#include "UserInterface/PythonSwitchbot.h" #include "UserInterface/PythonGuild.h" #include "UserInterface/MarkManager.h" #include "UserInterface/GuildMarkDownloader.h" @@ -158,6 +159,7 @@ struct GameSingletons CPythonMessenger pyManager; CPythonSafeBox pySafeBox; CPythonSash pySash; // PORT: AVA2 sash + CPythonSwitchbot pySwitchbot; // PORT: AVA2 switchbot CPythonGuild pyGuild; CGuildMarkManager kGuildMarkManager; CGuildMarkDownloader kGuildMarkDownloader; @@ -924,6 +926,7 @@ bool run_main_script_body(const char* lpCmdLine, std::string* error) initMessenger(); initsafebox(); initSash(); + initSwitchbot(); initguild(); initServerStateChecker(); initRenderTarget(); // PORT: AVA2 model preview diff --git a/src/platform/ScriptLib/SwitchbotScript.inc b/src/platform/ScriptLib/SwitchbotScript.inc index 88086cf9..30e82833 100644 --- a/src/platform/ScriptLib/SwitchbotScript.inc +++ b/src/platform/ScriptLib/SwitchbotScript.inc @@ -1,406 +1,1911 @@ -// PORT: AVA2-style automatic attribute change (uiswitchbot.py), driven by the server's /mt_switchbot -// command. Every roll runs on the server through the original change-attribute scroll path; this window -// only picks the item, scroll and targets and shows progress. The lock buttons toggle the server-side attribute -// lock that every reroll keeps. Protocol: metin2-server docs/FEATURE-SWITCHBOT.md, FEATURE-ATTR-LOCK.md. +// PORT: AVA2 switchbot (自动洗练) window, as module mt_switchbot. The C++ side is the AVA2 switchbot module +// (PythonSwitchbot.cpp, CG/GC_SWITCHBOT 171, the SWITCHBOT item window); this script is AVA2 root/uiswitchbot.py +// verbatim (SwitchbotItemTab, SwitchbotAttribute, SwitchbotWindow, SearchListWindow, ConfigurationWindow) plus +// what AVA2 put behind ENABLE_SWITCHBOT elsewhere: ui.ThinBoardCircle and ListBoxEx.GetItems, the SWITCHBOT_* +// locale strings (zh here), uitooltip SetSwitchBotItem, mouseModule/uiinventory SLOT_TYPE_SWITCHBOT, the +// interfacemodule/game.py glue. Deviations: cell 5 (the switcher cell) is hidden, because the server takes +// switchers from the inventory; the entry is a button by the minimap instead of the taskbar button and F9; the end +// / stop / error messages arrive as server commands (switchbot_end/stop/error) instead of locale ids 864/865. +// Images ship in the ava2items pack (tools/server/ava2-items, SWITCHBOT_UI). Server: metin2-server port_switchbot.cpp. static const char c_szSwitchbotScript[] = R"PY(# -*- coding: utf-8 -*- +import dbg +import constInfo import app +import ime +import item +import grp +import net +import ui +from uiToolTip import ItemToolTip +import player +import mouseModule +import localeInfo +import wndMgr +import cPickle as pickle +import switchbot + import chat import game -import grp -import item -import net -import player -import ui -import uiToolTip -import wndMgr +import interfaceModule +import uiInventory import weakref -from mt_biolog import Action, Text, L -from mt_wiki import B, U +from mt_biolog import Action -g_window=None -g_entry=None -USE_CHANGE_ATTRIBUTE=18 # CItemData::EUseSubTypes; the server re-checks the scroll subtype. -LIMITS=(10,50,100,200,500,1000) -MAX_TARGETS=5 -LOCK_GROUPS=2 -SEND_GAP=.3 -TIMEOUT=4. -REASONS={'running':'洗练中','matched':'已获得目标属性','limit':'已达到次数上限','no_scroll':'洗练道具已用完', - 'item_gone':'物品已移动、装备或交易,已停止','rejected':'服务器拒绝了本次洗练','busy':'交易/商店/仓库/合成界面打开,已停止', - 'stopped':'已手动停止','idle':'未运行'} -ERRORS={'rate':'操作过快,请稍后','invalid':'参数无效','item':'物品不存在','equipped':'请先卸下装备或结束交易','no_attr':'该物品不能洗练', - 'scroll':'没有可用的洗练道具','target':'目标属性超出可洗范围','running':'已有洗练在进行','busy':'当前状态不能洗练', - 'unsupported':'服务器尚未启用自动洗练','slot':'该条属性不能锁定','max':'最多锁定 2 条,且至少留 1 条可洗', - 'db':'锁定保存失败,请稍后再试','five_attr':'装备需要 5 条普通属性才能锁定','material':'锁定需要道具 50348,解锁需要道具 50349'} +# --- ui.py / localeInfo / constInfo parts AVA2 put behind ENABLE_SWITCHBOT ------------------------------------- +L=player.AutoHuntLocalize +TEXT={'SWITCHBOT_TITLE':'自动洗练','SWITCHBOT_START':'开始','SWITCHBOT_STOP':'停止','SWITCHBOT_SELECT_ATTR':'属性列表', + 'SWITCHBOT_SAVE_BUTTON':'保存方案','SWITCHBOT_SAVE':'保存','SWITCHBOT_LOAD_CONFIGURATION':'使用', + 'SWITCHBOT_CONFIGURATION_TITLE':'已保存的方案','SWITCHBOT_CLEAR_CONFIGURATION':'删除','SWITCHBOT_CLEAR_ATTR':'清除', + 'SWITCHBOT_EMPTY_ATTR':'选择属性','SWITCHBOT_ALTERNATIVES':'备选方案:', + 'SWITCHBOT_ACTIVE':'正在自动洗练,达到设定的属性或手动停止前不能移动该物品。','UI_ACCEPT':'确定','UI_CANCEL':'取消'} +for key,text in TEXT.items(): + if key.startswith('SWITCHBOT_') or not hasattr(localeInfo,key):setattr(localeInfo,key,L(text)) +MESSAGES={'end':'%s(第 %d 格)洗练完成!','noattr':'第 %d 格的物品没有可洗练的属性,已停止。', + 'nochanger':'自动洗练已停止:背包里没有可用的洗练道具。','active':'该格正在洗练,请先停止。', + 'invalid':'这件物品不能自动洗练。'} +if not hasattr(constInfo,'USERDATA_DIRECTORY'):constInfo.USERDATA_DIRECTORY='' + +class ThinBoardCircle(ui.Window): + CORNER_WIDTH = 4 + CORNER_HEIGHT = 4 + LINE_WIDTH = 4 + LINE_HEIGHT = 4 + BOARD_COLOR = grp.GenerateColor(255.0, 255.0, 255.0, 1.0) + + LT = 0 + LB = 1 + RT = 2 + RB = 3 + L = 0 + R = 1 + T = 2 + B = 3 + + def __init__(self, layer = "UI"): + ui.Window.__init__(self, layer) + + CornerFileNames = [ "d:/ymir work/ui/pattern/thinboardcircle/ThinBoard_Corner_"+dir+".tga" for dir in ["LeftTop_circle","LeftBottom_circle","RightTop_circle","RightBottom_circle"] ] + LineFileNames = [ "d:/ymir work/ui/pattern/thinboardcircle/ThinBoard_Line_"+dir+".tga" for dir in ["Left_circle","Right_circle","Top_circle","Bottom_circle"] ] + + self.Corners = [] + for fileName in CornerFileNames: + Corner = ui.ExpandedImageBox() + Corner.AddFlag("attach") + Corner.AddFlag("not_pick") + Corner.LoadImage(fileName) + Corner.SetParent(self) + Corner.SetPosition(0, 0) + Corner.Show() + self.Corners.append(Corner) + + self.Lines = [] + for fileName in LineFileNames: + Line = ui.ExpandedImageBox() + Line.AddFlag("attach") + Line.AddFlag("not_pick") + Line.LoadImage(fileName) + Line.SetParent(self) + Line.SetPosition(0, 0) + Line.Show() + self.Lines.append(Line) + + Base = ui.Bar() + Base.SetParent(self) + Base.AddFlag("attach") + Base.AddFlag("not_pick") + Base.SetPosition(self.CORNER_WIDTH, self.CORNER_HEIGHT) + Base.SetColor(self.BOARD_COLOR) + Base.Show() + self.Base = Base + + self.Lines[self.L].SetPosition(0, self.CORNER_HEIGHT) + self.Lines[self.T].SetPosition(self.CORNER_WIDTH, 0) + + def __del__(self): + ui.Window.__del__(self) + + def SetSize(self, width, height): + + width = max(self.CORNER_WIDTH*2, width) + height = max(self.CORNER_HEIGHT*2, height) + ui.Window.SetSize(self, width, height) + + self.Corners[self.LB].SetPosition(0, height - self.CORNER_HEIGHT) + self.Corners[self.RT].SetPosition(width - self.CORNER_WIDTH, 0) + self.Corners[self.RB].SetPosition(width - self.CORNER_WIDTH, height - self.CORNER_HEIGHT) + self.Lines[self.R].SetPosition(width - self.CORNER_WIDTH, self.CORNER_HEIGHT) + self.Lines[self.B].SetPosition(self.CORNER_HEIGHT, height - self.CORNER_HEIGHT) + + verticalShowingPercentage = float((height - self.CORNER_HEIGHT*2) - self.LINE_HEIGHT) / self.LINE_HEIGHT + horizontalShowingPercentage = float((width - self.CORNER_WIDTH*2) - self.LINE_WIDTH) / self.LINE_WIDTH + self.Lines[self.L].SetRenderingRect(0, 0, 0, verticalShowingPercentage) + self.Lines[self.R].SetRenderingRect(0, 0, 0, verticalShowingPercentage) + self.Lines[self.T].SetRenderingRect(0, 0, horizontalShowingPercentage, 0) + self.Lines[self.B].SetRenderingRect(0, 0, horizontalShowingPercentage, 0) + self.Base.SetSize(width - self.CORNER_WIDTH*2, height - self.CORNER_HEIGHT*2) + + def SetAlpha(self, alpha): + color = grp.GenerateColor(0.0, 0.0, 0.0, alpha) + self.Base.SetColor(color) + + def ShowInternal(self): + self.Base.Show() + for wnd in self.Lines: + wnd.Show() + for wnd in self.Corners: + wnd.Show() + + def HideInternal(self): + self.Base.Hide() + for wnd in self.Lines: + wnd.Hide() + for wnd in self.Corners: + wnd.Hide() + +if not hasattr(ui,'ThinBoardCircle'):ui.ThinBoardCircle=ThinBoardCircle +if not hasattr(ui.ListBoxEx,'GetItems'):ui.ListBoxEx.GetItems=lambda self:self.itemList + +# --- uiswitchbot.py (verbatim) --------------------------------------------------------------------------------- +COLOR_INACTIVE = grp.GenerateColor(1.0, 0.0, 0.0, 0.2) +COLOR_ACTIVE = grp.GenerateColor(1.0, 0.6, 0.1, 0.2) +COLOR_FINISHED = grp.GenerateColor(0.0, 1.0, 0.0, 0.2) +COLOR_SELECTED = grp.GenerateColor(1.0, 1.0, 1.0, 1.0) + +SKILL_DAMAGE_BONUS_MAX = 20 +NORMAL_HIT_DAMAGE_BONUS_MAX = 50 +ADDON_TYPES = {item.APPLY_SKILL_DAMAGE_BONUS : SKILL_DAMAGE_BONUS_MAX, item.APPLY_NORMAL_HIT_DAMAGE_BONUS : NORMAL_HIT_DAMAGE_BONUS_MAX} + +BOARD_WIDTH = 400 +INPUT_HEIGHT = 27 + +BORDER_SPACE = 8 +BORDER_SPACE_TOP = 30 + +ITEM_TAB_NAME_BOX_HEIGHT = 20 +ITEM_TAB_SPACE = 2 +ITEM_TAB_WIDTH = (BOARD_WIDTH - BORDER_SPACE * 2) / switchbot.SLOT_COUNT + 1 - ITEM_TAB_SPACE + +TOP_PANEL_HEIGHT = (BORDER_SPACE * 2) + (3 * 32) + ITEM_TAB_NAME_BOX_HEIGHT +TOP_PANEL_WIDTH = BOARD_WIDTH - (BORDER_SPACE * 2) + +MAIN_PANEL_WIDTH = BOARD_WIDTH - BORDER_SPACE * 2 +MAIN_PANEL_HEIGHT = INPUT_HEIGHT * 6 #1 AlternativeRow 5 Attribute + +BOT_PANEL_HEIGHT = 40 +BOT_PANEL_WIDTH = BOARD_WIDTH - BORDER_SPACE * 2 + +ATTR_SLOT_COUNT = 5 + +BOARD_HEIGHT = BORDER_SPACE_TOP + TOP_PANEL_HEIGHT + MAIN_PANEL_HEIGHT + BOT_PANEL_HEIGHT + BORDER_SPACE + +def GetAffectString(affectType, affectValue): + if not affectType: + return None + + try: + return ItemToolTip.AFFECT_DICT[affectType](affectValue) + except TypeError: + return "UNKNOWN_VALUE[{}] {}".format(affectType, affectValue) + except KeyError: + return "UNKNOWN_TYPE[{}] {}".format(affectType, affectValue) -def Number(text,low=0,high=4294967295): - if not text.isdigit() or len(text)>10:raise ValueError(text) - value=int(text) - if not low<=value<=high:raise ValueError(text) - return value +class SwitchbotItemTab(ui.ThinBoardCircle): + def __init__(self, slot_num, isAttrSlot = False): + ui.ThinBoardCircle.__init__(self) + + self.slot_num = slot_num + self.isAttrSlot = isAttrSlot + + self.__Initialize() + self.__LoadItemTab() + self.__BindEvents() + + def __del__(self): + ui.ThinBoardCircle.__del__(self) + + def __Initialize(self): + self.tooltipItem = None + self.onSelectEvent = None + + self.statusBar = None + self.itemSlot = None + self.selectButton = None + + self.lastSelectAlpha = 255 + self.lastSelectAlphaDir = 1 + + def __LoadItemTab(self): + self.SetSize(ITEM_TAB_WIDTH if not self.isAttrSlot else 38, TOP_PANEL_HEIGHT if not self.isAttrSlot else 5+32+5) + + self.statusBar = ui.Bar() + self.statusBar.SetParent(self) + self.statusBar.SetSize(ITEM_TAB_WIDTH - 4 if not self.isAttrSlot else 38-4, TOP_PANEL_HEIGHT - 4 if not self.isAttrSlot else 5+32+5-4) + self.statusBar.SetPosition(2, 2) + + self.selectBox = ui.Box() + self.selectBox.SetParent(self) + self.selectBox.SetPosition(1, 1) + self.selectBox.SetSize(ITEM_TAB_WIDTH - 2 if not self.isAttrSlot else 38-2, TOP_PANEL_HEIGHT - 2 if not self.isAttrSlot else 5+32+5-2) + self.selectBox.SetColor(COLOR_SELECTED) + + if not self.isAttrSlot: + self.selectButton = ui.RadioButton() + self.selectButton.SetParent(self) + self.selectButton.SetUpVisual("d:/ymir work/ui/switchbot/btn_small_01.sub") + self.selectButton.SetOverVisual("d:/ymir work/ui/switchbot/btn_small_02.sub") + self.selectButton.SetDownVisual("d:/ymir work/ui/switchbot/btn_small_03.sub") + self.selectButton.SetDisableVisual("d:/ymir work/ui/switchbot/btn_small_01.sub") + self.selectButton.SetWindowHorizontalAlignCenter() + self.selectButton.SetPosition(0, 5) + self.selectButton.SetText(str(self.slot_num+1)) + self.selectButton.Show() + + self.itemSlot = ui.GridSlotWindow() + self.itemSlot.SetParent(self) + self.itemSlot.ArrangeSlot(0, 1, 3 if not self.isAttrSlot else 1, 32, 32, 0, 0) + self.itemSlot.SetSlotBaseImage("d:/ymir work/ui/public/slot_base.sub", 1.0, 1.0, 1.0, 1.0) + if not self.isAttrSlot: + self.itemSlot.SetWindowHorizontalAlignCenter() + self.itemSlot.SetPosition(0 if not self.isAttrSlot else 2, 5 if self.isAttrSlot else 30) + self.itemSlot.Show() + + def __BindEvents(self): + self.itemSlot.SetOverInItemEvent(ui.__mem_func__(self.OverInItem)) + self.itemSlot.SetOverOutItemEvent(ui.__mem_func__(self.OverOutItem)) + if not self.isAttrSlot: + self.itemSlot.SetSelectEmptySlotEvent(ui.__mem_func__(self.SelectEmptySlot)) + self.itemSlot.SetSelectItemSlotEvent(ui.__mem_func__(self.SelectItemSlot)) + self.itemSlot.SetUnselectItemSlotEvent(ui.__mem_func__(self.UseItemSlot)) + self.itemSlot.SetUseSlotEvent(ui.__mem_func__(self.UseItemSlot)) + + if not self.isAttrSlot: + self.selectButton.SetEvent(ui.__mem_func__(self.__OnSelectButtonClick)) + + def Destroy(self): + self.tooltipItem = 0 + self.onSelectEvent = 0 + self.statusBar = 0 + self.itemSlot = 0 + self.selectButton = 0 + self.lastSelectAlpha = 0 + self.lastSelectAlphaDir = 0 + self.selectBox = 0 + self.selectButton = 0 + ui.ThinBoardCircle.Destroy(self) + + + def SetItemToolTip(self, tooltipItem): + self.tooltipItem = tooltipItem + + def OnPlacedItem(self, slot_num): + pass + + def OverOutItem(self): + self.itemSlot.SetUsableItem(False) + if self.tooltipItem: + self.tooltipItem.HideToolTip() + + def OverInItem(self, overSlotPos): + self.itemSlot.SetUsableItem(True) + if self.IsEmpty(): + return + self.tooltipItem.ClearToolTip() + + itemVnum = player.GetItemIndex(player.SWITCHBOT, self.slot_num) + + if self.IsActive(): + self.tooltipItem.SetSwitchBotItem(itemVnum) + self.tooltipItem.ShowToolTip() + return + + metinSlot = [player.GetItemMetinSocket(player.SWITCHBOT, self.slot_num, i) for i in xrange(player.METIN_SOCKET_MAX_NUM)] + attrSlot = [player.GetItemAttribute(player.SWITCHBOT, self.slot_num, i) for i in xrange(player.ATTRIBUTE_SLOT_MAX_NUM)] + + self.tooltipItem.AddItemData(itemVnum, metinSlot, attrSlot) + self.tooltipItem.ShowToolTip() + + def SelectEmptySlot(self, selectedSlotPos): + if constInfo.GET_ITEM_QUESTION_DIALOG_STATUS() == 1: + return + + check = player.GetItemIndex(player.SWITCHBOT, self.slot_num) + if check: + mouseModule.mouseController.DeattachObject() + return + + if mouseModule.mouseController.isAttached(): + + attachedSlotType = mouseModule.mouseController.GetAttachedType() + attachedSlotPos = mouseModule.mouseController.GetAttachedSlotNumber() + attachedItemCount = mouseModule.mouseController.GetAttachedItemCount() + attachedItemIndex = mouseModule.mouseController.GetAttachedItemIndex() + + if player.SLOT_TYPE_INVENTORY == attachedSlotType: + attachedCount = mouseModule.mouseController.GetAttachedItemCount() + net.SendItemMovePacket(player.INVENTORY, attachedSlotPos, player.SWITCHBOT, self.slot_num, long(attachedItemCount)) + elif player.SLOT_TYPE_SWITCHBOT == attachedSlotType: + attachedCount = mouseModule.mouseController.GetAttachedItemCount() + net.SendItemMovePacket(player.SWITCHBOT, attachedSlotPos, player.SWITCHBOT, self.slot_num, long(attachedItemCount)) + + mouseModule.mouseController.DeattachObject() + + self.OnPlacedItem(self.slot_num) + + def SelectItemSlot(self, itemSlotIndex): + if constInfo.GET_ITEM_QUESTION_DIALOG_STATUS() == 1: + return + + if switchbot.IsActive(self.slot_num): + return + + if mouseModule.mouseController.isAttached(): + mouseModule.mouseController.DeattachObject() + else: + + if app.IsPressed(app.DIK_LALT): + link = player.GetItemLink(player.SWITCHBOT, self.slot_num) + ime.PasteString(link) + else: + itemVnum = player.GetItemIndex(player.SWITCHBOT, self.slot_num) + itemCount = player.GetItemCount(player.SWITCHBOT, self.slot_num) + mouseModule.mouseController.AttachObject(self, player.SLOT_TYPE_SWITCHBOT, self.slot_num, itemVnum, itemCount) + + def UseItemSlot(self, slotIndex): + curCursorNum = app.GetCursor() + if app.SELL == curCursorNum: + return + + if constInfo.GET_ITEM_QUESTION_DIALOG_STATUS() == 1: + return + + net.SendItemUsePacket(player.SWITCHBOT, self.slot_num) + mouseModule.mouseController.DeattachObject() + self.OverOutItem() + + def RefreshItemSlot(self): + if self.IsEmpty(): + switchbot.ClearSlot(self.slot_num) + self.itemSlot.ClearSlot(0) + self.statusBar.Hide() + else: + itemCount = player.GetItemCount(player.SWITCHBOT, self.slot_num) + itemVnum = player.GetItemIndex(player.SWITCHBOT, self.slot_num) + if itemCount == 1: + itemCount = 0 + + if self.isAttrSlot: + itemCount = 0 if self.IsActive() else itemCount + + self.itemSlot.SetItemSlot(0, itemVnum, itemCount) + + self.statusBar.Show() + if self.IsActive(): + self.itemSlot.ActivateSlot(0) + if not self.isAttrSlot: + self.statusBar.SetColor(COLOR_ACTIVE) + else: + self.itemSlot.DeactivateSlot(0) + if self.isAttrSlot: + self.statusBar.SetColor(COLOR_FINISHED) + else: + if self.IsFinished(): + self.statusBar.SetColor(COLOR_FINISHED) + else: + self.statusBar.SetColor(COLOR_INACTIVE) + + self.itemSlot.RefreshSlot() + + def IsEmpty(self): + itemVnum = player.GetItemIndex(player.SWITCHBOT, self.slot_num) + return not itemVnum + + def IsActive(self): + if self.isAttrSlot: + for j in xrange(switchbot.SLOT_COUNT): + if switchbot.IsActive(j): + return True + return False + return switchbot.IsActive(self.slot_num) + + def IsFinished(self): + if self.isAttrSlot: + for j in xrange(switchbot.SLOT_COUNT): + if switchbot.IsActive(j): + return False + return True + return switchbot.IsFinished(self.slot_num) + + def GetSlotNum(self): + return self.slot_num + + def SetOnSelectEvent(self, event): + self.onSelectEvent = event + + def __OnSelectButtonClick(self): + if self.onSelectEvent: + self.onSelectEvent(self.slot_num) + + def SetUp(self): + if not self.isAttrSlot: + if self.selectButton: + self.selectButton.SetUp() + self.selectBox.Hide() + + def Down(self): + if not self.isAttrSlot: + if self.selectButton: + self.selectButton.Down() + + self.lastSelectAlpha = 255 + self.selectBox.Show() + + def OnUpdate(self): + if self.selectBox.IsShow(): + rate = 3 + + self.lastSelectAlpha -= (rate * self.lastSelectAlphaDir) + + if self.lastSelectAlpha <= 0: + self.lastSelectAlpha = 0 + self.lastSelectAlphaDir = -1 + elif self.lastSelectAlpha >= 255: + self.lastSelectAlpha = 255 + self.lastSelectAlphaDir = 1 + + self.selectBox.SetColor(grp.GenerateColor(1.0, 1.0, 1.0, float(self.lastSelectAlpha) / 255.0)) + +class SwitchbotAttribute(ui.Window): + VALUE_WIDTH = 50 + + typeInput = None + typeTextLine = None + searchTypeButton = None + deleteAttributeButton = None + valueInput = None + valueEditLine = None + + def __init__(self): + ui.Window.__init__(self) + self.__Initialize() + + def __del__(self): + ui.Window.__del__(self) + + def __Initialize(self): + self.selectedSlot = -1 + self.alternative = 0 + self.index = -1 + + self.attributeType = 0 + self.attributeValue = 0 + + self.searchEvent = None + self.attributeMaxValue = 0 + + self.typeInput = None + self.typeTextLine = None + self.searchTypeButton = None + self.deleteAttributeButton = None + self.valueInput = None + self.valueEditLine = None + + def Destroy(self): + self.VALUE_WIDTH = 0 + self.typeInput = 0 + self.typeTextLine = 0 + self.searchTypeButton = 0 + self.deleteAttributeButton = 0 + self.valueInput = 0 + self.valueEditLine = 0 + self.selectedSlot = 0 + self.alternative = 0 + self.index = 0 + + self.attributeType = 0 + self.attributeValue = 0 + self.searchEvent = 0 + self.attributeMaxValue = 0 + + def Create(self, width, index): + self.index = index + self.SetSize(width, INPUT_HEIGHT) + + self.typeInput = ui.ThinBoardCircle() + self.typeInput.SetParent(self) + self.typeInput.SetSize(width - self.VALUE_WIDTH, INPUT_HEIGHT) + self.typeInput.SetPosition(0, 0) + self.typeInput.Show() + + self.typeTextLine = ui.TextLine() + self.typeTextLine.SetParent(self.typeInput) + self.typeTextLine.SetText(localeInfo.SWITCHBOT_EMPTY_ATTR) + self.typeTextLine.SetVerticalAlignCenter() + self.typeTextLine.SetWindowVerticalAlignCenter() + self.typeTextLine.SetHorizontalAlignCenter() + self.typeTextLine.SetWindowHorizontalAlignCenter() + self.typeTextLine.SetPosition(-20, -1) + self.typeTextLine.Show() + + self.searchTypeButton = ui.Button() + self.searchTypeButton.SetParent(self.typeInput) + self.searchTypeButton.SetUpVisual("d:/ymir work/ui/switchbot/search_attr_01.sub") + self.searchTypeButton.SetOverVisual("d:/ymir work/ui/switchbot/search_attr_02.sub") + self.searchTypeButton.SetDownVisual("d:/ymir work/ui/switchbot/search_attr_03.sub") + self.searchTypeButton.SetDisableVisual("d:/ymir work/ui/switchbot/search_attr_03.sub") + self.searchTypeButton.SetWindowHorizontalAlignRight() + self.searchTypeButton.SetWindowVerticalAlignCenter() + self.searchTypeButton.SetPosition(24 * 2 + 2, 1) + self.searchTypeButton.SetEvent(ui.__mem_func__(self.__OnClickSearchButton)) + self.searchTypeButton.Show() + + self.deleteAttributeButton = ui.Button() + self.deleteAttributeButton.SetParent(self.typeInput) + self.deleteAttributeButton.SetUpVisual("d:/ymir work/ui/switchbot/delete_attr_01.sub") + self.deleteAttributeButton.SetOverVisual("d:/ymir work/ui/switchbot/delete_attr_02.sub") + self.deleteAttributeButton.SetDownVisual("d:/ymir work/ui/switchbot/delete_attr_03.sub") + self.deleteAttributeButton.SetDisableVisual("d:/ymir work/ui/switchbot/delete_attr_03.sub") + self.deleteAttributeButton.SetWindowHorizontalAlignRight() + self.deleteAttributeButton.SetWindowVerticalAlignCenter() + self.deleteAttributeButton.SetPosition(24 + 2, 1) + self.deleteAttributeButton.SetToolTipText(localeInfo.SWITCHBOT_CLEAR_ATTR) + self.deleteAttributeButton.SetEvent(ui.__mem_func__(self.__OnClickClearButton)) + self.deleteAttributeButton.Show() + + self.valueInput = ui.ThinBoardCircle() + self.valueInput.SetParent(self) + self.valueInput.SetSize(self.VALUE_WIDTH, INPUT_HEIGHT) + self.valueInput.SetPosition(width - self.VALUE_WIDTH, 0) + self.valueInput.Show() + + self.valueEditLine = ui.EditLine() + self.valueEditLine.SetParent(self.valueInput) + self.valueEditLine.SetSize(self.VALUE_WIDTH, 18) + self.valueEditLine.SetMax(4) + self.valueEditLine.SetNumberMode() + self.valueEditLine.SetText("0") + self.valueEditLine.SetPosition(10, 7) + self.valueEditLine.Show() + self.valueEditLine.OnIMEUpdate = self.__OnEditLineIMEUpdate + self.valueEditLine.SetEscapeEvent(ui.__mem_func__(self.__OnEscapeEvent)) + + + + def Hide(self): + ui.Window.Hide(self) + + if self.valueEditLine: + self.valueEditLine.KillFocus() + + def RefreshAttributeRow(self, slot_num, alternative, index): + self.selectedSlot = slot_num + self.alternative = alternative + self.index = index + + if switchbot.IsActive(slot_num): + self.searchTypeButton.Disable() + self.deleteAttributeButton.Disable() + self.valueEditLine.Hide() + else: + self.searchTypeButton.Enable() + self.deleteAttributeButton.Enable() + self.valueEditLine.Show() + + (type, value) = switchbot.GetAttribute(slot_num, alternative, index) + if not type: + self.SetAttribute(localeInfo.SWITCHBOT_EMPTY_ATTR, 0) + return + + affectString = GetAffectString(type, value) + if not affectString: + return + + self.SetAttribute(affectString, value) + + def __OnEditLineIMEUpdate(self): + ui.EditLine.OnIMEUpdate(self.valueEditLine) + + text = self.valueEditLine.GetText() + if len(text) > 0 and text.isdigit(): + (curType, curValue) = switchbot.GetAttribute(self.selectedSlot, self.alternative, self.index) + + maxValue = 0 + if not ADDON_TYPES.has_key(curType): + maxValue = switchbot.GetAttributeMaxValue(self.selectedSlot, curType) + + value = int(text) + + if value == curValue: + return + + if maxValue != 0 and value > maxValue: + value = maxValue + self.valueEditLine.SetText(str(value)) + + switchbot.SetAttribute(self.selectedSlot, self.alternative, self.index, curType, value) + self.typeTextLine.SetText(GetAffectString(curType, value)) + self.__OnAttributeUpdate() + + def SetSearchEvent(self, event): + self.searchEvent= event + + def __OnClickSearchButton(self): + if self.searchEvent: + self.searchEvent(self.index) + + def SetAttributeUpdateEvent(self, event): + self.attributeUpdateEvent = event + + def __OnAttributeUpdate(self): + if self.attributeUpdateEvent: + self.attributeUpdateEvent(self.index) + + def SetEscapeEvent(self, event): + self.escapeEvent = event + + def __OnEscapeEvent(self): + if self.escapeEvent: + self.escapeEvent() + + def __OnClickClearButton(self): + self.SetAttribute(localeInfo.SWITCHBOT_EMPTY_ATTR, 0) + switchbot.SetAttribute(self.selectedSlot, self.alternative, self.index, 0, 0) + self.__OnAttributeUpdate() + + def SetAttribute(self, applyname, maxValue): + self.typeTextLine.SetText(applyname) + self.valueEditLine.SetText(str(maxValue)) + + def GetIndex(self): + return self.index + +class SwitchbotWindow(ui.BoardWithTitleBar): + def __init__(self): + ui.BoardWithTitleBar.__init__(self) + try: + self.__Initialize() + self.__LoadWindow() + self.__BindEvents() + except: + import exception + exception.Abort("SwitchbotWindow.__init__") + + def __del__(self): + ui.BoardWithTitleBar.__del__(self) + + def __Initialize(self): + self.selectedSlot = 0 + self.alternative = 0 + + self.alternativeButtons = {} + self.itemTabs = {} + self.attrDict = {} + self.attrTab = None + + self.attributeSearchWindow = None + self.attrSearchIdx = -1 + + self.configurationSaveWindow = None + + self.topPanel = None + self.mainPanel = None + self.botPanel = None + + self.startButton = None + self.stopButton = None + + def Destroy(self): + ui.BoardWithTitleBar.Destroy(self) + for i in xrange(switchbot.SLOT_COUNT): + itemTab = self.itemTabs.get(i, None) + if not itemTab: + continue + itemTab.Destroy() + self.itemTabs = {} + if self.attrTab: + self.attrTab.Destroy() + self.attrTab = None + for i in xrange(ATTR_SLOT_COUNT): + itemTab = self.attrDict.get(i, None) + if not itemTab: + continue + itemTab.Destroy() + self.attrDict = {} + self.selectedSlot = 0 + self.alternative = 0 + self.alternativeButtons = {} + if self.attributeSearchWindow: + self.attributeSearchWindow.Destroy() + self.attributeSearchWindow = 0 + self.attrSearchIdx =0 + self.configurationSaveWindow = 0 + self.topPanel = 0 + self.mainPanel = 0 + self.alternativePanel = 0 + self.alternativeTextLine = 0 + self.botPanel = 0 + self.saveButton = 0 + self.startButton = 0 + self.stopButton = 0 + + def __LoadWindow(self): + self.AddFlag("movable") + self.SetSize(BOARD_WIDTH, BOARD_HEIGHT) + self.SetTitleName(localeInfo.SWITCHBOT_TITLE) + + self.topPanel = ui.ThinBoardCircle() + self.topPanel.SetParent(self) + self.topPanel.SetSize(TOP_PANEL_WIDTH, TOP_PANEL_HEIGHT) + self.topPanel.SetPosition(BORDER_SPACE, BORDER_SPACE_TOP) + self.topPanel.Show() + + for i in xrange(switchbot.SLOT_COUNT): + itemTab = SwitchbotItemTab(i) + itemTab.SetParent(self.topPanel) + itemTab.SetPosition((ITEM_TAB_WIDTH + ITEM_TAB_SPACE) * i, 0) + itemTab.SetOnSelectEvent(ui.__mem_func__(self.SelectSlot)) + itemTab.OnPlacedItem = self.__OnPlacedItem + itemTab.Show() + self.itemTabs[i] = itemTab + + + + self.mainPanel = ui.ThinBoardCircle() + self.mainPanel.SetParent(self) + self.mainPanel.SetSize(MAIN_PANEL_WIDTH, MAIN_PANEL_HEIGHT) + self.mainPanel.SetPosition(BORDER_SPACE, BORDER_SPACE_TOP + TOP_PANEL_HEIGHT) + self.mainPanel.Show() + + self.alternativePanel = ui.ThinBoardCircle() + self.alternativePanel.SetParent(self.mainPanel) + self.alternativePanel.SetSize(MAIN_PANEL_WIDTH, INPUT_HEIGHT) + self.alternativePanel.SetPosition(0, 0) + self.alternativePanel.Show() + + self.alternativeTextLine = ui.TextLine() + self.alternativeTextLine.SetParent(self.alternativePanel) + self.alternativeTextLine.SetPosition(5, -1) + self.alternativeTextLine.SetVerticalAlignCenter() + self.alternativeTextLine.SetWindowVerticalAlignCenter() + self.alternativeTextLine.SetText(localeInfo.SWITCHBOT_ALTERNATIVES) # PORT: AVA2 left this German + self.alternativeTextLine.Show() + + for i in xrange(switchbot.ALTERNATIVE_COUNT): + alternativeButton = ui.RadioButton() + alternativeButton.SetParent(self.alternativePanel) + alternativeButton.SetUpVisual("d:/ymir work/ui/switchbot/btn_small_01.sub") + alternativeButton.SetOverVisual("d:/ymir work/ui/switchbot/btn_small_02.sub") + alternativeButton.SetDownVisual("d:/ymir work/ui/switchbot/btn_small_03.sub") + alternativeButton.SetDisableVisual("d:/ymir work/ui/switchbot/btn_small_03.sub") + alternativeButton.SetWindowVerticalAlignCenter() + alternativeButton.SetPosition(80 + alternativeButton.GetWidth() * i, 0) + alternativeButton.SetText(str(i+1)) + alternativeButton.SetEvent(lambda arg = i : self.SelectAlternative(arg)) + alternativeButton.Show() + + self.alternativeButtons[i] = alternativeButton + + for i in xrange(ATTR_SLOT_COUNT): + attr = SwitchbotAttribute() + attr.SetParent(self.mainPanel) + attr.Create(MAIN_PANEL_WIDTH, i) + attr.SetPosition(0, INPUT_HEIGHT + (INPUT_HEIGHT * i)) + attr.SetSearchEvent(ui.__mem_func__(self.__OnSearchAttribute)) + attr.SetAttributeUpdateEvent(ui.__mem_func__(self.__OnAttributeUpdate)) + attr.SetEscapeEvent(ui.__mem_func__(self.Close)) + attr.Show() + + self.attrDict[i] = attr + + self.botPanel = ui.ThinBoardCircle() + self.botPanel.SetParent(self) + self.botPanel.SetSize(BOT_PANEL_WIDTH, BOT_PANEL_HEIGHT) + self.botPanel.SetPosition(BORDER_SPACE, BORDER_SPACE_TOP + TOP_PANEL_HEIGHT + MAIN_PANEL_HEIGHT) + self.botPanel.Show() + + self.saveButton = ui.Button() + self.saveButton.SetParent(self.botPanel) + self.saveButton.SetUpVisual("d:/ymir work/ui/switchbot/save_attr_01.sub") + self.saveButton.SetOverVisual("d:/ymir work/ui/switchbot/save_attr_02.sub") + self.saveButton.SetDownVisual("d:/ymir work/ui/switchbot/save_attr_03.sub") + self.saveButton.SetDisableVisual("d:/ymir work/ui/switchbot/save_attr_03.sub") + self.saveButton.SetWindowVerticalAlignCenter() + self.saveButton.SetPosition(BORDER_SPACE, 0) + self.saveButton.SetToolTipText(localeInfo.SWITCHBOT_SAVE_BUTTON) + self.saveButton.Show() + + self.startButton = ui.RadioButton() + self.startButton.SetParent(self.botPanel) + self.startButton.SetUpVisual("d:/ymir work/ui/switchbot/btn_big_01.sub") + self.startButton.SetOverVisual("d:/ymir work/ui/switchbot/btn_big_02.sub") + self.startButton.SetDownVisual("d:/ymir work/ui/switchbot/btn_big_03.sub") + self.startButton.SetDisableVisual("d:/ymir work/ui/switchbot/btn_big_03.sub") + self.startButton.SetWindowVerticalAlignCenter() + self.startButton.SetWindowHorizontalAlignCenter() + self.startButton.SetPosition(-self.startButton.GetWidth() / 2 - 10, 0) + self.startButton.SetText(localeInfo.SWITCHBOT_START) + self.startButton.Show() + + self.stopButton = ui.RadioButton() + self.stopButton.SetParent(self.botPanel) + self.stopButton.SetUpVisual("d:/ymir work/ui/switchbot/btn_big_01.sub") + self.stopButton.SetOverVisual("d:/ymir work/ui/switchbot/btn_big_02.sub") + self.stopButton.SetDownVisual("d:/ymir work/ui/switchbot/btn_big_03.sub") + self.stopButton.SetDisableVisual("d:/ymir work/ui/switchbot/btn_big_03.sub") + self.stopButton.SetWindowVerticalAlignCenter() + self.stopButton.SetWindowHorizontalAlignCenter() + self.stopButton.SetPosition(self.stopButton.GetWidth() / 2 + 20 - 25, 0) + self.stopButton.SetText(localeInfo.SWITCHBOT_STOP) + self.stopButton.Show() + + attrTab = SwitchbotItemTab(5, True) + attrTab.SetParent(self.botPanel) + attrTab.SetPosition((ITEM_TAB_WIDTH + ITEM_TAB_SPACE) * 4 + 35, 0) + #attrTab.SetOnSelectEvent(ui.__mem_func__(self.SelectSlot)) + #attrTab.OnPlacedItem = self.__OnPlacedItem + attrTab.Hide() # PORT: switchers stay in the inventory, cell 5 is unused (server port_switchbot.cpp) + self.attrTab = attrTab + + self.SelectSlot(0) + + def __BindEvents(self): + self.SetCloseEvent(ui.__mem_func__(self.Close)) + + self.startButton.SetEvent(lambda arg = True : self.SetActive(arg)) + self.stopButton.SetEvent(lambda arg = False : self.SetActive(arg)) + self.saveButton.SetEvent(ui.__mem_func__(self.OpenSaveConfiguration)) + + def Open(self): + self.Show() + self.SetTop() + self.SetCenterPosition() + self.RefreshSwitchbotWindow() + + def Close(self): + if self.attributeSearchWindow: + self.attributeSearchWindow.Close() + + if self.configurationSaveWindow: + self.configurationSaveWindow.Close() + + self.Hide() + return True + + def __OnPlacedItem(self, slot_num): + self.SelectSlot(slot_num) + + def SelectSlot(self, selectedSlot): + self.itemTabs[self.selectedSlot].SetUp() + self.selectedSlot = selectedSlot + self.itemTabs[self.selectedSlot].Down() + + self.SelectAlternative(0) + + def GetSelectedSlot(self): + return self.selectedSlot + + def SelectAlternative(self, alternative): + self.alternativeButtons[self.alternative].SetUp() + self.alternative = alternative + self.alternativeButtons[self.alternative].Down() + + self.RefreshSwitchbotWindow() + + def SetActive(self, active): + if self.selectedSlot >= switchbot.SLOT_COUNT: + return + + if active and self.IsActiveSlot(): + return + + if not active and not self.IsActiveSlot(): + return + + if active: + switchbot.Start(self.selectedSlot) + else: + switchbot.Stop(self.selectedSlot) + + def OpenSaveConfiguration(self): + if not self.configurationSaveWindow: + self.configurationSaveWindow = ConfigurationWindow(self) + + if self.configurationSaveWindow.IsShow(): + self.configurationSaveWindow.Close() + else: + self.configurationSaveWindow.Open() + + def SetItemToolTip(self, tooltipItem): + for i in xrange(switchbot.SLOT_COUNT): + self.itemTabs[i].SetItemToolTip(tooltipItem) + self.attrTab.SetItemToolTip(tooltipItem) + + def __AnyAttributeConfigured(self): + for i in xrange(switchbot.ALTERNATIVE_COUNT): + for j in xrange(ATTR_SLOT_COUNT): + (type, value) = switchbot.GetAttribute(self.selectedSlot, i, j) + if type and value: + return True + + return False + + def RefreshSwitchbotWindow(self): + self.__RefreshItemSlots() + self.__RefreshAlternatives() + self.__RefreshAttributeRows() + self.__RefreshButtons() + + def RefreshSwitchbotItem(self, slot): + if int(slot) == 5: + self.attrTab.RefreshItemSlot() + return + itemTab = self.itemTabs.get(slot, None) + if not itemTab: + return + + itemTab.RefreshItemSlot() + + def __RefreshItemSlots(self): + for i in xrange(switchbot.SLOT_COUNT): + itemTab = self.itemTabs.get(i, None) + if not itemTab: + continue + itemTab.RefreshItemSlot() + self.attrTab.RefreshItemSlot() + + def __RefreshAlternatives(self): + if self.IsEmptySlot(): + self.alternativePanel.Hide() + else: + self.alternativePanel.Show() + + def __RefreshAttributeRows(self): + for i in xrange(ATTR_SLOT_COUNT): + row = self.attrDict.get(i, None) + if not row: + continue + + (applyType, applyValue) = player.GetItemAttribute(player.SWITCHBOT, self.selectedSlot, i) + if applyType and applyValue: + row.Show() + else: + row.Hide() + + row.RefreshAttributeRow(self.selectedSlot, self.alternative, i) + + def __RefreshButtons(self): + if self.IsEmptySlot() or not self.__AnyAttributeConfigured(): + self.startButton.Disable() + self.stopButton.Disable() + return + + self.startButton.Enable() + self.stopButton.Enable() + + if self.IsActiveSlot(): + self.stopButton.SetUp() + self.startButton.Down() + else: + self.stopButton.Down() + self.startButton.SetUp() + + def __ClearAttributes(self): + + + for index, row in self.attrDict.iteritems(): + for alternative in xrange(switchbot.ALTERNATIVE_COUNT): + row.RefreshAttributeRow(self.selectedSlot, alternative, index) + + def __OnAttributeUpdate(self, attrIdx): + self.__RefreshButtons() + + def __OnSearchAttribute(self, attrIdx): + if self.attributeSearchWindow: + self.attributeSearchWindow.Close() + del self.attributeSearchWindow + + self.attrSearchIdx = attrIdx + + wnd = SearchListWindow() + width = 260 + height = 260 + wnd.MakeWindow(width, height) + wnd.SetTitleName(localeInfo.SWITCHBOT_SELECT_ATTR) + wnd.SetAcceptArgsType("KEY_VALUE") + + (mouseX, mouseY) = wndMgr.GetMousePosition() + + if mouseX + width/2 > wndMgr.GetScreenWidth(): + xPos = wndMgr.GetScreenWidth() - width + elif mouseX - width/2 < 0: + xPos = 0 + else: + xPos = mouseX - width/2 + + if mouseY + height/2 > wndMgr.GetScreenHeight(): + yPos = wndMgr.GetScreenHeight() - height + elif mouseY - height/2 < 0: + yPos = 0 + else: + yPos = mouseY - height/2 + + wnd.SetPosition(xPos, yPos) + + firstAttrType = player.GetItemAttribute(player.SWITCHBOT, self.selectedSlot, 0)[0] + if firstAttrType in ADDON_TYPES.keys(): + for addonType, maxValue in ADDON_TYPES.iteritems(): + affectString = GetAffectString(addonType, maxValue) + if not affectString: + continue + + wnd.AppendItem(addonType, affectString) + + attributes = switchbot.GetAttributesForSet(self.selectedSlot) + + selectedAttributes = [switchbot.GetAttribute(self.selectedSlot, self.alternative, attrIndex)[0] for attrIndex in xrange(ATTR_SLOT_COUNT)] + + for (type, value) in attributes: + if type in selectedAttributes: + continue + + affectString = GetAffectString(type, value) + if not affectString: + continue + + wnd.AppendItem(type, affectString) + + wnd.SetAcceptEvent(ui.__mem_func__(self.__OnAcceptSearch)) + wnd.SetCancelEvent(ui.__mem_func__(self.__OnCancelSearch)) + wnd.SetTop() + wnd.Open() + + self.attributeSearchWindow = wnd + + def __OnAcceptSearch(self, key, value): + if self.attrSearchIdx < 0 or self.attrSearchIdx >= ATTR_SLOT_COUNT: + return + + attrRow = self.attrDict.get(self.attrSearchIdx, None) + if not attrRow: + return + + maxValue = ADDON_TYPES.get(key, 0) + if not maxValue: + maxValue = switchbot.GetAttributeMaxValue(self.selectedSlot, key) + + attrRow.SetAttribute(value, maxValue) + switchbot.SetAttribute(self.selectedSlot, self.alternative, self.attrSearchIdx, key, maxValue) + + self.__RefreshButtons() + + def SetSavedAttribute(self, slot, alternative, attrIndex, attrType, attrValue): + if attrIndex < 0 or attrIndex >= ATTR_SLOT_COUNT: + return + + attrRow = self.attrDict.get(attrIndex, None) + if not attrRow: + return + + if slot >= switchbot.SLOT_COUNT: + return + + if switchbot.IsActive(slot): + return + + var = switchbot.GetAttributesForSet(slot) + attributes = [var[i][0] for i in xrange(len(var))] + + firstAttrType = player.GetItemAttribute(player.SWITCHBOT, slot, 0)[0] + if firstAttrType in ADDON_TYPES.keys(): + for addon in ADDON_TYPES.keys(): + attributes.append(addon) + + if not attrType in attributes: + switchbot.SetAttribute(slot, alternative, attrIndex, 0, 0) + else: + switchbot.SetAttribute(slot, alternative, attrIndex, attrType, attrValue) + + self.RefreshSwitchbotWindow() + + def IsEmptySlot(self): + slot = self.itemTabs.get(self.selectedSlot, None) + if not slot: + return True + + return slot.IsEmpty() + + def IsActiveSlot(self): + slot = self.itemTabs.get(self.selectedSlot, None) + if not slot: + return False + + return slot.IsActive() + + def GetSlotAttributeCount(self): + slot = self.itemTabs.get(self.selectedSlot, None) + if not slot: + return 0 + + return slot.GetAttributeCount() + + def OnMoveWindow(self, x, y): + if self.configurationSaveWindow: + self.configurationSaveWindow.AdjustPosition() + + def __OnCancelSearch(self): + pass + + def OnPressEscapeKey(self): + self.Close() + return True + +class SearchListWindow(ui.BoardWithTitleBar): + class SearchListItem(ui.Window): + LIST_ITEM_HEIGHT = 12 + + def __init__(self, key, value): + ui.Window.__init__(self) + + self.key = key + self.value = value + self.isDown = False + self.onClickEvent = None + + self.textLine = ui.TextLine() + self.textLine.AddFlag("not_pick") + self.textLine.SetParent(self) + self.textLine.SetVerticalAlignCenter() + self.textLine.SetWindowVerticalAlignCenter() + self.textLine.SetPosition(10, -1) + self.textLine.SetText(str(value)) + self.textLine.UpdateRect() + self.textLine.Show() + + def __del__(self): + ui.Window.__del__(self) + + def Destroy(self): + self.key = 0 + self.value = 0 + self.onClickEvent = 0 + self.textLine = 0 + self.LIST_ITEM_HEIGHT = 0 + + def OnMouseLeftButtonUp(self): + if not self.isDown: + self.__OnClick() + self.Down() + + def OnRender(self): + if self.IsIn() or self.isDown: + self.RenderHoverOrSelected() + + def RenderHoverOrSelected(self): + x, y = self.GetGlobalPosition() + grp.SetColor(grp.GenerateColor(0.0, 0.0, 0.7, 0.7)) + grp.RenderBar(x, y, self.GetWidth(), self.GetHeight()) + + def SetUp(self): + self.isDown = False + + def Down(self): + self.isDown = True + + def IsDown(self): + return self.isDown + + def GetKey(self): + return self.key + + def GetValue(self): + return self.value + + def GetText(self): + return self.textLine.GetText() + + def MatchText(self, text): + return text in self.GetText() + + def SetOnClickEvent(self, event): + self.onClickEvent = ui.__mem_func__(event) + + def __OnClick(self): + if self.onClickEvent: + self.onClickEvent(self.key, self.value) + + def __init__(self): + ui.BoardWithTitleBar.__init__(self) + self.AddFlag("attach") + self.AddFlag("movable") + + self.__Initialize() + + def __del__(self): + ui.BoardWithTitleBar.__del__(self) + + def Destroy(self): + ui.BoardWithTitleBar.Destroy(self) + self.listItems =0 + self.acceptEvent = 0 + self.acceptArgsType = 0 + self.cancelEvent = 0 + self.searchInput = 0 + self.searchEditLine = 0 + self.scrollBar = 0 + self.container.Destroy() + self.container = 0 + self.listBox.RemoveAllItems() + self.listBox = 0 + self.acceptButton = 0 + self.cancelButton = 0 + + def __Initialize(self): + self.listItems = {} + self.acceptEvent = None + self.acceptArgsType = "VALUE" + self.cancelEvent = None + + def MakeWindow(self, width, height, maxInput = 50): + self.SetSize(width, height) + + self.searchInput = ui.ThinBoardCircle() + self.searchInput.SetParent(self) + self.searchInput.SetSize(width - (BORDER_SPACE*2), INPUT_HEIGHT) + self.searchInput.SetPosition(BORDER_SPACE, BORDER_SPACE_TOP) + self.searchInput.Show() + + self.searchEditLine = ui.EditLine() + self.searchEditLine.SetParent(self.searchInput) + self.searchEditLine.SetPosition(10, 8) + self.searchEditLine.SetSize(self.searchInput.GetWidth() - 20, self.searchInput.GetHeight() - 16) + self.searchEditLine.SetMax(maxInput) + self.searchEditLine.SetReturnEvent(ui.__mem_func__(self.__OnAccept)) + self.searchEditLine.SetEscapeEvent(ui.__mem_func__(self.Close)) + self.searchEditLine.OnIMEUpdate = self.__OnSearchIMEUpdate + self.searchEditLine.Show() + + containerHeight = height - (BORDER_SPACE_TOP + INPUT_HEIGHT + 30) + + self.scrollBar = ui.ScrollBar() + self.scrollBar.SetParent(self) + self.scrollBar.SetWindowHorizontalAlignRight() + self.scrollBar.SetPosition(23, BORDER_SPACE_TOP + INPUT_HEIGHT + 2) + self.scrollBar.SetScrollBarSize(containerHeight - 4) + + self.container = ui.ThinBoardCircle() + self.container.SetParent(self) + self.container.SetPosition(BORDER_SPACE, BORDER_SPACE_TOP + INPUT_HEIGHT) + self.container.SetSize(width - (BORDER_SPACE*2), containerHeight) + self.container.Show() + + listBoxHeight = self.container.GetHeight() + listBoxWidth = self.container.GetWidth() + + self.listBox = ui.ListBoxEx() + self.listBox.SetParent(self.container) + self.listBox.SetPosition(2, 2) + self.listBox.SetSize(listBoxWidth, listBoxHeight) + self.listBox.SetItemStep(self.SearchListItem.LIST_ITEM_HEIGHT) + self.listBox.SetViewItemCount(self.__GetViewItemCount()) + self.listBox.SetItemSize(listBoxWidth, self.SearchListItem.LIST_ITEM_HEIGHT) + self.listBox.SetScrollBar(self.scrollBar) + self.listBox.Show() + + buttonWidth = width / 2 - 20 + + self.acceptButton = ui.Button() + self.acceptButton.SetParent(self) + self.acceptButton.SetUpVisual("d:/ymir work/ui/public/large_button_01.sub") + self.acceptButton.SetOverVisual("d:/ymir work/ui/public/large_button_02.sub") + self.acceptButton.SetDownVisual("d:/ymir work/ui/public/large_button_03.sub") + self.acceptButton.SetDisableVisual("d:/ymir work/ui/public/large_button_03.sub") + self.acceptButton.SetWindowVerticalAlignBottom() + self.acceptButton.SetWindowHorizontalAlignCenter() + self.acceptButton.SetPosition(-buttonWidth / 2 - 5, 29) + self.acceptButton.SetText(localeInfo.UI_ACCEPT) + self.acceptButton.SetEvent(ui.__mem_func__(self.__OnAccept)) + self.acceptButton.Show() + + self.cancelButton = ui.Button() + self.cancelButton.SetParent(self) + self.cancelButton.SetUpVisual("d:/ymir work/ui/public/large_button_01.sub") + self.cancelButton.SetOverVisual("d:/ymir work/ui/public/large_button_02.sub") + self.cancelButton.SetDownVisual("d:/ymir work/ui/public/large_button_03.sub") + self.cancelButton.SetDisableVisual("d:/ymir work/ui/public/large_button_03.sub") + self.cancelButton.SetWindowVerticalAlignBottom() + self.cancelButton.SetWindowHorizontalAlignCenter() + self.cancelButton.SetPosition(buttonWidth / 2 - 5, 29) + self.cancelButton.SetText(localeInfo.UI_CANCEL) + self.cancelButton.SetEvent(ui.__mem_func__(self.__OnCancel)) + self.cancelButton.Show() + + self.__AdjustScrollbar() + + def __OnSearchIMEUpdate(self): + ui.EditLine.OnIMEUpdate(self.searchEditLine) + self.__RefreshListBox() + + def __GetViewItemCount(self): + return self.container.GetHeight() / self.SearchListItem.LIST_ITEM_HEIGHT + + def __AdjustScrollbar(self): + if len(self.listBox.GetItems()) > self.__GetViewItemCount(): + listBoxWidth = self.GetWidth() - (BORDER_SPACE*2) - 20 + self.container.SetSize(listBoxWidth, self.container.GetHeight()) + self.listBox.SetSize(listBoxWidth - 4, self.listBox.GetHeight() - 4) + self.listBox.SetItemSize(listBoxWidth - 4, self.SearchListItem.LIST_ITEM_HEIGHT) + attachmentCount = len(self.listBox.GetItems()) + scrollBarHeight = min(float(self.__GetViewItemCount()) / float(attachmentCount), 1.0) + self.scrollBar.SetMiddleBarSize(scrollBarHeight) + self.scrollBar.Show() + else: + listBoxWidth = self.GetWidth() - (BORDER_SPACE*2) + self.container.SetSize(listBoxWidth, self.container.GetHeight()) + self.listBox.SetSize(listBoxWidth - 4, self.listBox.GetHeight() - 4) + self.listBox.SetItemSize(listBoxWidth - 4, self.SearchListItem.LIST_ITEM_HEIGHT) + self.scrollBar.Hide() + + def RemoveAllItems(self): + self.listItems = {} + self.listBox.RemoveAllItems() + + def AppendItem(self, key, value = ""): + if self.listItems.has_key(key): + return + + if not value: + value = key + + self.listItems[key] = { "value" : value, "item" : None, } + self.__RefreshListBox() + + def __RefreshListBox(self): + self.listBox.RemoveAllItems() + + keys = sorted(self.listItems.iterkeys()) + + for key in keys: + dict = self.listItems.get(key, None) + if not dict: + continue + + listItem = dict["item"] + + if not self.searchEditLine.GetText() or self.searchEditLine.GetText().lower() in dict["value"].lower(): + listItem = self.SearchListItem(key, dict["value"]) + listItem.SetOnClickEvent(self.__OnClickListItem) + self.listBox.AppendItem(listItem) + else: + del listItem + + self.__AdjustScrollbar() + + def GetSelectedItem(self): + for listItem in self.listBox.GetItems(): + if listItem.IsDown(): + return listItem + + return None + + def SetCancelEvent(self, event): + self.cancelEvent = event + + def SetAcceptEvent(self, event): + self.acceptEvent = event + + def SetAcceptArgsType(self, type): + self.acceptArgsType = type + + def __OnClickListItem(self, key, value): + curItem = self.GetSelectedItem() + if curItem: + curItem.SetUp() + + def __OnCancel(self): + if self.cancelEvent: + self.cancelEvent() + + self.Close() + + def __OnAccept(self): + selItem = self.GetSelectedItem() + if not selItem: + if len(self.listBox.GetItems()) == 1: + selItem = self.listBox.GetItems()[0] + else: + return + + if self.acceptEvent: + if self.acceptArgsType == "VALUES": + self.acceptEvent(selItem.GetValue()) + elif self.acceptArgsType == "KEY": + self.acceptEvent(selItem.GetKey()) + elif self.acceptArgsType == "KEY_VALUE": + self.acceptEvent(selItem.GetKey(), selItem.GetValue()) + + self.Close() + + def OnPressEscapeKey(self): + self.Close() + return True + + def Open(self): + self.Show() + self.searchEditLine.SetFocus() + + def Close(self): + self.searchEditLine.SetText("") + self.searchEditLine.KillFocus() + self.Hide() + +class ConfigurationWindow(ui.BoardWithTitleBar): + BOARD_WIDTH = 250 + + class ConfigurationLine(ui.Window): + LIST_ITEM_HEIGHT = 26 + + id = 0 + name = "" + + loadEvent = None + deleteEvent = None + + def __init__(self, width): + ui.Window.__init__(self) + + self.SetSize(width, 26) + + self.nameTextLine = ui.TextLine() + self.nameTextLine.SetParent(self) + self.nameTextLine.SetVerticalAlignCenter() + self.nameTextLine.SetWindowVerticalAlignCenter() + self.nameTextLine.SetPosition(5, -1) + self.nameTextLine.Show() + + self.loadButton = ui.Button() + self.loadButton.SetParent(self) + self.loadButton.SetUpVisual("d:/ymir work/ui/switchbot/load_attr_01.sub") + self.loadButton.SetOverVisual("d:/ymir work/ui/switchbot/load_attr_02.sub") + self.loadButton.SetDownVisual("d:/ymir work/ui/switchbot/load_attr_03.sub") + self.loadButton.SetDisableVisual("d:/ymir work/ui/switchbot/load_attr_03.sub") + self.loadButton.SetWindowHorizontalAlignRight() + self.loadButton.SetWindowVerticalAlignCenter() + self.loadButton.SetPosition(24 * 2 + 2, 1) + self.loadButton.SetToolTipText(localeInfo.SWITCHBOT_LOAD_CONFIGURATION) + self.loadButton.SetEvent(ui.__mem_func__(self.__OnClickLoadButton)) + self.loadButton.Show() + + self.deleteButton = ui.Button() + self.deleteButton.SetParent(self) + self.deleteButton.SetUpVisual("d:/ymir work/ui/switchbot/delete_attr_01.sub") + self.deleteButton.SetOverVisual("d:/ymir work/ui/switchbot/delete_attr_02.sub") + self.deleteButton.SetDownVisual("d:/ymir work/ui/switchbot/delete_attr_03.sub") + self.deleteButton.SetDisableVisual("d:/ymir work/ui/switchbot/delete_attr_03.sub") + self.deleteButton.SetWindowHorizontalAlignRight() + self.deleteButton.SetWindowVerticalAlignCenter() + self.deleteButton.SetPosition(24 + 2, 1) + self.deleteButton.SetToolTipText(localeInfo.SWITCHBOT_CLEAR_CONFIGURATION) + self.deleteButton.SetEvent(ui.__mem_func__(self.__OnClickDeleteButton)) + self.deleteButton.Show() + + def __del__(self): + ui.Window.__del__(self) + + def Destroy(self): + self.LIST_ITEM_HEIGHT = 0 + self.id = 0 + self.name = 0 + self.loadEvent = 0 + self.deleteEvent = 0 + self.nameTextLine = 0 + self.loadButton = 0 + self.deleteButton = 0 + + def Load(self, id, name): + self.id = id + self.name = name + self.nameTextLine.SetText(name) + + def SetLoadEvent(self, event): + self.loadEvent = event + + def SetDeleteEvent(self, event): + self.deleteEvent = event + + def __OnClickLoadButton(self): + if self.loadEvent: + self.loadEvent(self.id) + + def __OnClickDeleteButton(self): + if self.deleteEvent: + self.deleteEvent(self.id) + + wndSwitchbot = None + + nameInput = None + valueEditLine = None + + dict = {} + + listItems = {} + + def __init__(self, wndSwitchbot=None): + ui.BoardWithTitleBar.__init__(self) + + if not wndSwitchbot: + import exception + exception.Abort("ConfigurationWindow.__init__ Cannot initialize without binding to Switchbot window.") + + self.wndSwitchbot = wndSwitchbot + + self.__LoadWindow() + + def __del__(self): + ui.BoardWithTitleBar.__del__(self) + + def Destroy(self): + self.wndSwitchbot = None + self.saveButton = None + self.nameInput = None + self.nameEditLine = None + self.valueEditLine = None + self.scrollBar = None + self.container = None + self.listBox.RemoveAllItems() + self.listBox = None + for key in self.listItems.iterkeys(): + config = self.listItems.get(key, None) + if not config: + continue + config.Destroy() + self.dict = {} + self.listItems = {} + ui.BoardWithTitleBar.Destroy(self) + self.BOARD_WIDTH = 0 + + def __LoadWindow(self): + self.SetSize(self.BOARD_WIDTH, BOARD_HEIGHT) + self.SetTitleName(localeInfo.SWITCHBOT_CONFIGURATION_TITLE) + self.SetCloseEvent(ui.__mem_func__(self.Close)) + self.AddFlag("attach") + # self.AddFlag("movable") + + self.saveButton = ui.Button() + self.saveButton.SetParent(self) + self.saveButton.SetUpVisual("d:/ymir work/ui/switchbot/btn_small_01.sub") + self.saveButton.SetOverVisual("d:/ymir work/ui/switchbot/btn_small_02.sub") + self.saveButton.SetDownVisual("d:/ymir work/ui/switchbot/btn_small_03.sub") + self.saveButton.SetDisableVisual("d:/ymir work/ui/switchbot/btn_small_01.sub") + self.saveButton.SetWindowHorizontalAlignRight() + self.saveButton.SetPosition(self.saveButton.GetWidth() + BORDER_SPACE, BORDER_SPACE_TOP + 3) + self.saveButton.SetText(localeInfo.SWITCHBOT_SAVE) + self.saveButton.SetEvent(ui.__mem_func__(self.__OnSave)) + self.saveButton.Show() + + self.nameInput = ui.ThinBoardCircle() + self.nameInput.SetParent(self) + self.nameInput.SetSize(self.BOARD_WIDTH - (BORDER_SPACE * 2) - self.saveButton.GetWidth() - 3, INPUT_HEIGHT) + self.nameInput.SetPosition(BORDER_SPACE, BORDER_SPACE_TOP) + self.nameInput.Show() + + self.nameEditLine = ui.EditLine() + self.nameEditLine.SetParent(self.nameInput) + self.nameEditLine.SetSize(self.nameInput.GetWidth() - 20, 18) + self.nameEditLine.SetMax(32) + self.nameEditLine.SetPosition(10, 7) + self.nameEditLine.Show() + self.nameEditLine.SetEscapeEvent(ui.__mem_func__(self.__OnEscapeEvent)) + + height = BOARD_HEIGHT - BORDER_SPACE_TOP - INPUT_HEIGHT - BORDER_SPACE + + self.scrollBar = ui.ScrollBar() + self.scrollBar.SetParent(self) + self.scrollBar.SetWindowHorizontalAlignRight() + self.scrollBar.SetPosition(23, BORDER_SPACE_TOP + INPUT_HEIGHT + 2) + self.scrollBar.SetScrollBarSize(height - 4) + + self.container = ui.ThinBoardCircle() + self.container.SetParent(self) + self.container.SetPosition(BORDER_SPACE, BORDER_SPACE_TOP + INPUT_HEIGHT) + self.container.SetSize(BOARD_WIDTH - (BORDER_SPACE*2), height) + self.container.Show() + + listBoxHeight = self.container.GetHeight() + listBoxWidth = self.container.GetWidth() + + self.listBox = ui.ListBoxEx() + self.listBox.SetParent(self.container) + self.listBox.SetPosition(2, 2) + self.listBox.SetSize(listBoxWidth, listBoxHeight) + self.listBox.SetItemStep(self.ConfigurationLine.LIST_ITEM_HEIGHT + 1) + self.listBox.SetViewItemCount(self.__GetViewItemCount()) + self.listBox.SetItemSize(listBoxWidth, self.ConfigurationLine.LIST_ITEM_HEIGHT) + self.listBox.SetScrollBar(self.scrollBar) + self.listBox.Show() + + self.__AdjustScrollbar() + + def LoadConfigurations(self): + try: + f = open(constInfo.USERDATA_DIRECTORY+'switchbot.inf', 'rb') + self.dict = pickle.load(f) + f.close() + except IOError: + self.dict = {} + + self.listBox.RemoveAllItems() + + lineWidth = self.listBox.GetWidth() + if len(self.dict) > self.__GetViewItemCount(): + lineWidth -= 20 + + self.__AdjustScrollbar() + + for key in self.dict.iterkeys(): + config = self.dict.get(key, None) + if not config: + continue + + line = self.ConfigurationLine(lineWidth) + line.Load(key, config["name"]) + line.SetLoadEvent(ui.__mem_func__(self.__OnApplyConfiguration)) + line.SetDeleteEvent(ui.__mem_func__(self.__OnDeleteConfiguration)) + self.listBox.AppendItem(line) + + self.listItems[key] = line + + def SaveConfigurations(self): + with open(constInfo.USERDATA_DIRECTORY+'switchbot.inf', 'wb') as f: + pickle.dump(self.dict, f) + + def __OnApplyConfiguration(self, key): + config = self.dict.get(key, None) + if not config: + return + + if not self.wndSwitchbot: + return + + selectedSlot = self.wndSwitchbot.GetSelectedSlot() + for alternativeIdx in xrange(len(config["alternatives"])): + alternative = config["alternatives"][alternativeIdx] + for attrIdx in xrange(len(alternative)): + (attrType, attrValue) = alternative[attrIdx] + self.wndSwitchbot.SetSavedAttribute(selectedSlot, alternativeIdx, attrIdx, attrType, attrValue) + + def __OnDeleteConfiguration(self, key): + config = self.dict.get(key, None) + if not config: + return + + del self.listItems[key] + del self.dict[key] + self.SaveConfigurations() + self.LoadConfigurations() + + def Open(self): + self.Show() + self.LoadConfigurations() + self.AdjustPosition() + + def Close(self): + self.Hide() + + def AdjustPosition(self): + if not self.wndSwitchbot: + return + + (x, y) = self.wndSwitchbot.GetGlobalPosition() + self.SetPosition(x - self.GetWidth(), y) + + def __GetViewItemCount(self): + return self.container.GetHeight() / (self.ConfigurationLine.LIST_ITEM_HEIGHT + 1) + + def __AdjustScrollbar(self): + if len(self.dict) > self.__GetViewItemCount(): + listBoxWidth = self.GetWidth() - (BORDER_SPACE*2) - 20 + self.container.SetSize(listBoxWidth, self.container.GetHeight()) + self.listBox.SetSize(listBoxWidth - 4, self.listBox.GetHeight() - 4) + self.listBox.SetItemSize(listBoxWidth - 4, self.ConfigurationLine.LIST_ITEM_HEIGHT) + attachmentCount = len(self.dict) + scrollBarHeight = min(float(self.__GetViewItemCount()) / float(attachmentCount), 1.0) + self.scrollBar.SetMiddleBarSize(scrollBarHeight) + self.scrollBar.Show() + else: + listBoxWidth = self.GetWidth() - (BORDER_SPACE*2) + self.container.SetSize(listBoxWidth, self.container.GetHeight()) + self.listBox.SetSize(listBoxWidth - 4, self.listBox.GetHeight() - 4) + self.listBox.SetItemSize(listBoxWidth - 4, self.ConfigurationLine.LIST_ITEM_HEIGHT) + self.scrollBar.Hide() + + def __OnEscapeEvent(self): + self.Close() + + def __GetNewKey(self): + key = 0 + while self.dict.has_key(key): + key += 1 + + return key + + def __BuildDict(self, slot, name): + key = self.__GetNewKey() + alternatives = [] + for alternative in xrange(switchbot.ALTERNATIVE_COUNT): + attributes = [switchbot.GetAttribute(slot, alternative, i) for i in xrange(player.ATTRIBUTE_SLOT_MAX_NUM)] + alternatives.append(attributes) + + new_dict = { + "name" : name, + "alternatives" : alternatives, + } + + return (key, new_dict) + + def __OnSave(self): + if not self.wndSwitchbot: + return + + selectedSlot = self.wndSwitchbot.GetSelectedSlot() + name = self.nameEditLine.GetText() + + if not name: + return + + (key, new_dict) = self.__BuildDict(selectedSlot, name) + self.dict[key] = new_dict + + self.nameEditLine.SetText("") + + self.SaveConfigurations() + self.LoadConfigurations() -class Bot(object): - # Protocol state only; the window renders it. send(text) posts a chat command, now() is seconds. - def __init__(self,send,now,listener=None): - self.send=send;self.now=now;self.listener=listener - self.queue=[];self.nextSend=0;self.waiting=None - self.allowed={};self.locks={};self.loading=None;self.state=None;self.error=None;self.unsupported=False +# --- uitooltip.py SetSwitchBotItem ---------------------------------------------------------------------------- +def SetSwitchBotItem(self, vnum): + item.SelectItem(vnum) + self.AppendTextLine(item.GetItemName(), self.SPECIAL_TITLE_COLOR) + self.AppendSpace(5) + itemDesc = localeInfo.SWITCHBOT_ACTIVE + self._ItemToolTip__AdjustMaxWidth(0, itemDesc) + self.AppendDescription(itemDesc, 26) - def Enqueue(self,verb,text): - if verb=='attrs' and self.waiting and self.waiting[2]==text:return - self.queue=[q for q in self.queue if not (verb=='attrs' and q[0]=='attrs')] - if len(self.queue)<4:self.queue.append((verb,text)) - self.Tick() - - def RequestAttrs(self,cell): - self.Enqueue('attrs','/mt_switchbot 1 attrs %d'%cell) - - def Start(self,cell,scroll,limit,alternatives): - groups=[a for a in alternatives if a] - if not groups or len(groups)>2 or not 1<=limit<=1000:return 'invalid' - allowed=dict(self.allowed.get(cell,{}).get('rows',())) - parts=['/mt_switchbot 1 start %d %d %d'%(cell,scroll,limit)] - for targets in groups: - if len(targets)>MAX_TARGETS or len(set(a for a,v in targets))!=len(targets):return 'invalid' - parts.append(str(len(targets))) - for apply,value in targets: - if apply not in allowed or not 1<=value<=allowed[apply]:return 'target' - parts.append('%d %d'%(apply,value)) - self.error=None;self.Enqueue('start',' '.join(parts));return None - - def Lock(self,cell,slot): - if not 0<=slot<5 or cell not in self.locks:return - self.error=None;self.Enqueue('lock','/mt_switchbot 1 lock %d %d'%(cell,slot)) - - def LockMask(self,cell,vnum): - lock=self.locks.get(cell) - return lock[1] if lock and lock[0]==vnum else None - - def Stop(self):self.Enqueue('stop','/mt_switchbot 1 stop') - def Status(self):self.Enqueue('status','/mt_switchbot 1 status') - def Running(self):return bool(self.state and self.state['active']) - - def Tick(self): - now=self.now() - if self.waiting and now>=self.waiting[1]: - self.waiting=None;self.queue=[];self.loading=None;self.unsupported=True;self.error='unsupported';self.Notify('error') - if self.queue and not self.waiting and now>=self.nextSend: - verb,text=self.queue.pop(0);self.send(text);self.nextSend=now+SEND_GAP - self.waiting=(verb,now+TIMEOUT,text) - - def Answered(self,verb): - if self.waiting and (self.waiting[0]==verb or verb in ('state','error')):self.waiting=None - self.unsupported=False - - def Notify(self,kind): - if self.listener:self.listener(kind) - - def Receive(self,line): - if not line.startswith('MTSB1 '):return False - words=line.split() - try:self.Parse(words[1:]) - except (ValueError,IndexError,KeyError):self.loading=None - return True - - def Parse(self,words): - kind=words[0] - if kind=='attrs': - self.loading=dict(cell=Number(words[1]),vnum=Number(words[2]),count=Number(words[3],0,255),rows=[]) - elif kind=='attr': - row=self.loading;index=Number(words[1]) - if not row or index!=len(row['rows']) or index>=row['count']:raise ValueError('order') - row['rows'].append((Number(words[2],0,255),Number(words[3],1,2147483647))) - elif kind=='attrs_end': - row=self.loading;self.loading=None - if not row or Number(words[1])!=row['cell'] or Number(words[2])!=row['count'] or len(row['rows'])!=row['count']: - raise ValueError('partial') - self.allowed[row['cell']]=row;self.Answered('attrs');self.Notify('attrs') - elif kind=='lock': - # Follows attrs_end (and answers lock). Servers without the lock never send it, so no buttons show. - if len(words)!=4:raise ValueError('lock') - self.locks[Number(words[1])]=(Number(words[2]),Number(words[3],0,31));self.Answered('lock');self.Notify('lock') - elif kind=='state': - if len(words)!=9 or words[8] not in REASONS:raise ValueError('state') - self.state=dict(active=Number(words[1],0,1)==1,cell=Number(words[2]),vnum=Number(words[3]),rolls=Number(words[4]), - limit=Number(words[5]),scroll=Number(words[6]),scrolls=Number(words[7]),reason=words[8]) - self.Answered('state');self.Notify('state') - elif kind=='error': - if len(words)!=3 or words[2] not in ERRORS:raise ValueError('error') - if words[1]=='attrs':self.loading=None - self.error=words[2];self.Answered('error');self.Notify('error') +ItemToolTip.SetSwitchBotItem=SetSwitchBotItem -def ItemName(vnum): - item.SelectItem(vnum);return item.GetItemName() +# --- mouseModule.py: SLOT_TYPE_SWITCHBOT carries an item icon like the inventory ------------------------------- +_attach=mouseModule.CMouseController.AttachObject +_deattach=mouseModule.CMouseController.DeattachObject + +def AttachObject(self, Owner, Type, SlotNumber, ItemIndex, count = 0): + if Type!=player.SLOT_TYPE_SWITCHBOT:return _attach(self,Owner,Type,SlotNumber,ItemIndex,count) + _attach(self,Owner,player.SLOT_TYPE_INVENTORY,SlotNumber,ItemIndex,count) + if not self.AttachedFlag:return + self.AttachedType=Type + item.SelectItem(ItemIndex) + (width,height)=item.GetItemSize() + wndMgr.AttachIcon(Type,ItemIndex,SlotNumber,width,height) + +def DeattachObject(self): + if self.AttachedType==player.SLOT_TYPE_SWITCHBOT and self.AttachedIconHandle: + item.DeleteIconInstance(self.AttachedIconHandle);self.AttachedIconHandle=0 + return _deattach(self) + +mouseModule.CMouseController.AttachObject=AttachObject +mouseModule.CMouseController.DeattachObject=DeattachObject -def AffectText(apply,value): - affect=getattr(uiToolTip.ItemToolTip,'AFFECT_DICT',{}).get(apply) - try: - if affect:return affect(value) - except (TypeError,ValueError):pass - return L(B(u'属性#%d +%d'%(apply,value))) +# --- uiinventory.py: an item dragged out of the switchbot window goes back to the inventory -------------------- +_selectEmpty=uiInventory.InventoryWindow.SelectEmptySlot + +def SelectEmptySlot(self, selectedSlotPos): + mouse=mouseModule.mouseController + if constInfo.GET_ITEM_QUESTION_DIALOG_STATUS()!=1 and mouse.isAttached() and mouse.GetAttachedType()==player.SLOT_TYPE_SWITCHBOT: + cell=self._InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos(selectedSlotPos) + net.SendItemMovePacket(player.SWITCHBOT,mouse.GetAttachedSlotNumber(),player.INVENTORY,cell,mouse.GetAttachedItemCount()) + mouse.DeattachObject() + return + return _selectEmpty(self,selectedSlotPos) + +uiInventory.InventoryWindow.SelectEmptySlot=SelectEmptySlot -def Step(maximum):return max(1,maximum//5) - - -class SwitchbotWindow(ui.Window): - def __init__(self): - ui.Window.__init__(self);self.SetWindowName('SwitchbotWindow');self.AddFlag('float');self.AddFlag('movable') - self.bot=Bot(net.SendChatPacket,app.GetTime,self.OnBot) - self.items=[];self.itemIndex=0;self.scrolls=[];self.scrollIndex=0;self.limitIndex=2 - self.alternatives=[[],[]];self.alt=0;self.picking=False;self.pickPage=0;self.dimensions=None;self.nextScan=0 - self.heading=Text(self,18,18,'自动洗练',0xffffd68b) - self.closeButton=Action(self,0,6,60,'关闭',self.Hide) - self.itemPrev=Action(self,18,58,48,'<',lambda:self.Cycle('item',-1));self.itemNext=Action(self,0,58,48,'>',lambda:self.Cycle('item',1)) - self.itemText=Text(self,80,82,'') - self.scrollPrev=Action(self,18,110,48,'<',lambda:self.Cycle('scroll',-1));self.scrollNext=Action(self,0,110,48,'>',lambda:self.Cycle('scroll',1)) - self.scrollText=Text(self,80,134,'') - self.limitButton=Action(self,0,110,110,'',self.NextLimit) - self.altButtons=[Action(self,18+i*104,162,96,'方案一' if i==0 else '方案二',lambda i=i:self.SelectAlt(i)) for i in range(2)] - self.addButton=Action(self,0,162,110,'添加属性',self.TogglePick) - self.rows=[] - for i in range(MAX_TARGETS): - y=214+i*46 - self.rows.append(dict(text=Text(self,24,y+22,''),minus=Action(self,0,y,44,'-',lambda i=i:self.Adjust(i,-1)), - plus=Action(self,0,y,44,'+',lambda i=i:self.Adjust(i,1)),remove=Action(self,0,y,44,'×',lambda i=i:self.Remove(i)), - pick=Action(self,18,y,100,'',lambda i=i:self.Pick(i)))) - self.pickPrev=Action(self,18,0,80,'上一页',lambda:self.PickPage(-1));self.pickNext=Action(self,0,0,80,'下一页',lambda:self.PickPage(1)) - self.startButton=Action(self,18,0,120,'开始洗练',self.Start);self.stopButton=Action(self,146,0,120,'停止',self.bot.Stop) - self.lockButtons=[Action(self,0,0,40,'',lambda i=i:self.ToggleLock(i)) for i in range(5)] - self.status=Text(self,18,0,'',0xffc3b7a1);self.current=Text(self,18,0,'',0xffefdfc3) - self.Reflow();self.Hide() - - def Buttons(self): - rows=[b for r in self.rows for b in (r['minus'],r['plus'],r['remove'],r['pick'])] - return [self.closeButton,self.itemPrev,self.itemNext,self.scrollPrev,self.scrollNext,self.limitButton,self.addButton, - self.pickPrev,self.pickNext,self.startButton,self.stopButton]+self.altButtons+self.lockButtons+rows - - def Open(self): - self.Reflow();self.Scan();self.SetCenterPosition();self.Show();self.SetTop();self.bot.Status();self.RequestAttrs() - - def Scan(self): - items=[];scrolls={} - for cell in range(player.INVENTORY_PAGE_SIZE*player.INVENTORY_PAGE_COUNT): - vnum=player.GetItemIndex(player.INVENTORY,cell) - if not vnum:continue - item.SelectItem(vnum);kind=item.GetItemType() - # 54001-54267 with a value2 mask are AVA2 costume enchants (mt_costume_attr), 71302 / 53996 talisman - # rerolls (mt_pendant) and 50348 / 50349 attribute lock materials, not switchers; talismans have their own attribute pool. - if kind==item.ITEM_TYPE_USE and item.GetItemSubType()==USE_CHANGE_ATTRIBUTE and not (54001<=vnum<=54267 and item.GetValue(2)) and vnum not in (71302,53996,50348,50349): - scrolls[vnum]=scrolls.get(vnum,0)+player.GetItemCount(player.INVENTORY,cell) - elif kind in (item.ITEM_TYPE_WEAPON,item.ITEM_TYPE_ARMOR) and not (kind==item.ITEM_TYPE_ARMOR and item.GetItemSubType()==item.ARMOR_PENDANT) and any(player.GetItemAttribute(player.INVENTORY,cell,i)[0] for i in range(5)): - items.append((cell,vnum)) - selected=self.Selected();scroll=self.Scroll();state=self.bot.state - if state and state['active'] and (state['cell'],state['vnum']) in items: - # The server binds the bot to the item ID and reports its current cell; follow it after a move. - if selected and selected[0] in self.bot.allowed and selected[1]==state['vnum']: - self.bot.allowed[state['cell']]=dict(self.bot.allowed[selected[0]],cell=state['cell']) - if selected[0] in self.bot.locks:self.bot.locks[state['cell']]=self.bot.locks[selected[0]] - selected=(state['cell'],state['vnum']) - self.items=items;self.scrolls=sorted(scrolls.items()) - self.itemIndex=next((i for i,v in enumerate(items) if v==selected), - next((i for i,v in enumerate(items) if selected and v[1]==selected[1]),min(self.itemIndex,max(0,len(items)-1)))) - self.scrollIndex=next((i for i,v in enumerate(self.scrolls) if v[0]==scroll),min(self.scrollIndex,max(0,len(self.scrolls)-1))) - self.nextScan=app.GetTime()+1 - if self.Selected()!=selected:self.alternatives=[[],[]];self.RequestAttrs() - - def Selected(self):return self.items[self.itemIndex] if self.items else None - def Scroll(self):return self.scrolls[self.scrollIndex][0] if self.scrolls else 0 - - def RequestAttrs(self): - selected=self.Selected() - if selected and (self.bot.allowed.get(selected[0],{}).get('vnum')!=selected[1]):self.bot.RequestAttrs(selected[0]) - - def Allowed(self): - selected=self.Selected() - data=self.bot.allowed.get(selected[0]) if selected else None - return data['rows'] if data and data['vnum']==selected[1] else None - - def Cycle(self,kind,step): - if self.bot.Running():return - if kind=='item' and self.items: - self.itemIndex=(self.itemIndex+step)%len(self.items);self.alternatives=[[],[]];self.picking=False;self.RequestAttrs() - elif kind=='scroll' and self.scrolls:self.scrollIndex=(self.scrollIndex+step)%len(self.scrolls) - self.Refresh() - - def NextLimit(self): - if not self.bot.Running():self.limitIndex=(self.limitIndex+1)%len(LIMITS);self.Refresh() - - def SelectAlt(self,index):self.alt=index;self.picking=False;self.Refresh() - - def TogglePick(self): - if self.bot.Running() or self.Allowed() is None:return - self.picking=not self.picking;self.pickPage=0;self.Refresh() - - def Candidates(self): - used=set(a for a,v in self.alternatives[self.alt]) - return [r for r in self.Allowed() or () if r[0] not in used] - - def PickPage(self,step):self.pickPage+=step;self.Refresh() - - def Pick(self,index): - rows=self.Candidates()[self.pickPage*MAX_TARGETS:] - if index1:b.Show() - else:b.Hide() - locks=self.Locks() - for i,b in enumerate(self.lockButtons): - filled=selected and player.GetItemAttribute(player.INVENTORY,selected[0],i)[0] - if locks is None or self.picking or not filled:b.Hide();continue - b.SetText(L(B(u'【锁%d】'%(i+1) if locks>>i&1 else u'锁%d'%(i+1))));b.SetEnabled(not running);b.Show() - self.pickPrev.SetEnabled(self.pickPage>0);self.pickNext.SetEnabled(self.pickPage+1>i&1 else '')+AffectText(apply,value)) - return ' / '.join(parts) - - def Reflow(self): - dims=(wndMgr.GetScreenWidth(),wndMgr.GetScreenHeight()) - if dims==self.dimensions:return - self.dimensions=dims;width=min(600,max(480,dims[0]-16));height=min(560,max(400,dims[1]-8));self.SetSize(width,height) - self.closeButton.SetPosition(width-76,6);self.itemNext.SetPosition(width-66,58);self.limitButton.SetPosition(width-128,110) - self.scrollNext.SetPosition(width-184,110);self.addButton.SetPosition(width-128,162) - for row in self.rows: - x,y=row['minus'].GetLocalPosition() - row['minus'].SetPosition(width-166,y);row['plus'].SetPosition(width-116,y);row['remove'].SetPosition(width-66,y) - row['pick'].SetSize(width-36,44);row['pick'].label.SetPosition((width-36)//2,22) - bottom=height-104 - self.pickPrev.SetPosition(18,bottom);self.pickNext.SetPosition(width-98,bottom) - self.startButton.SetPosition(18,bottom);self.stopButton.SetPosition(146,bottom) - step=(width-292)//5 - for i,b in enumerate(self.lockButtons):b.SetPosition(274+i*step,bottom);b.SetSize(step-4,48);b.label.SetPosition((step-4)//2,24) - self.status.SetPosition(18,height-46);self.current.SetPosition(18,height-22) - self.SetCenterPosition();self.Refresh() - - def OnUpdate(self): - self.Reflow();self.bot.Tick() - if self.IsShow() and app.GetTime()>=self.nextScan:self.Scan();self.Refresh() - - def OnRender(self): - x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight()) - - def OnPressEscapeKey(self):self.Hide();return True - - def Destroy(self): - self.Hide();self.bot.listener=None - for b in self.Buttons():b.event=None +# --- interfacemodule.py ---------------------------------------------------------------------------------------- +_hideAll=interfaceModule.Interface.HideAllWindows +_hideWindows=interfaceModule.Interface._Interface__HideWindows + +def ToggleSwitchbotWindow(self): + if not getattr(self,'wndSwitchbot',None):return + if self.wndSwitchbot.IsShow(): + self.wndSwitchbot.Close() + else: + self.wndSwitchbot.Open() + +def RefreshSwitchbotWindow(self): + if getattr(self,'wndSwitchbot',None) and self.wndSwitchbot.IsShow(): + self.wndSwitchbot.RefreshSwitchbotWindow() + +def RefreshSwitchbotItem(self, slot): + if getattr(self,'wndSwitchbot',None) and self.wndSwitchbot.IsShow(): + self.wndSwitchbot.RefreshSwitchbotItem(slot) + +def HideAllWindows(self): + _hideAll(self) + if getattr(self,'wndSwitchbot',None): + self.wndSwitchbot.Hide() + +def HideWindows(self): + hideWindows=_hideWindows(self) + if getattr(self,'wndSwitchbot',None) and self.wndSwitchbot.IsShow(): + self.wndSwitchbot.Hide();hideWindows=list(hideWindows)+[self.wndSwitchbot] + return hideWindows + +interfaceModule.Interface.ToggleSwitchbotWindow=ToggleSwitchbotWindow +interfaceModule.Interface.RefreshSwitchbotWindow=RefreshSwitchbotWindow +interfaceModule.Interface.RefreshSwitchbotItem=RefreshSwitchbotItem +interfaceModule.Interface.HideAllWindows=HideAllWindows +interfaceModule.Interface._Interface__HideWindows=HideWindows +# --- game.py: the window, its entry button, the GC_SWITCHBOT refresh calls and the server messages ------------- class Entry(Action): + # PORT: AVA2 opens the window from the expanded taskbar (BUTTON_SWITCHBOT) and F9; 40250 has neither that + # taskbar nor a free F9 (auto hunt), so the button stays next to the minimap, where touch can reach it. def __init__(self,window): - Action.__init__(self,None,0,0,64,'洗练',Toggle) + Action.__init__(self,None,0,0,64,'洗练',lambda:window.interface.ToggleSwitchbotWindow()) self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('SwitchbotEntry');self.OnUpdate() def OnUpdate(self): x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+148) - -def Toggle(): - if g_window: - if g_window.IsShow():g_window.Hide() - else:g_window.Open() - - +g_entry=None _open=game.GameWindow.Open _close=game.GameWindow.Close _command=game.GameWindow.BINARY_ServerCommand_Run def Open(self): - global g_window,g_entry - _open(self);g_window=SwitchbotWindow();g_entry=Entry(self) + global g_entry + _open(self) + if not self.interface:return + self.interface.wndSwitchbot=SwitchbotWindow() + self.interface.wndSwitchbot.SetItemToolTip(self.interface.tooltipItem) + self.interface.wndSwitchbot.Hide() + g_entry=Entry(self) def Close(self): - global g_window,g_entry + global g_entry if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None - if g_window:g_window.Destroy();g_window=None + if self.interface and getattr(self.interface,'wndSwitchbot',None): + self.interface.wndSwitchbot.Hide() + self.interface.wndSwitchbot.Destroy() + self.interface.wndSwitchbot=None _close(self) +def GameRefreshSwitchbotWindow(self): + if self.interface:self.interface.RefreshSwitchbotWindow() + +def GameRefreshSwitchbotItem(self, slot): + if self.interface:self.interface.RefreshSwitchbotItem(slot) + def Command(self,line): - if line.startswith('MTSB1 '): - if g_window:g_window.bot.Receive(line) + words=line.split() + if words and words[0] in ('switchbot_end','switchbot_stop','switchbot_error'): + text=None + if words[0]=='switchbot_end' and len(words)==2 and words[1].isdigit(): + slot=int(words[1]);item.SelectItem(player.GetItemIndex(player.SWITCHBOT,slot)) + text=L(MESSAGES['end'])%(item.GetItemName(),slot+1) + elif words[0]=='switchbot_stop' and len(words)==3 and words[2].isdigit(): + if words[1]=='noattr':text=L(MESSAGES['noattr'])%(int(words[2])+1) + elif words[1]=='nochanger':text=L(MESSAGES['nochanger']) + elif words[0]=='switchbot_error' and len(words)==2 and words[1] in MESSAGES: + text=L(MESSAGES[words[1]]) + if text:chat.AppendChat(chat.CHAT_TYPE_INFO,text) return 1 return _command(self,line) game.GameWindow.Open=Open game.GameWindow.Close=Close +game.GameWindow.RefreshSwitchbotWindow=GameRefreshSwitchbotWindow +game.GameWindow.RefreshSwitchbotItem=GameRefreshSwitchbotItem game.GameWindow.BINARY_ServerCommand_Run=Command )PY"; diff --git a/src/port/UserInterface/GameType.h b/src/port/UserInterface/GameType.h index 61a1f0f7..9d0d45dc 100644 --- a/src/port/UserInterface/GameType.h +++ b/src/port/UserInterface/GameType.h @@ -157,6 +157,7 @@ enum ESlotType SLOT_TYPE_PRIVATE_SHOP, SLOT_TYPE_MALL, SLOT_TYPE_DRAGON_SOUL_INVENTORY, + SLOT_TYPE_SWITCHBOT, // PORT: AVA2 switchbot SLOT_TYPE_MAX, }; @@ -169,10 +170,12 @@ enum EWindows MALL, DRAGON_SOUL_INVENTORY, GROUND, // NOTE: 2013년 2월5일 현재까지 unused.. 왜 있는거지??? + SWITCHBOT, // PORT: AVA2 switchbot; 7 on the wire = metin2-server EWindows SWITCHBOT BELT_INVENTORY, // NOTE: W2.1 버전에 새로 추가되는 벨트 슬롯 아이템이 제공하는 벨트 인벤토리 WINDOW_TYPE_MAX, }; +static_assert(SWITCHBOT == 7, "SWITCHBOT window must match the server"); enum EDSInventoryMaxNum { @@ -180,6 +183,32 @@ enum EDSInventoryMaxNum DS_REFINE_WINDOW_MAX_NUM = 15, }; +// PORT: AVA2 switchbot (GameType.h ENABLE_SWITCHBOT). Attribute sets as the server numbers them: the 40250 +// item_attr sets, then the pseudo sets for new rings and talismans (metin2-server port_switchbot.cpp). +enum ESwitchbotValues +{ + SWITCHBOT_SLOT_COUNT = 6, + SWITCHBOT_SLOT_COUNT_REAL = 5, + + SWITCHBOT_ALTERNATIVE_COUNT = 2, + MAX_NORM_ATTR_NUM = 5, +}; + +enum EAttributeSet +{ + ATTRIBUTE_SET_WEAPON, + ATTRIBUTE_SET_BODY, + ATTRIBUTE_SET_WRIST, + ATTRIBUTE_SET_FOOTS, + ATTRIBUTE_SET_NECK, + ATTRIBUTE_SET_HEAD, + ATTRIBUTE_SET_SHIELD, + ATTRIBUTE_SET_EAR, + ATTRIBUTE_SET_NEW_RINGS, + ATTRIBUTE_SET_PENDANT, + ATTRIBUTE_SET_MAX_NUM, +}; + #pragma pack (push, 1) #define WORD_MAX 0xffff @@ -220,6 +249,9 @@ typedef struct SItemPos case DRAGON_SOUL_INVENTORY: return cell < (DS_INVENTORY_MAX_NUM); break; + case SWITCHBOT: + return cell < SWITCHBOT_SLOT_COUNT; + break; default: return false; } diff --git a/src/port/UserInterface/Packet.h b/src/port/UserInterface/Packet.h index 03b28cca..3b773927 100644 --- a/src/port/UserInterface/Packet.h +++ b/src/port/UserInterface/Packet.h @@ -155,6 +155,7 @@ enum HEADER_CG_DRAGON_SOUL_REFINE = 205, HEADER_CG_STATE_CHECKER = 206, HEADER_CG_SASH = 211, // PORT: AVA2 sash (metin2-server FEATURE-AVA2-UNLOCK P4) + HEADER_CG_SWITCHBOT = 171, // PORT: AVA2 switchbot (metin2-server FEATURE-SWITCHBOT) #ifdef __AUCTION__ HEADER_CG_AUCTION_CMD = 205, @@ -360,6 +361,7 @@ enum HEADER_GC_DRAGON_SOUL_REFINE = 209, HEADER_GC_RESPOND_CHANNELSTATUS = 210, HEADER_GC_SASH = 215, // PORT: AVA2 sash + HEADER_GC_SWITCHBOT = 171, // PORT: AVA2 switchbot, DYNAMIC_SIZE_PACKET HEADER_GC_KEY_AGREEMENT_COMPLETED = 0xfa, // _IMPROVED_PACKET_ENCRYPTION_ HEADER_GC_KEY_AGREEMENT = 0xfb, // _IMPROVED_PACKET_ENCRYPTION_ @@ -2865,4 +2867,47 @@ typedef struct SSashResult DWORD dwMaxAbs; } TSashResult; +// PORT: AVA2 switchbot (ENABLE_SWITCHBOT), AVA2 Packet.h order. CG/GC: header, size, subheader, slot, then the +// subheader's payload; the item update carries our 3 sockets and 7 attributes like TPacketGCItemSet. +enum ECGSwitchbotSubheader +{ + SUBHEADER_CG_SWITCHBOT_START, + SUBHEADER_CG_SWITCHBOT_STOP, +}; + +struct TPacketCGSwitchbot +{ + BYTE header; + int size; + BYTE subheader; + BYTE slot; +}; + +enum EGCSwitchbotSubheader +{ + SUBHEADER_GC_SWITCHBOT_UPDATE, + SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM, + SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION, +}; + +struct TPacketGCSwitchbot +{ + BYTE header; + int size; + BYTE subheader; + BYTE slot; +}; + +struct TSwitchbotUpdateItem +{ + BYTE slot; + DWORD vnum; + WORD count; + LONG alSockets[ITEM_SOCKET_SLOT_MAX_NUM]; // PORT: LONG, the 32-bit Win32 long + TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM]; +}; + #pragma pack(pop) + +static_assert(sizeof(TPacketCGSwitchbot) == 7 && sizeof(TPacketGCSwitchbot) == 7, "switchbot packet header"); +static_assert(sizeof(TSwitchbotUpdateItem) == 40, "TSwitchbotUpdateItem"); diff --git a/src/port/UserInterface/PythonNetworkStream.cpp b/src/port/UserInterface/PythonNetworkStream.cpp index 2cd30362..1270435b 100644 --- a/src/port/UserInterface/PythonNetworkStream.cpp +++ b/src/port/UserInterface/PythonNetworkStream.cpp @@ -185,6 +185,7 @@ class CMainPacketHeaderMap : public CNetworkPacketHeaderMap Set(HEADER_GC_SPECIFIC_EFFECT, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCSpecificEffect), STATIC_SIZE_PACKET)); Set(HEADER_GC_DRAGON_SOUL_REFINE, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCDragonSoulRefine), STATIC_SIZE_PACKET)); Set(HEADER_GC_SASH, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketSash), STATIC_SIZE_PACKET)); // PORT: AVA2 sash + Set(HEADER_GC_SWITCHBOT, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCSwitchbot), DYNAMIC_SIZE_PACKET)); // PORT: AVA2 switchbot } }; diff --git a/src/port/UserInterface/PythonNetworkStream.h b/src/port/UserInterface/PythonNetworkStream.h index ed660051..8bab5542 100644 --- a/src/port/UserInterface/PythonNetworkStream.h +++ b/src/port/UserInterface/PythonNetworkStream.h @@ -7,6 +7,7 @@ #include "InsultChecker.h" #include "Packet.h" +#include "PythonSwitchbot.h" // PORT: AVA2 switchbot class CInstanceBase; class CNetworkActorManager; @@ -273,6 +274,10 @@ class CPythonNetworkStream : public CNetworkStream, public CSingleton alternatives); + bool SendSwitchbotStopPacket(BYTE slot); + // Handshake bool RecvHandshakePacket(); bool RecvHandshakeOKPacket(); @@ -552,6 +557,7 @@ class CPythonNetworkStream : public CNetworkStream, public CSingleton= table_size) + { + CPythonSwitchbot::TSwitchbottAttributeTable table; + if (!Recv(table_size, &table)) + { + return false; + } + + CPythonSwitchbot::Instance().AddAttributeToMap(table); + packet_size -= table_size; + } + } + + return true; +} + +bool CPythonNetworkStream::SendSwitchbotStartPacket(BYTE slot, std::vector alternatives) +{ + TPacketCGSwitchbot pack; + pack.header = HEADER_CG_SWITCHBOT; + pack.subheader = SUBHEADER_CG_SWITCHBOT_START; + pack.size = sizeof(TPacketCGSwitchbot) + sizeof(CPythonSwitchbot::TSwitchbotAttributeAlternativeTable) * SWITCHBOT_ALTERNATIVE_COUNT; + pack.slot = slot; + + if (!Send(sizeof(pack), &pack)) + { + return false; + } + + for (const auto& it : alternatives) + { + if (!Send(sizeof(it), &it)) + { + return false; + } + } + + return SendSequence(); +} + +bool CPythonNetworkStream::SendSwitchbotStopPacket(BYTE slot) +{ + TPacketCGSwitchbot pack; + pack.header = HEADER_CG_SWITCHBOT; + pack.subheader = SUBHEADER_CG_SWITCHBOT_STOP; + pack.size = sizeof(TPacketCGSwitchbot); + pack.slot = slot; + + if (!Send(sizeof(pack), &pack)) + { + return false; + } + + return SendSequence(); +} diff --git a/src/port/UserInterface/PythonPlayer.cpp b/src/port/UserInterface/PythonPlayer.cpp index f17dc296..3cf8668e 100644 --- a/src/port/UserInterface/PythonPlayer.cpp +++ b/src/port/UserInterface/PythonPlayer.cpp @@ -587,6 +587,8 @@ const TItemData * CPythonPlayer::GetItemData(TItemPos Cell) const return &m_playerStatus.aItem[Cell.cell]; case DRAGON_SOUL_INVENTORY: return &m_playerStatus.aDSItem[Cell.cell]; + case SWITCHBOT: // PORT: AVA2 switchbot + return &m_playerStatus.aSwitchbotItem[Cell.cell]; default: return NULL; } @@ -616,6 +618,9 @@ void CPythonPlayer::SetItemData(TItemPos Cell, const TItemData & c_rkItemInst) case DRAGON_SOUL_INVENTORY: m_playerStatus.aDSItem[Cell.cell] = c_rkItemInst; break; + case SWITCHBOT: // PORT: AVA2 switchbot + m_playerStatus.aSwitchbotItem[Cell.cell] = c_rkItemInst; + break; } } diff --git a/src/port/UserInterface/PythonPlayer.h b/src/port/UserInterface/PythonPlayer.h index 28e250e2..e7ed2e72 100644 --- a/src/port/UserInterface/PythonPlayer.h +++ b/src/port/UserInterface/PythonPlayer.h @@ -119,6 +119,7 @@ class CPythonPlayer : public CSingleton, public IAbstractPlayer { TItemData aItem[c_Inventory_Count]; TItemData aDSItem[c_DragonSoul_Inventory_Count]; + TItemData aSwitchbotItem[SWITCHBOT_SLOT_COUNT]; // PORT: AVA2 switchbot window TQuickSlot aQuickSlot[QUICKSLOT_MAX_NUM]; TSkillInstance aSkill[SKILL_MAX_NUM]; long m_alPoint[POINT_MAX_NUM]; diff --git a/src/port/UserInterface/PythonPlayerModule.cpp b/src/port/UserInterface/PythonPlayerModule.cpp index 94dab98c..ab550833 100644 --- a/src/port/UserInterface/PythonPlayerModule.cpp +++ b/src/port/UserInterface/PythonPlayerModule.cpp @@ -2586,6 +2586,7 @@ void initPlayer() PyModule_AddIntConstant(poModule, "SLOT_TYPE_MALL", SLOT_TYPE_MALL); PyModule_AddIntConstant(poModule, "SLOT_TYPE_EMOTION", SLOT_TYPE_EMOTION); PyModule_AddIntConstant(poModule, "SLOT_TYPE_DRAGON_SOUL_INVENTORY", SLOT_TYPE_DRAGON_SOUL_INVENTORY); + PyModule_AddIntConstant(poModule, "SLOT_TYPE_SWITCHBOT", SLOT_TYPE_SWITCHBOT); // PORT: AVA2 switchbot PyModule_AddIntConstant(poModule, "RESERVED_WINDOW", RESERVED_WINDOW); PyModule_AddIntConstant(poModule, "INVENTORY", INVENTORY); @@ -2594,6 +2595,7 @@ void initPlayer() PyModule_AddIntConstant(poModule, "MALL", MALL); PyModule_AddIntConstant(poModule, "DRAGON_SOUL_INVENTORY", DRAGON_SOUL_INVENTORY); PyModule_AddIntConstant(poModule, "GROUND", GROUND); + PyModule_AddIntConstant(poModule, "SWITCHBOT", SWITCHBOT); // PORT: AVA2 switchbot PyModule_AddIntConstant(poModule, "ITEM_MONEY", -1); diff --git a/src/port/UserInterface/PythonSwitchbot.cpp b/src/port/UserInterface/PythonSwitchbot.cpp new file mode 100644 index 00000000..f2fcca31 --- /dev/null +++ b/src/port/UserInterface/PythonSwitchbot.cpp @@ -0,0 +1,474 @@ +#include "StdAfx.h" + +// PORT: AVA2 PythonSwitchbot.cpp (ENABLE_SWITCHBOT) verbatim except memcpy for memcpy_s and the two PORT notes; +// the switchbot module is driven by mt_switchbot (ScriptLib/SwitchbotScript.inc). + +#include "PythonSwitchbot.h" +#include "PythonNetworkStream.h" +#include "PythonPlayer.h" +#include "../GameLib/ItemManager.h" + +CPythonSwitchbot::CPythonSwitchbot() +{ + Initialize(); +} + +CPythonSwitchbot::~CPythonSwitchbot() +{ + Initialize(); +} + +void CPythonSwitchbot::Initialize() +{ + m_SwitchbotTable = {}; + m_map_AttributesBySet.clear(); +} + +void CPythonSwitchbot::Update(const TSwitchbotTable& table) +{ + memcpy(m_SwitchbotTable.active, table.active, sizeof(table.active)); + memcpy(m_SwitchbotTable.finished, table.finished, sizeof(table.finished)); + memcpy(m_SwitchbotTable.alternatives, table.alternatives, sizeof(table.alternatives)); + memcpy(m_SwitchbotTable.items, table.items, sizeof(table.items)); + m_SwitchbotTable.player_id = table.player_id; +} + +void CPythonSwitchbot::SetAttribute(BYTE slot, BYTE alternative, BYTE attrIdx, BYTE attrType, int attrValue) +{ + if (slot >= SWITCHBOT_SLOT_COUNT) + { + return; + } + + if (alternative >= SWITCHBOT_ALTERNATIVE_COUNT) + { + return; + } + + m_SwitchbotTable.alternatives[slot][alternative].attributes[attrIdx].bType = attrType; + m_SwitchbotTable.alternatives[slot][alternative].attributes[attrIdx].sValue = attrValue; +} + +TPlayerItemAttribute CPythonSwitchbot::GetAttribute(BYTE slot, BYTE alternative, BYTE attrIdx) +{ + TPlayerItemAttribute attr = {}; + + if (slot >= SWITCHBOT_SLOT_COUNT) + { + return attr; + } + + if (alternative >= SWITCHBOT_ALTERNATIVE_COUNT) + { + return attr; + } + + attr.bType = m_SwitchbotTable.alternatives[slot][alternative].attributes[attrIdx].bType; + attr.sValue = m_SwitchbotTable.alternatives[slot][alternative].attributes[attrIdx].sValue; + + return attr; +} + +void CPythonSwitchbot::GetAlternatives(BYTE slot, std::vector& vec_alternatives) +{ + if (slot >= SWITCHBOT_SLOT_COUNT) + { + return; + } + + for (const auto& it : m_SwitchbotTable.alternatives[slot]) + { + vec_alternatives.emplace_back(it); + } +} + +int CPythonSwitchbot::GetAttibuteSet(BYTE slot) +{ + if (slot >= SWITCHBOT_SLOT_COUNT) + { + return -1; + } + + TItemPos pos(SWITCHBOT, slot); + + CItemData* pItemDataPtr = NULL; + BYTE item_type = 0, item_subtype = 0; // PORT: AVA2 left item_type uninitialised + + if (CItemManager::Instance().GetItemDataPointer(CPythonPlayer::Instance().GetItemIndex(pos), &pItemDataPtr)) + { + item_type = pItemDataPtr->GetType(); + item_subtype = pItemDataPtr->GetSubType(); + } + + if (item_type == 0 && item_subtype == 0) + { + return -1; + } + + if (item_type == CItemData::ITEM_TYPE_WEAPON) + { + if (item_subtype == CItemData::WEAPON_ARROW) + { + return -1; + } + + return ATTRIBUTE_SET_WEAPON; + } + + if(item_type == CItemData::ITEM_TYPE_RINGS) + { + return ATTRIBUTE_SET_NEW_RINGS; + } + + if (item_type == CItemData::ITEM_TYPE_ARMOR || item_type == CItemData::ITEM_TYPE_COSTUME) + { + switch (item_subtype) + { + case CItemData::ARMOR_BODY: + return ATTRIBUTE_SET_BODY; + + case CItemData::ARMOR_WRIST: + return ATTRIBUTE_SET_WRIST; + + case CItemData::ARMOR_FOOTS: + return ATTRIBUTE_SET_FOOTS; + + case CItemData::ARMOR_NECK: + return ATTRIBUTE_SET_NECK; + + case CItemData::ARMOR_HEAD: + return ATTRIBUTE_SET_HEAD; + + case CItemData::ARMOR_SHIELD: + return ATTRIBUTE_SET_SHIELD; + + case CItemData::ARMOR_EAR: + return ATTRIBUTE_SET_EAR; + + case CItemData::ARMOR_PENDANT: + return ATTRIBUTE_SET_PENDANT; + } + } + + return -1; +} + +bool CPythonSwitchbot::IsActive(BYTE slot) +{ + if (slot >= SWITCHBOT_SLOT_COUNT) + { + return false; + } + + return m_SwitchbotTable.active[slot]; +} + +bool CPythonSwitchbot::IsFinished(BYTE slot) +{ + if (slot >= SWITCHBOT_SLOT_COUNT) + { + return false; + } + + return m_SwitchbotTable.finished[slot]; +} + +void CPythonSwitchbot::ClearSlot(BYTE slot) +{ + if (slot >= SWITCHBOT_SLOT_COUNT) + { + return; + } + + m_SwitchbotTable.active[slot] = false; + m_SwitchbotTable.items[slot] = 0; + memset(&m_SwitchbotTable.alternatives[slot], 0, sizeof(m_SwitchbotTable.alternatives[slot])); +} + +void CPythonSwitchbot::ClearAttributeMap() +{ + m_map_AttributesBySet.clear(); +} + +void CPythonSwitchbot::AddAttributeToMap(const TSwitchbottAttributeTable& table) +{ + const auto& it = m_map_AttributesBySet.find(table.attribute_set); + if (it == m_map_AttributesBySet.end()) + { + std::map attribute_map; + attribute_map.insert(std::make_pair(table.apply_num, table.max_value)); + + m_map_AttributesBySet.insert(std::make_pair(table.attribute_set, attribute_map)); + } + else + { + std::map::iterator it2 = it->second.find(table.apply_num); + if (it2 == it->second.end()) + { + it->second.insert(std::make_pair(table.apply_num, table.max_value)); + } + else + { + it2->second = table.max_value; + } + } +} + +void CPythonSwitchbot::GetAttributesBySet(int iAttributeSet, std::vector& vec_attributes) +{ + if (iAttributeSet == -1) + { + return; + } + + const auto& it = m_map_AttributesBySet.find(iAttributeSet); + if (it == m_map_AttributesBySet.end()) + { + return; + } + + for (const auto& it2 : it->second) + { + TPlayerItemAttribute attr; + attr.bType = it2.first; + attr.sValue = it2.second; + + vec_attributes.emplace_back(attr); + } +} + +long CPythonSwitchbot::GetAttributeMaxValue(int iAttributeSet, BYTE attrType) +{ + if (iAttributeSet == -1) + { + return 0; + } + + const auto& it = m_map_AttributesBySet.find(iAttributeSet); + if (it == m_map_AttributesBySet.end()) + { + return 0; + } + + const auto& it2 = it->second.find(attrType); + if (it2 == it->second.end()) + { + return 0; + } + + return it2->second; +} + +PyObject* switchbotIsActive(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + return Py_BuildValue("i", CPythonSwitchbot::Instance().IsActive(bSlot)); +} + +PyObject* switchbotIsFinished(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + return Py_BuildValue("i", CPythonSwitchbot::Instance().IsFinished(bSlot)); +} + +PyObject* switchbotGetAttribute(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + BYTE bAlternative; + if (!PyTuple_GetByte(poArgs, 1, &bAlternative)) + { + return Py_BuildException(); + } + + BYTE bAttrIndex; + if (!PyTuple_GetByte(poArgs, 2, &bAttrIndex)) + { + return Py_BuildException(); + } + + TPlayerItemAttribute attr = CPythonSwitchbot::Instance().GetAttribute(bSlot, bAlternative, bAttrIndex); + return Py_BuildValue("ii", attr.bType, attr.sValue); +} + +PyObject* switchbotSetAttribute(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + BYTE bAlternative; + if (!PyTuple_GetByte(poArgs, 1, &bAlternative)) + { + return Py_BuildException(); + } + + BYTE bAttrIndex; + if (!PyTuple_GetByte(poArgs, 2, &bAttrIndex)) + { + return Py_BuildException(); + } + + BYTE bType; + if (!PyTuple_GetByte(poArgs, 3, &bType)) + { + return Py_BuildException(); + } + + int iValue; + if (!PyTuple_GetInteger(poArgs, 4, &iValue)) + { + return Py_BuildException(); + } + + CPythonSwitchbot::Instance().SetAttribute(bSlot, bAlternative, bAttrIndex, bType, iValue); + return Py_BuildNone(); +} + +PyObject* switchbotClearSlot(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + CPythonSwitchbot::Instance().ClearSlot(bSlot); + return Py_BuildNone(); +} + +PyObject* switchbotGetAttributesForSet(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + PyObject* list = PyList_New(0); + + int iAttributeSet = CPythonSwitchbot::Instance().GetAttibuteSet(bSlot); + if (iAttributeSet == -1) + { + return list; + } + + std::vector vec_attributes; + CPythonSwitchbot::Instance().GetAttributesBySet(iAttributeSet, vec_attributes); + + struct + { + bool operator()(TPlayerItemAttribute a, TPlayerItemAttribute b) const + { + return a.bType < b.bType; + } + } SortAttributes; + + std::sort(vec_attributes.begin(), vec_attributes.end(), SortAttributes); + + for (TPlayerItemAttribute attr : vec_attributes) + { + PyList_Append(list, Py_BuildValue("(ii)", attr.bType, attr.sValue)); + } + + return list; +} + +PyObject* switchbotGetAttributeMaxValue(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + BYTE bAttrType; + if (!PyTuple_GetByte(poArgs, 1, &bAttrType)) + { + return Py_BuildException(); + } + + int iAttributeSet = CPythonSwitchbot::Instance().GetAttibuteSet(bSlot); + if (iAttributeSet == -1) + { + return Py_BuildValue("i", 0); + } + + long maxValue = CPythonSwitchbot::Instance().GetAttributeMaxValue(iAttributeSet, bAttrType); + return Py_BuildValue("i", int(maxValue)); // PORT: "i" takes an int; long is 64-bit here +} + +PyObject* switchbotStart(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + if (bSlot > SWITCHBOT_SLOT_COUNT) + { + return Py_BuildNone(); + } + + std::vector vec_alternatives; + CPythonSwitchbot::Instance().GetAlternatives(bSlot, vec_alternatives); + + CPythonNetworkStream::Instance().SendSwitchbotStartPacket(bSlot, vec_alternatives); + return Py_BuildNone(); +} + +PyObject* switchbotStop(PyObject* poSelf, PyObject* poArgs) +{ + BYTE bSlot; + if (!PyTuple_GetByte(poArgs, 0, &bSlot)) + { + return Py_BuildException(); + } + + if (bSlot > SWITCHBOT_SLOT_COUNT) + { + return Py_BuildNone(); + } + + CPythonNetworkStream::Instance().SendSwitchbotStopPacket(bSlot); + return Py_BuildNone(); +} + +void initSwitchbot() +{ + static PyMethodDef s_methods[] = + { + { "IsActive", switchbotIsActive, METH_VARARGS }, + { "IsFinished", switchbotIsFinished, METH_VARARGS }, + { "GetAttribute", switchbotGetAttribute, METH_VARARGS }, + { "SetAttribute", switchbotSetAttribute, METH_VARARGS }, + { "GetAttributesForSet", switchbotGetAttributesForSet, METH_VARARGS }, + { "GetAttributeMaxValue", switchbotGetAttributeMaxValue, METH_VARARGS }, + { "ClearSlot", switchbotClearSlot, METH_VARARGS }, + { "Start", switchbotStart, METH_VARARGS }, + { "Stop", switchbotStop, METH_VARARGS }, + + { NULL, NULL, NULL }, + }; + + PyObject * poModule = Py_InitModule("switchbot", s_methods); + PyModule_AddIntConstant(poModule, "SLOT_COUNT", SWITCHBOT_SLOT_COUNT_REAL); + PyModule_AddIntConstant(poModule, "ALTERNATIVE_COUNT", SWITCHBOT_ALTERNATIVE_COUNT); +} diff --git a/src/port/UserInterface/PythonSwitchbot.h b/src/port/UserInterface/PythonSwitchbot.h new file mode 100644 index 00000000..59fa9ada --- /dev/null +++ b/src/port/UserInterface/PythonSwitchbot.h @@ -0,0 +1,82 @@ +#pragma once + +// PORT: AVA2 PythonSwitchbot.h (ENABLE_SWITCHBOT). The tables are the server's wire layout +// (metin2-server common/tables.h); max_value is LONG, the 32-bit Win32 long. +#include "Packet.h" + +class CPythonSwitchbot : public CSingleton +{ +public: + #pragma pack(1) + struct TSwitchbotAttributeAlternativeTable + { + TPlayerItemAttribute attributes[MAX_NORM_ATTR_NUM]; + + bool IsConfigured() const + { + for (const auto& it : attributes) + { + if (it.bType && it.sValue) + { + return true; + } + } + + return false; + } + }; + + struct TSwitchbotTable + { + DWORD player_id; + bool active[SWITCHBOT_SLOT_COUNT]; + bool finished[SWITCHBOT_SLOT_COUNT]; + DWORD items[SWITCHBOT_SLOT_COUNT]; + TSwitchbotAttributeAlternativeTable alternatives[SWITCHBOT_SLOT_COUNT][SWITCHBOT_ALTERNATIVE_COUNT]; + + TSwitchbotTable() : player_id(0) + { + memset(&items, 0, sizeof(items)); + memset(&alternatives, 0, sizeof(alternatives)); + memset(&active, false, sizeof(active)); + memset(&finished, false, sizeof(finished)); + } + }; + + struct TSwitchbottAttributeTable + { + BYTE attribute_set; + int apply_num; + LONG max_value; + }; + +#pragma pack() + + CPythonSwitchbot(); + virtual ~CPythonSwitchbot(); + + void Initialize(); + void Update(const TSwitchbotTable& table); + + void SetAttribute(BYTE slot, BYTE alternative, BYTE attrIdx, BYTE attrType, int attrValue); + TPlayerItemAttribute GetAttribute(BYTE slot, BYTE alternative, BYTE attrIdx); + void GetAlternatives(BYTE slot, std::vector& attributes); + int GetAttibuteSet(BYTE slot); + bool IsActive(BYTE slot); + bool IsFinished(BYTE slot); + + void ClearSlot(BYTE slot); + void ClearAttributeMap(); + + void AddAttributeToMap(const TSwitchbottAttributeTable& table); + void GetAttributesBySet(int iAttributeSet, std::vector& vec_attributes); + long GetAttributeMaxValue(int iAttributeSet, BYTE attrType); + +protected: + TSwitchbotTable m_SwitchbotTable; + std::map> m_map_AttributesBySet; +}; + +static_assert(sizeof(CPythonSwitchbot::TSwitchbotTable) == 220, "TSwitchbotTable"); +static_assert(sizeof(CPythonSwitchbot::TSwitchbotAttributeAlternativeTable) == 15, "TSwitchbotAttributeAlternativeTable"); +static_assert(sizeof(CPythonSwitchbot::TSwitchbottAttributeTable) == 9, "TSwitchbottAttributeTable"); diff --git a/src/port/UserInterface/StdAfx.h b/src/port/UserInterface/StdAfx.h index 0438de5b..3702c66d 100644 --- a/src/port/UserInterface/StdAfx.h +++ b/src/port/UserInterface/StdAfx.h @@ -69,6 +69,7 @@ void initBackground(); void initMessenger(); void initsafebox(); void initSash(); // PORT: AVA2 sash +void initSwitchbot(); // PORT: AVA2 switchbot void initguild(); void initServerStateChecker(); void initRenderTarget(); // PORT: AVA2 CPythonRenderTargetModule diff --git a/tests/wiki/test_item_actions.py b/tests/wiki/test_item_actions.py index a7e741ba..17c2025e 100644 --- a/tests/wiki/test_item_actions.py +++ b/tests/wiki/test_item_actions.py @@ -24,12 +24,11 @@ class Action(Widget): class ItemActionsTests(unittest.TestCase): def setUp(self): - names=('game','grp','player','ui','wndMgr','mt_biolog','mt_preview','mt_chest','mt_wiki','uiInventory','mt_battlepass','mt_switchbot') + names=('game','grp','player','ui','wndMgr','mt_biolog','mt_preview','mt_chest','mt_wiki','uiInventory','mt_battlepass') mods={name:types.ModuleType(name) for name in names};self.mods=mods;self.actions=[];self.bag={3:(50011,2),4:(19,1)} mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None)) mods['uiInventory'].InventoryWindow=type('InventoryWindow',(),dict(UseItemSlot=lambda owner,cell:self.actions.append(('use',cell)),_InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos=lambda owner,cell:cell)) mods['mt_battlepass'].g_window=types.SimpleNamespace(OfferTicket=lambda c,v:self.actions.append(('ticket',c,v))) - mods['mt_switchbot'].g_window=types.SimpleNamespace(Open=lambda:self.actions.append(('lock',))) mods['ui'].Window=Widget;mods['mt_biolog'].Action=Action mods['player'].GetItemIndex=lambda cell:self.bag.get(cell,(0,0))[0] mods['player'].GetItemCount=lambda cell:self.bag.get(cell,(0,0))[1] @@ -57,11 +56,11 @@ class ItemActionsTests(unittest.TestCase): self.ns['ShowInventory'](self.owner,4) self.window.buttons[1].event();self.assertEqual(self.actions[-1],('preview',19)) - def test_ticket_lock_and_original_use(self): + def test_ticket_and_original_use(self): inventory=self.mods['uiInventory'].InventoryWindow() for vnum in (25159,50348,50349,27001): self.bag[5]=(vnum,1);inventory.UseItemSlot(5) - self.assertEqual(self.actions,[('ticket',5,25159),('lock',),('lock',),('use',5)]) + self.assertEqual(self.actions,[('ticket',5,25159),('use',5),('use',5),('use',5)]) # 50348/50349 no longer open the switchbot window def test_stale_actions_never_fire(self): for change in ('page','vnum','count','closed'): diff --git a/tests/wiki/test_switchbot.py b/tests/wiki/test_switchbot.py index 120a99cf..10c17e72 100644 --- a/tests/wiki/test_switchbot.py +++ b/tests/wiki/test_switchbot.py @@ -1,23 +1,28 @@ -import re +"""mt_switchbot (SwitchbotScript.inc): AVA2 root/uiswitchbot.py verbatim plus its ENABLE_SWITCHBOT glue. The window +talks to the C++ switchbot module (CG/GC_SWITCHBOT 171), items move through the SWITCHBOT window, and the server +reports end/stop/error as switchbot_* commands. The old /mt_switchbot chat protocol is gone.""" import sys import types import unittest from pathlib import Path ROOT=Path(__file__).resolve().parents[2] +AVA2=ROOT.parent/'AVA2/TEST/1. Client DEV/pack_maker/root/uiswitchbot.py' def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0] class Widget(object): - def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0) - def __getattr__(self,name):return lambda *a,**k:None + def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0);self.itemList=[] + def __getattr__(self,name): + if name.startswith('__'):raise AttributeError(name) + return lambda *a,**k:0 def Show(self):self.shown=True def Hide(self):self.shown=False def IsShow(self):return self.shown def SetText(self,text):self.text=text + def GetText(self):return self.text def SetPosition(self,x,y):self.pos=(x,y) - def GetLocalPosition(self):return self.pos def GetGlobalPosition(self):return self.pos def SetSize(self,w,h):self.size=(w,h) def GetWidth(self):return self.size[0] @@ -25,159 +30,104 @@ class Widget(object): class Action(Widget): - def __init__(self,parent,x,y,width,text,event): - Widget.__init__(self);self.pos=(x,y);self.event=event;self.enabled=True;self.label=Widget();self.text=text;self.shown=True - def SetEnabled(self,enabled):self.enabled=enabled + def __init__(self,parent,x,y,width,text,event):Widget.__init__(self);self.text=text;self.event=event;self.shown=True + + +class Mouse(object): + def __init__(self):self.AttachedFlag=False;self.AttachedType=0;self.AttachedSlotNumber=0;self.AttachedCount=0;self.AttachedIconHandle=0 + def AttachObject(self,owner,kind,slot,vnum,count=0): + self.AttachedFlag=True;self.AttachedType=kind;self.AttachedSlotNumber=slot;self.AttachedCount=count;self.AttachedIconHandle=9 + def DeattachObject(self):self.AttachedFlag=False;self.AttachedIconHandle=0 + def isAttached(self):return self.AttachedFlag + def GetAttachedType(self):return self.AttachedType + def GetAttachedSlotNumber(self):return self.AttachedSlotNumber + def GetAttachedItemCount(self):return self.AttachedCount class SwitchbotTests(unittest.TestCase): def setUp(self): - self.time=1.;self.sent=[];self.chat=[];self.events=[] - self.inventory={10:(11209,1,[(3,2),(15,1)]),20:(71084,7,[]),21:(71084,3,[]),30:(27001,5,[])} - protos={11209:(2,0),71084:(3,18),27001:(3,0)} - mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','item','net','player','ui','uiToolTip','wndMgr','mt_biolog','mt_wiki')} - mods['app'].GetTime=lambda:self.time + self.moves=[];self.chat=[];self.icons=[];self.deleted=[];self.passed=[];self.bag={(7,2):11209} + names=('dbg','constInfo','app','ime','item','grp','net','ui','uiToolTip','player','mouseModule','localeInfo','wndMgr', + 'cPickle','switchbot','chat','game','interfaceModule','uiInventory','mt_biolog') + mods={n:types.ModuleType(n) for n in names};self.mods=mods + mods['constInfo'].GET_ITEM_QUESTION_DIALOG_STATUS=lambda:0 + mods['grp'].GenerateColor=lambda *a:0 + it=mods['item'];it.APPLY_SKILL_DAMAGE_BONUS=71;it.APPLY_NORMAL_HIT_DAMAGE_BONUS=72;self.selected=0 + it.SelectItem=lambda v:setattr(self,'selected',v);it.GetItemName=lambda:'N%d'%self.selected;it.GetItemSize=lambda:(1,2) + it.DeleteIconInstance=self.deleted.append + mods['net'].SendItemMovePacket=lambda *a:self.moves.append(a) + ui=mods['ui'] + for n in ('Window','Bar','BoardWithTitleBar','Box','Button','EditLine','ExpandedImageBox','GridSlotWindow','ListBoxEx', + 'RadioButton','ScrollBar','TextLine'):setattr(ui,n,type(n,(Widget,),{})) + ui.__mem_func__=lambda f:f + mods['uiToolTip'].ItemToolTip=type('ItemToolTip',(),dict(AFFECT_DICT={})) + pl=mods['player'];pl.INVENTORY=1;pl.SWITCHBOT=7;pl.SLOT_TYPE_INVENTORY=1;pl.SLOT_TYPE_SWITCHBOT=33 + pl.AutoHuntLocalize=lambda t:t;pl.GetItemIndex=lambda w,c:self.bag.get((w,c),0) + mods['mouseModule'].CMouseController=Mouse;self.mouse=mods['mouseModule'].mouseController=Mouse() + mods['wndMgr'].AttachIcon=lambda *a:self.icons.append(a) + sb=mods['switchbot'];sb.SLOT_COUNT=5;sb.ALTERNATIVE_COUNT=2 mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m) - mods['net'].SendChatPacket=self.sent.append - mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None,BINARY_ServerCommand_Run=lambda s,line:7)) - grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None - it=mods['item'];it.ITEM_TYPE_WEAPON=1;it.ITEM_TYPE_ARMOR=2;it.ITEM_TYPE_USE=3;it.ARMOR_PENDANT=7;self.selected=None - it.SelectItem=lambda v:setattr(self,'selected',v);it.GetItemType=lambda:protos[self.selected][0];it.GetItemSubType=lambda:protos[self.selected][1] - it.GetItemName=lambda:'N%d'%self.selected - pl=mods['player'];pl.INVENTORY=1;pl.INVENTORY_PAGE_SIZE=45;pl.INVENTORY_PAGE_COUNT=5 - pl.GetItemIndex=lambda w,c:self.inventory.get(c,(0,))[0];pl.GetItemCount=lambda w,c:self.inventory[c][1] - pl.GetItemAttribute=lambda w,c,i:(self.inventory[c][2]+[(0,0)]*5)[i] - mods['ui'].Window=Widget - mods['uiToolTip'].ItemToolTip=type('ItemToolTip',(),dict(AFFECT_DICT={3:lambda v:'STR+%d'%v})) - mods['wndMgr'].GetScreenWidth=lambda:800;mods['wndMgr'].GetScreenHeight=lambda:600 - mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8') - mods['mt_wiki'].U=lambda t:t if isinstance(t,str) else t.decode('utf-8');mods['mt_wiki'].B=lambda t,limit=0:t - self.previous={n:sys.modules.get(n) for n in mods} - sys.modules.update(mods) + mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None, + BINARY_ServerCommand_Run=lambda s,line:self.passed.append(line) or 7)) + mods['interfaceModule'].Interface=type('Interface',(),dict(HideAllWindows=lambda s:None,_Interface__HideWindows=lambda s:[])) + mods['uiInventory'].InventoryWindow=type('InventoryWindow',(),dict(SelectEmptySlot=lambda s,c:self.passed.append(('empty',c)), + _InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos=lambda s,c:c+45)) + mods['mt_biolog'].Action=Action + self.previous={n:sys.modules.get(n) for n in mods};sys.modules.update(mods) self.ns={'__name__':'mt_switchbot'};exec(script('SwitchbotScript.inc'),self.ns) - self.bot=self.ns['Bot'](self.sent.append,lambda:self.time,self.events.append) def tearDown(self): - for name,value in self.previous.items(): - if value is None:sys.modules.pop(name,None) - else:sys.modules[name]=value + for n,value in self.previous.items(): + if value is None:sys.modules.pop(n,None) + else:sys.modules[n]=value - def advance(self,seconds=.4):self.time+=seconds;self.bot.Tick() + def test_verbatim_ava2_window(self): + text=script('SwitchbotScript.inc') + for name in ('SwitchbotItemTab(ui.ThinBoardCircle)','SwitchbotAttribute(ui.Window)','SwitchbotWindow(ui.BoardWithTitleBar)', + 'SearchListWindow(ui.BoardWithTitleBar)','ConfigurationWindow(ui.BoardWithTitleBar)'): + self.assertIn('class %s:'%name,text) + self.assertNotIn('/mt_switchbot',text);self.assertNotIn('SendChatPacket',text) + if not AVA2.is_file():self.skipTest('AVA2 tree not checked out') + src=AVA2.read_bytes().decode('latin1').replace('\r\n','\n');src=src[src.index('COLOR_INACTIVE'):].rstrip() + src=src.replace('self.alternativeTextLine.SetText("Alternativen:")','self.alternativeTextLine.SetText(localeInfo.SWITCHBOT_ALTERNATIVES)') + body=text[text.index('COLOR_INACTIVE'):text.index('# --- uitooltip.py')].rstrip() + body=body.replace('\t# PORT: AVA2 left this German','').replace( + 'attrTab.Hide()\t# PORT: switchers stay in the inventory, cell 5 is unused (server port_switchbot.cpp)','attrTab.Show()') + self.assertEqual(body,src) - def load(self,bot,cell=10): - for line in ('MTSB1 attrs %d 11209 3'%cell,'MTSB1 attr 0 3 12','MTSB1 attr 1 63 6','MTSB1 attr 2 71 30','MTSB1 attrs_end %d 3'%cell):bot.Receive(line) + def test_ui_and_locale_parts(self): + self.assertIs(self.mods['ui'].ThinBoardCircle,self.ns['ThinBoardCircle']) + box=self.mods['ui'].ListBoxEx();box.itemList=[1,2];self.assertEqual(box.GetItems(),[1,2]) + self.assertEqual(self.mods['localeInfo'].SWITCHBOT_TITLE,'自动洗练') + self.assertEqual(self.mods['constInfo'].USERDATA_DIRECTORY,'') + self.assertEqual(self.ns['ITEM_TAB_WIDTH'],(400-16)/5+1-2) # 5 tabs: cell 5 is hidden, as in AVA2 - def test_commands_are_paced_and_attrs_requests_collapse(self): - self.bot.RequestAttrs(10);self.bot.RequestAttrs(11);self.bot.RequestAttrs(12);self.bot.Status() - self.assertEqual(self.sent,['/mt_switchbot 1 attrs 10']) - self.load(self.bot);self.advance() - self.assertEqual(self.sent[-1],'/mt_switchbot 1 attrs 12') - self.bot.Receive('MTSB1 error attrs no_attr');self.advance() - self.assertEqual(self.sent[-1],'/mt_switchbot 1 status') - self.assertEqual(len(self.sent),3) + def test_server_messages(self): + game=self.mods['game'].GameWindow() + for line in ('switchbot_end 2','switchbot_stop noattr 1','switchbot_stop nochanger 0','switchbot_error active', + 'switchbot_error invalid','switchbot_end x','quest 3'): + game.BINARY_ServerCommand_Run(line) + self.assertEqual(self.chat,['N11209(第 3 格)洗练完成!','第 2 格的物品没有可洗练的属性,已停止。', + '自动洗练已停止:背包里没有可用的洗练道具。','该格正在洗练,请先停止。','这件物品不能自动洗练。']) + self.assertEqual(self.passed,['quest 3']) - def test_atomic_attr_list_and_rejected_partials(self): - self.load(self.bot) - self.assertEqual(self.bot.allowed[10]['rows'],[(3,12),(63,6),(71,30)]) - for bad in (['MTSB1 attrs 11 1 2','MTSB1 attr 0 3 12','MTSB1 attrs_end 11 2'], - ['MTSB1 attrs 11 1 1','MTSB1 attr 1 3 12','MTSB1 attrs_end 11 1'], - ['MTSB1 attrs 11 1 1','MTSB1 attr 0 3 -1','MTSB1 attrs_end 11 1'], - ['MTSB1 attrs_end 11 0']): - for line in bad:self.assertTrue(self.bot.Receive(line)) - self.assertNotIn(11,self.bot.allowed) - self.assertFalse(self.bot.Receive('MTF1 cap 1 1 127 0')) + def test_drag_back_to_inventory(self): + self.mouse.AttachObject(None,self.mods['player'].SLOT_TYPE_SWITCHBOT,2,11209,1) + self.assertEqual(self.mouse.AttachedType,33);self.assertEqual(self.icons,[(33,11209,2,1,2)]) + self.mods['uiInventory'].InventoryWindow().SelectEmptySlot(4) + self.assertEqual(self.moves,[(7,2,1,49,1)]);self.assertFalse(self.mouse.isAttached());self.assertEqual(self.deleted,[9]) + self.mods['uiInventory'].InventoryWindow().SelectEmptySlot(5);self.assertEqual(self.passed,[('empty',5)]) - def test_start_validates_against_server_list_and_builds_command(self): - self.load(self.bot) - self.assertEqual(self.bot.Start(10,71084,100,[[(3,13)],[]]),'target') - self.assertEqual(self.bot.Start(10,71084,100,[[(1,1)],[]]),'target') - self.assertEqual(self.bot.Start(10,71084,100,[[(3,1),(3,2)],[]]),'invalid') - self.assertEqual(self.bot.Start(10,71084,1001,[[(3,1)],[]]),'invalid') - self.assertEqual(self.bot.Start(10,71084,100,[[],[]]),'invalid') - self.assertIsNone(self.bot.Start(10,71084,100,[[(3,8),(63,6)],[(71,30)]])) - self.advance() - self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 100 2 3 8 63 6 1 71 30') - self.bot.Receive('MTSB1 error start running') - self.assertIsNone(self.bot.Start(10,71084,5,[[],[(71,1)]]));self.advance() - self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 5 1 71 1') # empty first alternative skipped - - def test_state_errors_and_timeout(self): - self.bot.Receive('MTSB1 state 1 10 11209 3 100 71084 4 running') - self.assertTrue(self.bot.Running());self.assertEqual(self.bot.state['scrolls'],4) - self.bot.Receive('MTSB1 state 0 10 11209 4 100 71084 3 matched') - self.assertFalse(self.bot.Running());self.assertEqual(self.bot.state['reason'],'matched') - self.bot.Receive('MTSB1 state 0 10 11209 4 100 71084 3 exploded') - self.assertEqual(self.bot.state['reason'],'matched') # unknown reason ignored - self.bot.Receive('MTSB1 error start busy');self.assertEqual(self.bot.error,'busy') - self.bot.Status();self.advance(4.1);self.advance() - self.assertEqual(self.bot.error,'unsupported');self.assertTrue(self.bot.unsupported) - - def test_server_constants_match(self): - server=ROOT.parent/'metin2-server/src/server/game/src/port_switchbot.h' - if not server.exists():self.skipTest('server checkout not installed') - text=server.read_text(encoding='latin1') - reasons=set(re.findall(r'return "([a-z_]+)"',text))|{'running','stopped','idle'} - errors=set(re.findall(r'error [a-z%]+ ([a-z_]+)"',text))|{'invalid','rate'} - lock_errors={'slot','max','db'} - self.assertTrue(reasons-{'invalid','running','item','equipped','no_attr','scroll','target','busy'}-lock_errors<=set(self.ns['REASONS'])) - self.assertTrue(lock_errors<=set(self.ns['ERRORS'])) - self.assertTrue(errors<=set(self.ns['ERRORS'])) - self.assertIn('kPortSwitchLimit=1000',text);self.assertEqual(max(self.ns['LIMITS']),1000) - self.assertEqual(self.ns['MAX_TARGETS'],5) - - def test_lock_protocol_and_buttons(self): - self.bot.Lock(10,0);self.assertEqual(self.sent,[]) # no lock line yet: old server, no request - self.load(self.bot);self.bot.Receive('MTSB1 lock 10 11209 2') - self.assertEqual(self.bot.LockMask(10,11209),2);self.assertIsNone(self.bot.LockMask(10,11210)) - self.bot.Lock(10,5);self.bot.Lock(10,0);self.advance() - self.assertEqual(self.sent[-1],'/mt_switchbot 1 lock 10 0') - self.bot.Receive('MTSB1 lock 10 11209 3');self.assertIsNone(self.bot.waiting);self.assertEqual(self.bot.LockMask(10,11209),3) - self.bot.Lock(10,1);self.advance();self.bot.Receive('MTSB1 error lock max');self.assertEqual(self.bot.error,'max') - for bad in ('MTSB1 lock 10 11209','MTSB1 lock 10 11209 32'):self.bot.Receive(bad) - self.assertEqual(self.bot.LockMask(10,11209),3) - # Window: one button per filled slot, hidden while picking, locked attributes marked. - game=sys.modules['game'];gw=game.GameWindow();gw.interface=types.SimpleNamespace(wndMiniMap=Widget()) - game.GameWindow.Open(gw);w=self.ns['g_window'];w.Open() - self.assertFalse(any(b.shown for b in w.lockButtons)) - self.load(w.bot);w.bot.Receive('MTSB1 lock 10 11209 2') - self.assertEqual([b.shown for b in w.lockButtons],[True,True,False,False,False]) - self.assertEqual([b.text for b in w.lockButtons[:2]],['锁1','【锁2】']);self.assertIn('[锁]',w.current.text.split(' / ')[1]) - self.assertIn('保持不变',w.status.text) - self.time+=.5;w.OnUpdate();w.bot.Receive('MTSB1 state 0 0 0 0 0 0 0 idle') # answers the status request - sent=len(self.sent);w.lockButtons[0].event();self.time+=.5;w.OnUpdate() - self.assertEqual(self.sent[sent:],['/mt_switchbot 1 lock 10 0']) - w.TogglePick();self.assertFalse(any(b.shown for b in w.lockButtons));w.TogglePick() - w.bot.Receive('MTSB1 state 1 10 11209 0 100 71084 9 running');self.assertFalse(w.lockButtons[0].enabled) - sent=len(self.sent);w.lockButtons[0].event();self.time+=.5;w.OnUpdate() - self.assertNotIn('/mt_switchbot 1 lock 10 0',self.sent[sent:]) - game.GameWindow.Close(gw) - - def test_window_scan_pick_start_and_notify(self): - game=sys.modules['game'];window_type=game.GameWindow - gw=window_type();gw.interface=types.SimpleNamespace(wndMiniMap=Widget()) - game.GameWindow.Open(gw);w=self.ns['g_window'];w.Open() - self.assertEqual(w.items,[(10,11209)]);self.assertEqual(w.scrolls,[(71084,10)]) - self.assertEqual(self.sent,['/mt_switchbot 1 attrs 10']) # the status request waits for this reply - self.load(w.bot);self.time+=.5;w.OnUpdate() - self.assertEqual(self.sent[-1],'/mt_switchbot 1 status') - self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'MTSB1 state 0 0 0 0 0 0 0 idle'),1) - self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'other'),7) - w.TogglePick();w.Pick(0) - self.assertEqual(w.alternatives[0],[[3,12]]) - w.Adjust(0,-1);self.assertEqual(w.alternatives[0][0][1],10);w.Adjust(0,1);w.Adjust(0,1);self.assertEqual(w.alternatives[0][0][1],12) - w.Start();self.time+=.5;w.OnUpdate() - self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 100 1 3 12') - w.bot.Receive('MTSB1 state 1 10 11209 1 100 71084 9 running');self.assertFalse(w.startButton.enabled) - self.inventory[40]=self.inventory.pop(10);sent=len(self.sent) # moved while running: follow the server's cell - w.bot.Receive('MTSB1 state 1 40 11209 2 100 71084 8 running');w.Scan() - self.assertEqual(w.Selected(),(40,11209));self.assertEqual(w.alternatives[0],[[3,12]]) - self.assertEqual(w.Allowed(),[(3,12),(63,6),(71,30)]);self.time+=.5;w.OnUpdate();self.assertEqual(len(self.sent),sent) - w.bot.Receive('MTSB1 state 0 40 11209 2 100 71084 8 stopped') - self.inventory[5]=self.inventory.pop(40);w.Scan();self.assertEqual(w.Selected(),(5,11209)) # moved while idle: same vnum - self.inventory[10]=self.inventory.pop(5);w.Scan() - w.Hide();w.bot.Receive('MTSB1 state 0 10 11209 2 100 71084 8 matched') - self.assertTrue(w.IsShow());self.assertIn('已获得目标属性',self.chat[-1]) - game.GameWindow.Close(gw);self.assertIsNone(self.ns['g_window']) + def test_interface_hooks(self): + Interface=self.mods['interfaceModule'].Interface;ui=Interface() + ui.RefreshSwitchbotWindow();ui.ToggleSwitchbotWindow() # no window yet: no-ops + calls=[] + ui.wndSwitchbot=types.SimpleNamespace(shown=True,IsShow=lambda:True,Hide=lambda:calls.append('hide'), + RefreshSwitchbotWindow=lambda:calls.append('refresh'),RefreshSwitchbotItem=lambda s:calls.append(('item',s)),Close=lambda:calls.append('close')) + game=self.mods['game'].GameWindow();game.interface=ui + game.RefreshSwitchbotWindow();game.RefreshSwitchbotItem(3);ui.ToggleSwitchbotWindow() + self.assertEqual(ui._Interface__HideWindows(),[ui.wndSwitchbot]);ui.HideAllWindows() + self.assertEqual(calls,['refresh',('item',3),'close','hide','hide']) if __name__=='__main__':unittest.main() diff --git a/tools/server/ava2-items/make_items.py b/tools/server/ava2-items/make_items.py index 871d8ed8..d21cbdaf 100644 --- a/tools/server/ava2-items/make_items.py +++ b/tools/server/ava2-items/make_items.py @@ -32,6 +32,8 @@ DESC={'ITEM_METIN':'可镶嵌到武器的空孔中。','ITEM_MATERIAL':'制作 # covers vnum..vnum+4). SASH_EFFECTS=('d:/ymir work/effect/etc/buff/buff_item6.mse','d:/ymir work/effect/etc/buff/buff_item7.mse', 'd:/ymir work/pc/common/effect/armor/acc_01.mse') +# Switchbot window (AVA2-PARITY-PLAN 阶段 1, client mt_switchbot = AVA2 uiswitchbot.py): its buttons and ui.ThinBoardCircle's frame. +SWITCHBOT_UI=('d:/ymir work/ui/switchbot/','d:/ymir work/ui/pattern/thinboardcircle/') SASH_LOCALE={'locale/en/ui/acce/acce_combine.tga':'locale/zh/ui/acce/acce_combine.tga', 'locale/en/ui/acce/acce_absorb.tga':'locale/zh/ui/acce/acce_absorb.tga'} # Per-subtype descriptions (override DESC). @@ -207,7 +209,9 @@ def prepare(ava,proto_reader,locale,output,tool,packer,wrap=lambda text:text): if not target.exists():shutil.copy2(files[q],target);copied+=1 mount_files=[q for q in files for _,d in MOUNT_MOBS.values() if q.startswith('d:/ymir work/npc_mount/%s/'%d)] if len({q.split('/')[3] for q in mount_files})!=len(MOUNT_MOBS):raise SystemExit('missing AVA2 mount models') - for q in shape_models()+effect_files(files)+mount_files: + switchbot_files=[q for q in files if q.startswith(SWITCHBOT_UI)] + if len(switchbot_files)