Integrate AVA2 native shop and refine mobile controls and locale tooltips

This commit is contained in:
shen
2026-10-19 07:13:56 -07:00
parent 1359eab806
commit 24c1b3b416
36 changed files with 3501 additions and 52 deletions
+11
View File
@@ -0,0 +1,11 @@
{
"active_original_products": 49,
"source_products": 217,
"qa_coins": 0,
"qa_orders": 0,
"qa_awards": 0,
"test_stack": 0,
"test_triggers": 0,
"game_sha256": "56975b48aa2fd40389c57eab84d017b0a2518cf6e1b573d967bf239f4ae04aba",
"db_sha256": "dc940401fe6ccc3410c8d90ce98d2a5bad2e2c023279665bcd664c008d011699"
}
+18
View File
@@ -0,0 +1,18 @@
[
{
"case": "wallet lock timeout",
"status": 6,
"elapsed_seconds": 2.17,
"unchanged": true
},
{
"case": "SQL connection lost before commit",
"status": 6,
"unchanged": true
},
{
"case": "SQL reconnect and persistent order replay",
"status": 0,
"unchanged": true
}
]
@@ -0,0 +1 @@
{"catalogue": 49, "pending": null, "quantity_before": 1, "scroll_before": 0.0, "balance": 0, "scroll_after": 0.06876790830945559, "quantity_after": 2, "widget_bound_confirmation": true, "all_icons": true}
@@ -0,0 +1 @@
{"quote": [900001, 1, 29, 71084], "confirmation": ["\u8d2d\u4e70 \u7269\u54c1\u5c5e\u6027\u8f6c\u6362\u79d8\u7c4d\uff1f", "\u4ef7\u683c\uff1a29 \u9f99\u5e01"], "display": ["\u539f\u4ef7 58\uff08\u4f18\u60e0 50%\uff09", " 29 \u9f99\u5e01"], "confirm_button": "\u786e\u8ba4"}
+27
View File
@@ -0,0 +1,27 @@
{
"at": 145.56300354003906,
"balance": 9749,
"dropped": [
{
"status": 0,
"token": "25f1ade2e0549b0e3f9e899b8dd84b1e",
"balance": 9749,
"time": 123.39399719238281
}
],
"pending": null,
"replies": [
[
"25f1ade2e0549b0e3f9e899b8dd84b1e",
0,
9749
]
],
"assertions": {
"one_additional_order": true,
"one_additional_unit": true,
"deducted_exactly": 29,
"same_token_replayed": true,
"pending_cleared": true
}
}
@@ -0,0 +1 @@
{"labels": ["[F5] \u526f\u672c\u4fe1\u606f", "[F6] \u6218\u6597\u901a\u884c\u8bc1", "[F7] \u751f\u7269\u5b66\u5bb6", "[F8] \u70b9\u51fb\u6362\u7ebf"], "passed": true, "encoding": "native locale bridge"}
+10
View File
@@ -0,0 +1,10 @@
{
"original_product": 170,
"vnum": 70002,
"quantity": 2,
"paid": 198,
"wallet_after": 0,
"award_rows": 2,
"each_award_count": 1,
"prototype_lookup_correct_after_sort": true
}
@@ -0,0 +1 @@
{"count": 49, "all_prototypes_and_icons": true, "offers": [{"price": 99, "vnum": 70002, "id": 170, "icon": "icon\\item\\70002.tga"}, {"price": 99, "vnum": 71234, "id": 172, "icon": "icon\\item\\71234.tga"}, {"price": 99, "vnum": 71254, "id": 177, "icon": "icon\\item\\71254.tga"}, {"price": 349, "vnum": 71502, "id": 3, "icon": "icon\\item\\71502.tga"}, {"price": 349, "vnum": 71505, "id": 6, "icon": "icon\\item\\71505.tga"}, {"price": 349, "vnum": 71508, "id": 9, "icon": "icon\\item\\71508.tga"}, {"price": 349, "vnum": 71511, "id": 12, "icon": "icon\\item\\71511.tga"}, {"price": 60, "vnum": 54003, "id": 78, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54006, "id": 79, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54009, "id": 80, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54012, "id": 81, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54015, "id": 82, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54018, "id": 83, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54021, "id": 84, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54024, "id": 85, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54027, "id": 86, "icon": "icon\\item\\54003.tga"}, {"price": 60, "vnum": 54030, "id": 87, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54033, "id": 88, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54036, "id": 89, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54039, "id": 90, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54042, "id": 91, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54045, "id": 92, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54048, "id": 93, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54051, "id": 94, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54054, "id": 95, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54057, "id": 96, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54060, "id": 97, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54063, "id": 98, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54066, "id": 99, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54069, "id": 100, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54072, "id": 101, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54075, "id": 102, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54078, "id": 103, "icon": "icon\\item\\54006.tga"}, {"price": 60, "vnum": 54126, "id": 183, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54129, "id": 184, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54132, "id": 185, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54135, "id": 186, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54138, "id": 187, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54141, "id": 188, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54144, "id": 189, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54147, "id": 190, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54150, "id": 191, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54153, "id": 192, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54156, "id": 193, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54159, "id": 194, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54162, "id": 195, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54168, "id": 197, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54171, "id": 198, "icon": "icon\\item\\54126.tga"}, {"price": 60, "vnum": 54174, "id": 199, "icon": "icon\\item\\54126.tga"}], "categories": [1, 2, 3, 5]}
+126
View File
@@ -0,0 +1,126 @@
[
{
"script": "test_applies.py",
"passed": true
},
{
"script": "test_attr_lock.py",
"passed": true
},
{
"script": "test_attr_lock_snapshots.py",
"passed": true
},
{
"script": "test_attr_lock_use.py",
"passed": true
},
{
"script": "test_attr_lock_views.py",
"passed": true
},
{
"script": "test_ava2_channel_registry.py",
"passed": true
},
{
"script": "test_ava2_chest.py",
"passed": true
},
{
"script": "test_ava2_dungeon_track.py",
"passed": true
},
{
"script": "test_ava2_pickup.py",
"passed": true
},
{
"script": "test_ava2_ticket_shop.py",
"passed": true
},
{
"script": "test_ava2_track.py",
"passed": true
},
{
"script": "test_battlepass.py",
"passed": true
},
{
"script": "test_bosses.py",
"passed": true
},
{
"script": "test_calendar.py",
"passed": true
},
{
"script": "test_chest.py",
"passed": true
},
{
"script": "test_cmd_prefix.py",
"passed": true
},
{
"script": "test_costume_attr.py",
"passed": true
},
{
"script": "test_drops.py",
"passed": true
},
{
"script": "test_itemshop.py",
"passed": true
},
{
"script": "test_mount.py",
"passed": true
},
{
"script": "test_native_queries.py",
"passed": true
},
{
"script": "test_pendant.py",
"passed": true
},
{
"script": "test_pickup.py",
"passed": true
},
{
"script": "test_queries.py",
"passed": true
},
{
"script": "test_rings.py",
"passed": true
},
{
"script": "test_sash.py",
"passed": true
},
{
"script": "test_stone_socket.py",
"passed": true
},
{
"script": "test_switchbot.py",
"passed": true
},
{
"script": "test_switchbot_matching.py",
"passed": true
},
{
"script": "test_travel.py",
"passed": true
},
{
"script": "test_vip.py",
"passed": true
}
]
+57
View File
@@ -0,0 +1,57 @@
[
{
"case": "same token replays original purchase",
"status": 0,
"unchanged": true
},
{
"case": "same token changed quantity refused",
"status": 7,
"unchanged": true
},
{
"case": "insufficient coins",
"status": 1,
"unchanged": true
},
{
"case": "weekly quantity limit",
"status": 2,
"unchanged": true
},
{
"case": "monthly quantity limit",
"status": 3,
"unchanged": true
},
{
"case": "stock remaining less than quantity",
"status": 4,
"unchanged": true
},
{
"case": "expired offer",
"status": 5,
"unchanged": true
},
{
"case": "disabled product",
"status": 6,
"unchanged": true
},
{
"case": "missing prototype",
"status": 6,
"unchanged": true
},
{
"case": "price changed after confirmation",
"status": 9,
"unchanged": true
},
{
"case": "award insert failure rolls back wallet stock order",
"status": 6,
"unchanged": true
}
]
+1
View File
@@ -0,0 +1 @@
{"search_matches": 1, "balance": 9852, "subcategories": [[0, 0], [0, 1], [0, 2], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 0], [3, 1], [3, 2], [5, 0], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5]], "catalogue_count": 1}
@@ -0,0 +1 @@
{"after": 2, "confirmed_count": 2, "id": 84, "before": 1}
+16
View File
@@ -0,0 +1,16 @@
{
"device": "Mi 8 Lite",
"android": "15",
"server": "in-process offline fixture; production untouched",
"distance_before": 1550.002197265625,
"distance_spread": 774.980712890625,
"distance_closed": 1549.99169921875,
"position_unchanged": true,
"drawer_touch_opened": true,
"final_skill_layout": "original arc restored per user feedback",
"secondary_menu_visual_scale": 0.72,
"minimum_hit_target_dp": 48,
"native_touch_and_camera_test": "MT_TEST_MOBILE=1 MT_TEST_PINCH=1 MT_TEST_WIKI=1 port_login_flow_test",
"layout_test": "tests/host/touch_layout_test.cpp",
"note": "Pinch and drawer tested with injected Android MotionEvents; final visual layout checked separately on device."
}
+2
View File
@@ -660,3 +660,5 @@
{"time": "2026-10-19T04:37:42.044205+00:00", "event": "authorized_ava2_extension", "unit": "ScriptLib/AttrLockViewsScript", "finding": "AVA2 lock-line styling extended to existing exchange, shop/builder, safebox/mall and GM equipment tooltip setters using bounded read-only contextual queries. Base item packets and CWindow algorithms unchanged.", "evidence": ["docs/AVA2-ATTR-LOCK-VIEWS.md", "tests/wiki/test_attr_lock_ui.py", "tests/wiki/test_attr_lock_views.py"], "result": "macOS/sbtest two-player trade/shop/storage and real GM equipment lock highlights verified; ordinary equipment queries and closed contexts denied. 126 client tests and native macOS/Android builds passed; fixtures and temporary test GM removed. Active switchbot/hyperlink lock metadata remains pending; no aggregate parity upgrade."}
{"time": "2026-10-19T05:08:12.881941+00:00", "event": "authorized_ava2_extension", "unit": "ScriptLib/AttrLockSnapshotsScript", "finding": "Owner metadata follows existing item packets; bounded post-entry synchronization bridges loading-phase command loss. Versioned seven-slot chat snapshots and active switchbot lock lines preserve the classic wire layouts and original CWindow algorithms. Chinese active descriptions use measured text width.", "evidence": ["docs/AVA2-ATTR-LOCK-SNAPSHOTS.md", "tests/wiki/test_attr_lock_snapshots.py", "docs/AVA2-PARITY-PLAN.md"], "result": "132 client tests and macOS/Android offline builds passed. macOS/sbtest first-entry sync, immutable link/relay, active roll/stop, slot moves and same-process relogin passed. Final layout measured 348 versus longest text 308; test weapon/902 switchers and original unlocked state restored. Production unchanged; no aggregate parity upgrade."}
{"time": "2026-10-19T06:35:09.108370+00:00", "event": "authorized_ava2_extension", "unit": "ScriptLib/Ava2NativeSystems", "finding": "Vendor active AVA2 uiBattlePassEx, uiWiki/WikiUI, uiDropItem and uiEventCalendarNew; preserve classic SHOP_SIGN39 by moving event payload to GC214, configured-db battlepass persistence, real loaded drop data and original CWindow algorithms. Correct active-versus-legacy protocol mapping.", "evidence": ["docs/AVA2-NATIVE-SYSTEMS.md", "tests/wiki/test_native_systems.py", "tools/ava2-native/sources.json", "docs/AVA2-PARITY-PLAN.md"], "result": "146 client tests, 30 server feature scripts with updated version-marker retest, native macOS/Android offline builds; sbtest mission/final idempotency, persistent native views, drop data, scoped calendar/icon verified. Production game a8d606ea deployed; backup /root/backup-native-systems/20261019-083154. No aggregate parity upgrade; phone not tested."}
{"time": "2026-10-19T13:52:09.182541+00:00", "event": "authorized_ava2_extension", "unit": "ScriptLib/Ava2ItemShop", "finding": "Vendor active uiitemshopnew.py; native GC93 and authenticated GD/DG76, InnoDB wallet/catalogue/order/award transaction, durable token and confirmed quote, bounded atomic decoder, native UI locale/event/scroll/preview adapters. Correct db prototype pointer index after sort. Classic item layout and CWindow algorithms remain unchanged.", "evidence": ["docs/AVA2-ITEMSHOP.md", "tests/wiki/test_itemshop.py", "tools/ava2-native/sources.json", "audit/evidence/itemshop/"], "result": "157 client tests; 31 server feature scripts including native-layout, integer-total and real prototype-index body tests. macOS/sbtest purchase, redemption, refusal/rollback, restart replay, SQL loss/lock timeout, lost-result retry and real widget callbacks verified. 49 original offers with matching IDs/prices/icons enabled only on sbtest; other 168 and recharge/wheel remain closed. Android offline build only; no production deployment or aggregate parity upgrade."}
{"time": "2026-10-19T14:13:41.385041+00:00", "event": "authorized_mobile_ui_fix", "unit": "ScriptLib/MobileHUD and host/TouchController", "finding": "Fix UTF-8 minimap tooltip boundaries. Retain original skill arc per user feedback; smaller secondary menu artwork with 48dp hit targets, compact menus with drawer and native shop entry. Proportional two-finger camera zoom, stationary-stick fix and gesture cancellation.", "evidence": ["tests/wiki/test_minimap_buttons.py", "tests/port/port_login_flow_test.cpp", "audit/evidence/mobile-ui/acceptance.json", "audit/evidence/itemshop/minimap-tooltips.json", "docs/ANDROID-TESTING.md"], "result": "158 Python tests; focused real TouchController/camera offline flow; Mi 8 Lite Android multi-pointer and menu checks. No production deployment or aggregate parity upgrade."}
+22
View File
@@ -48,3 +48,25 @@ ANDROID_SERIAL=<serial> python3 tools/perf/run_render_isolation.py build/qa/devi
```
每段排除首个加载后的采样窗口,记录 6 个 2 秒窗口;输出 CSV、截图、内存快照和汇总 JSON,结束后恢复正常登录启动。
## 手机操作与布局(2026-10-19)
根据本轮用户反馈,六个技能保留原先围绕右下攻击键的弧形排列,道具和自动狩猎位置随原技能布局保持一致。
菜单按钮图形缩小28%,同时保留至少48dp触摸区域;头像和战斗按钮不随次要菜单缩小。
角色、背包、好友、设置及商城/更多排在小地图左侧;任务、挂机设置、帮助、聊天在“更多”中展开。
左侧保留移动摇杆和主要视野,副本/战令/生物学家入口继续在小地图外环。
场景空白处双指张开拉近、收拢拉远;左右手先后落下均可,界面和战斗按钮优先接收各自手势。
已经推动的摇杆不会被新落下的右手抢作缩放。缩放直接按指距比例改变镜头距离,原镜头距离上限和地形碰撞仍有效。
系统取消触摸或应用失去焦点时清掉残留手势;摇杆停在中心时不再误发送移动。
可重复的离线手势检查(真实TouchController和镜头,未连接正式服):
```sh
cmake --build build/native --target port_login_flow_test -j4
MT_TEST_MOBILE=1 MT_TEST_PINCH=1 MT_TEST_WIKI=1 \
build/native/src/port/port_login_flow_test "$PWD/build/ava2-parity-20261018/Client" "$PWD/build/native/python27.zip"
```
`MT_TEST_PINCH`只运行加载及移动端镜头/折叠菜单验收,跳过无关的频道状态探测和后续经典交互测试。
布局边界和按钮不重叠由 `tests/host/touch_layout_test.cpp` 覆盖不同屏宽、刘海留白和最小触摸尺寸。
+94
View File
@@ -0,0 +1,94 @@
# AVA2 原生商城移植
## 范围与入口
活动版本为 AVA2 `uiitemshopnew.py`,不是旧 `uiitemshop.py` / `uiitemshop_v2.py`。
原始 Python 源码由 `tools/ava2-native/import_sources.py` 转码后原样嵌入,SHA256 记录在
`tools/ava2-native/sources.json`。兼容、汉化及服务端接入位于 `Ava2ItemShopScript.inc`。
桌面入口:**F9**,以及与 AVA2 相同的任务栏圆形商城入口。经典商城仓库入口保留用于领货。
包含八个主分类、17 个子分类、名称搜索、热销、折扣、数量 1–20、购买确认、余额、库存、最近100笔购买记录、可支持道具的模型预览。
鼠标滚轮在商城列表中滚动,指针在商城窗口内时不改变游戏镜头。
充值按钮和幸运转盘保留“尚未开放”提示;不访问 AVA2 提供者的网站,不显示随机假奖励。
它们需要各自的支付服务/奖励池和玩法验收,不能由商城窗口本身代替。
## 协议与经济规则
- 客户端 GC93:5字节头(BYTE + DWORD 长度),总长 6–32768;完整收齐后再分发。
- 原生目录 `TIShopData` 49字节、记录 `TIShopLogData` 90字节。目录/记录整帧验证成功后才替换界面状态。
- game/db 使用空闲 GD/DG76。请求为固定103字节;响应封套包含 account、player、payload size。
- `/ishop data -1`、`/ishop log`,购买扩展为 `/ishop buy id count token quoted_total quoted_vnum`。
token为32位随机十六进制串,绑定一次确认;超时最多重发3次,保持同一token。
- 新客户端标识 `mt20261020`。game 仅接受这个版本及之后的商城请求,避免旧客户端收到未知GC93。
- game按账号/角色构建请求,db再次检查在线账号所属peer和角色归属;返回时校验账号、角色和game阶段。
- db按配置的SQL_ACCOUNT定位龙币,使用配置的SQL_PLAYER连接执行跨库InnoDB事务,禁止硬编码正式库名。
SQL_ACCOUNT/SQL_PLAYER必须指向同一MySQL主机和端口;否则商城拒绝购买。
- 同一事务锁定账号和商品,检查余额、有效期、数量、库存、周/月按件数限购及报价,再扣币、更新库存、写订单和商城发货记录。
- 订单唯一键 `(account_id,token)`。重放同一订单不会再次扣币;更换数量、商品或报价的重放被拒绝。
- 总价统一使用整数:`unit * count * (100-discount) / 100` 向下取整。
修复原版浮点误差(58龙币、五折应为29)以及折扣数量计算不一致。
- 确认框打开后若商品或售价变化,拒绝付款并刷新,不按新价格直接扣款。
- SQL连接在事务期间禁用自动重连,锁等待上限3秒。COMMIT结果不明确时保留原token重试。
- 周期边界采用数据库时区的周一零点/每月一日零点。
- 修复旧db在排序前建立道具指针索引的问题:排序完成后再建立映射,保证目录、堆叠属性和仓库发货使用正确模板。
- 发货插入现有 `item_award`、`mall=1`,沿用商城仓库领取链路;非堆叠物品逐件发放。
背包满、掉线和关闭窗口不删除已付款的发货记录。
未改变经典物品7条属性/3个socket及CWindow算法。当前AVA2对齐整体仍为PARTIAL。
## 商品数据
从 `AVA2/2. Backup SF+SRC and SQL/MYSQL56.tgz` 恢复出 **217条** `player.ishop_data`。
原价、分类、折扣、时间、销量、限购和限量字段保存在服务端
`data/ava2-itemshop/original-products.tsv`,来源散列另见该目录的 `source.json`。
当前服务端模板核对:**55条缺模板,55条对应ITEM_NONE占位物品,107条有实际类型但仍须逐项确认玩法和资源**。
这些数量不能理解为217条商品均可售卖。兼容清单见服务端 `compatibility.json`。
迁移默认将217条全设为停用。已依据现有坐骑、外观强化和拾取实现整理 `verified-products.json`:
**49件原版商品**已在sbtest启用,全部通过当前客户端模板、图标和目录接收验证,售价保持AVA2原价。
包括4件永久坐骑、2件坐骑外观、42件时装/发型/坐骑外观强化石、1件第三只手。
其余168条继续保持停用;实际类型存在不代表对应玩法和模型已经完整。
测试商品900001在验收后撤下。没有给正式玩家发币或上架未完成道具。
## 构建、测试与交付状态
候选客户端:`dist/itemshop/Metin2.app`。Android仅离线编译,按用户要求未测手机真机。
自动化测试覆盖原生布局、截断/重复/越界帧、整数折扣、冻结报价、双击保护、重试和节流。
真实sbtest验收结果及二进制散列见本文件的验收记录。
**正式服仍运行此前的原生战令/百科/日历版本;这次商城尚未部署到正式服。**
正式上线需要先备份账号和发货表,再执行服务端迁移并同步更新game/db;候选客户端不能单独让旧服务端具有商城能力。
## 数据库迁移
服务端运行:
```
python3 tools/ava2-itemshop/migrate.py --player player_sb --account account_sb --output /tmp/itemshop.sql
```
先审阅SQL和备份,再用MySQL执行。正式服使用实际配置的库名,不能照抄sbtest库名。
对已确认实现的49件商品,可另生成并审阅:
```
python3 tools/ava2-itemshop/enable_verified.py --player player_sb --output /tmp/itemshop-enable.sql
```
该脚本核对原商品ID、vnum和实际模板类型,只改开关,不改售价。
迁移将目录、订单、账号和发货表转为InnoDB,并在必要时添加龙币列;重复执行不重置余额、库存、订单或已有商品开关。
回滚二进制时保留订单和发货记录,避免抹掉玩家已付款的物品。不要把账号表改回MyISAM。
## 本轮验收记录(2026-10-19)
158项客户端Python测试和31个服务端功能脚本通过。sbtest确认49件原商品目录、原价、图标、原型一致;
购买、商城仓库领货、非堆叠逐件发货、重复请求、报价改变、余额/库存/限购/过期拒绝、SQL回滚、锁等待和断线恢复均已验证。
故意丢弃一次成功响应后,客户端用同一token重试,数据库只产生一笔扣币及发货。
测试币、订单、发货、道具及触发器已清理;sbtest game/db已重启,正式服二进制保持不变。
具体结果及最新sbtest game/db SHA256见 `audit/evidence/itemshop/`。
小地图F5/F6/F7/F8、扩展栏自动洗练/百科提示统一通过本地代码页桥接。
已在实际客户端确认F7“生物学家”正常显示,修复并非只改源文字。
候选Android包 `dist/itemshop/Metin2-Android.apk`;外置资源增量位于 `dist/itemshop/Client-patch/pack/`。
APK不内含全部游戏地图包,手机安装时另行同步完整的候选Client资源。
+7
View File
@@ -162,3 +162,10 @@ AVA2 功能包头号在当前服务端基本空闲,可以直接沿用:
战令沿用现有赛季与进度/领取主键;百科模板和掉落来自当前203数据,日历展示实际已接入的月光宝箱/圣诞袜排期。
其他活动的服务端玩法、宠物等不因迁移窗口自动完成,整体 AVA2 对齐仍为 PARTIAL。
详见 [AVA2-NATIVE-SYSTEMS.md](AVA2-NATIVE-SYSTEMS.md),生产部署证据在同文档中单列。
### 2026-10-19:原生商城
AVA2活动版本 `uiitemshopnew.py` 已接入原生GC93和GD/DG76,事务扣币、限购、库存、订单去重与商城仓库发货;
新增确认报价校验,修复原版折扣数量/浮点误差和失效的目录更新。
原217条商品配置已恢复,sbtest先开放49件已有玩法和资源的原版商品;其他168条依赖未闭合,充值/转盘未开放。
正式服本轮未更新。详见 [AVA2-ITEMSHOP.md](AVA2-ITEMSHOP.md)。
+5 -1
View File
@@ -261,7 +261,10 @@ bool VulkanWindow::poll(bool forward_to_live_client) {
} else if (event.type == SDL_EVENT_FINGER_MOTION) {
touch_controller.on_finger_motion(event.tfinger.fingerID, event.tfinger.x, event.tfinger.y);
continue;
} else if (event.type == SDL_EVENT_FINGER_UP || event.type == SDL_EVENT_FINGER_CANCELED) {
} else if (event.type == SDL_EVENT_FINGER_CANCELED) {
touch_controller.cancel_gestures();
continue;
} else if (event.type == SDL_EVENT_FINGER_UP) {
touch_controller.on_finger_up(event.tfinger.fingerID, event.tfinger.x, event.tfinger.y);
continue;
}
@@ -275,6 +278,7 @@ bool VulkanWindow::poll(bool forward_to_live_client) {
SDL_HideCursor();
os_cursor_hidden_ = true;
} else if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) {
touch_controller.cancel_gestures();
SDL_CaptureMouse(false);
PythonBoot::UIMouseButton(2, false, last_mx_, last_my_);
PythonBoot::UIMouseButton(3, false, last_mx_, last_my_);
+63 -17
View File
@@ -33,12 +33,24 @@ public:
}
void set_enabled(bool enabled) {
if (enabled_ && !enabled) cancel_gestures();
enabled_ = enabled;
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
PythonBoot::SetTouchInput(enabled);
#endif
}
bool is_enabled() const { return enabled_; }
// OS cancellation/focus loss must discard gestures without synthesizing a world tap.
void cancel_gestures() {
release_gameplay_controls();
ui_touch_finger_id_ = -1;
ui_gesture_ = UiGesture::None;
tap_stage_ = 0;
keyboard_requested_ = false;
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
PythonBoot::SetInventoryDrag(false);
#endif
}
void set_minimum_touch_target(float logicalSize) { minimum_touch_target_ = std::max(48.0f, logicalSize); }
// Short vibration when a long press fires (the host wires it to the platform).
void set_haptic(void (*haptic)()) { haptic_ = haptic; }
@@ -110,7 +122,8 @@ public:
controls_were_visible_ = true;
if (joystick_active_) {
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
PythonBoot::SetMoveDirection(move_angle_, true);
PythonBoot::SetMoveDirection(move_angle_,
std::hypot(joystick_last_x_ - joystick_base_x_, joystick_last_y_ - joystick_base_y_) > 8.0f);
#endif
}
}
@@ -165,12 +178,38 @@ public:
}
#endif
// PORT: two scene fingers own a pinch before the second can become a joystick.
// A stationary new left thumb may join the pinch; an established moving stick stays movement.
if (controls_visible && pinch_finger_id_ >= 0)
return true; // Additional scene fingers cannot steal an ongoing pinch.
if (controls_visible) {
if (look_finger_id_ == finger_id) return true;
if (look_finger_id_ >= 0) {
begin_pinch(finger_id, px, py);
return true;
}
if (joystick_active_ && !joystick_moved_) {
look_finger_id_ = joystick_finger_id_;
look_last_x_ = joystick_last_x_;
look_last_y_ = joystick_last_y_;
look_can_rotate_ = true;
joystick_active_ = false;
joystick_finger_id_ = -1;
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
PythonBoot::SetMoveDirection(0.0f, false);
#endif
begin_pinch(finger_id, px, py);
return true;
}
}
// Mobile-game layout: the left half moves (floating stick), the right half looks.
if (controls_visible && norm_x < kMoveZoneRight && norm_y > kMoveZoneTop && !joystick_active_) {
joystick_active_ = true;
joystick_finger_id_ = finger_id;
joystick_base_x_ = px;
joystick_base_y_ = py;
joystick_base_x_ = joystick_last_x_ = px;
joystick_base_y_ = joystick_last_y_ = py;
joystick_moved_ = false;
joystick_knob_x_ = px;
joystick_knob_y_ = py;
update_joystick_motion(px, py);
@@ -195,15 +234,6 @@ public:
#endif
return true;
}
if (pinch_finger_id_ < 0 && look_can_rotate_ && in_look_zone) {
pinch_finger_id_ = finger_id;
pinch_x_ = px;
pinch_y_ = py;
pinch_last_dist_ = std::hypot(px - look_last_x_, py - look_last_y_);
look_rotating_ = false;
look_moved_ = true; // a pinch never ends as a tap
return true;
}
return false;
}
@@ -234,6 +264,10 @@ public:
// 2. Virtual Joystick finger
if (joystick_active_ && finger_id == joystick_finger_id_) {
joystick_last_x_ = px;
joystick_last_y_ = py;
if (std::hypot(px - joystick_base_x_, py - joystick_base_y_) > kLookDeadZone)
joystick_moved_ = true;
update_joystick_motion(px, py);
return true;
}
@@ -253,7 +287,7 @@ public:
}
}
// 4. Two-finger pinch zoom (look finger + second right-half finger)
// 4. Two-finger scene pinch: scale camera distance, without wheel inertia or UI scrolling.
if (pinch_finger_id_ >= 0 && (finger_id == pinch_finger_id_ || finger_id == look_finger_id_)) {
if (finger_id == pinch_finger_id_) {
pinch_x_ = px;
@@ -263,13 +297,13 @@ public:
look_last_y_ = py;
}
const float cur_dist = std::hypot(pinch_x_ - look_last_x_, pinch_y_ - look_last_y_);
const float delta_d = cur_dist - pinch_last_dist_;
if (std::abs(delta_d) > 2.0f) {
// Rebase very close/crossed fingers instead of dividing by a near-zero span.
if (cur_dist >= 24.0f && pinch_last_dist_ >= 24.0f) {
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
PythonBoot::UIMouseWheel(int(delta_d * 8.0f));
PythonBoot::CameraZoomBy(pinch_last_dist_ / cur_dist);
#endif
pinch_last_dist_ = cur_dist;
}
pinch_last_dist_ = cur_dist;
return true;
}
@@ -615,6 +649,16 @@ public:
}
private:
void begin_pinch(int64_t finger_id, float px, float py) {
pinch_finger_id_ = finger_id;
pinch_x_ = px;
pinch_y_ = py;
pinch_last_dist_ = std::hypot(px - look_last_x_, py - look_last_y_);
look_rotating_ = false;
look_can_rotate_ = true;
look_moved_ = true; // Neither finger may turn into a tap after pinching.
}
bool gameplay_controls_visible() const {
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
return PythonBoot::InGamePhase() && !PythonBoot::CurrentMapName().empty();
@@ -904,6 +948,8 @@ private:
float joystick_radius_ = 65.0f;
float joystick_knob_radius_ = 23.0f;
float move_angle_ = 0.0f;
float joystick_last_x_ = 0.0f, joystick_last_y_ = 0.0f;
bool joystick_moved_ = false;
// Zones are fractions of the screen; distances are logical UI pixels.
static constexpr float kMoveZoneRight = 0.5f;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,248 @@
// Native shop platform glue; original AVA2 source is kept byte-equivalent after encoding normalization.
static const char c_szAva2ShopSupportScript[]=R"PY(# -*- coding: utf-8 -*-
import localeInfo,app,item
item.ITEM_FLAG_STACKABLE=1<<2
app.ENABLE_RENDER_TARGET=True
app.ENABLE_MOUSEWHEEL_EVENT=True
import ui
ui.Window.SetMouseWheelScrollEvent=lambda self,event:setattr(self,'onMouseWheelScrollEvent',event)
from mt_biolog import L
LOCALE={'CATEGORY_0_NAME': 'Offers', 'CATEGORY_0_SUB_0_NAME': 'Battle pass', 'CATEGORY_0_SUB_1_NAME': 'Special packs', 'CATEGORY_0_SUB_2_NAME': 'Special Offers', 'CATEGORY_1_NAME': 'Special Objects', 'CATEGORY_2_NAME': 'Cosmetics', 'CATEGORY_2_SUB_0_NAME': 'Weapons Skins', 'CATEGORY_2_SUB_1_NAME': 'Body Costume', 'CATEGORY_2_SUB_2_NAME': 'Hairstyles', 'CATEGORY_2_SUB_3_NAME': 'Sash Skin', 'CATEGORY_2_SUB_4_NAME': 'Mount Skin', 'CATEGORY_3_NAME': 'Pets and mounts', 'CATEGORY_3_SUB_0_NAME': 'Mounts', 'CATEGORY_3_SUB_1_NAME': 'Leveable pets', 'CATEGORY_3_SUB_2_NAME': 'Normal pets', 'CATEGORY_4_NAME': 'Dungeons', 'CATEGORY_5_NAME': 'Reinforce Costume', 'CATEGORY_5_SUB_0_NAME': 'Weapon Skin', 'CATEGORY_5_SUB_1_NAME': 'Body Costume', 'CATEGORY_5_SUB_2_NAME': 'Hairstyles', 'CATEGORY_5_SUB_3_NAME': 'Mount Skin', 'CATEGORY_5_SUB_4_NAME': 'Sash Skin', 'CATEGORY_5_SUB_5_NAME': 'Effects', 'CATEGORY_6_NAME': 'Alchemy', 'CATEGORY_7_NAME': 'Equipment', 'ITEMSHOP_BUY': 'Comprar', 'ITEMSHOP_BUY_COIN': 'Home', 'ITEMSHOP_BUY_TEXT': 'Wanna buy |cffF7BD48%s|r ?', 'ITEMSHOP_BUY_TEXT_COUNT': 'Wanna buy |cffF7BD48%sx%d|r ?', 'ITEMSHOP_DRAGONCOINT': 'Dragon Coins', 'ITEMSHOP_HOTITEMS': '|Eishop/hot|ePOPULAR', 'ITEMSHOP_ITEMSEARCH_DEFAULT_TEXT': 'Search the itemshop ...', 'ITEMSHOP_LAST_COUNT': 'Remaining amount: %d', 'ITEMSHOP_OFFERS': '|Eishop/offer|e OFFERS', 'ITEMSHOP_PRICE_NEW': '|Eishop/mini_coin|e %s Coins', 'ITEMSHOP_PRICE_ONLY_TEXT': '%s Coins', 'ITEMSHOP_PRICE_WITH_DISCOUNT': '|Eishop/mini_coin|e |cffFF7B7B%s Coins (%d%%)', 'ITEMSHOP_PURCHASES': 'SHOPPING', 'ITEMSHOP_WHEEL': '|Eishop/wheel_icon|e Roulette', 'ITEMSHOP_WHEEL_BACK_ISHOP': 'Itemhop go back', 'ITEMSHOP_WHEEL_COIN_TEXT': ' |Eishop/coin|e Price: 10 Coins', 'ITEMSHOP_WHEEL_COIN_TEXT_INFO': 'You will use |cffF7BD48Coins|r to spin.', 'ITEMSHOP_WHEEL_PURCHASE': '|Eishop/wheel_icon|e |cffF7BD48Fortune roulette|r', 'ITEMSHOP_WHEEL_SKIP_ANIMATION': 'Skip animation', 'ITEMSHOP_WHEEL_TICKET_TEXT': '|Eishop/wheel_ticket|e x1 ticket', 'ITEMSHOP_WHEEL_TICKET_TEXT_INFO': 'Your are using |cffF7BD48Roulette ticket|r to spin.', 'PURCHASES_ACCOUNTID': 'ID account', 'PURCHASES_DATE': 'Date', 'PURCHASES_IP': 'IP', 'PURCHASES_ITEMBOUGHT': 'Purchased object', 'PURCHASES_PRICE': 'Price', 'PURCHASES_PRICE_TEXT': '|Eishop/mini_coin|e |cfff7bd48%s dragon coins', 'UI_CANCEL': 'Cancel', 'UI_OK': 'OK', 'WHEEL_REWARD_TEXT': 'You have received', 'WHEEL_REWARD_TEXT_1': 'In your inventory', 'WHEEL_REWARD_TITLE': 'Roulette reward', 'YES': 'Buy'}
ZH={'YES':'确认','ITEMSHOP_BUY_COIN': '充值', 'ITEMSHOP_WHEEL': '幸运转盘', 'ITEMSHOP_PURCHASES': '购买记录', 'ITEMSHOP_HOTITEMS': '热销商品', 'ITEMSHOP_OFFERS': '限时优惠', 'ITEMSHOP_ITEMSEARCH_DEFAULT_TEXT': '搜索道具名称', 'ITEMSHOP_DRAGONCOINT': '龙币', 'ITEMSHOP_BUY': '购买', 'ITEMSHOP_BUY_TEXT': '购买 %s?', 'ITEMSHOP_BUY_TEXT_COUNT': '购买 %s × %d?', 'ITEMSHOP_PRICE_NEW': '价格:%s 龙币', 'ITEMSHOP_PRICE_ONLY_TEXT': '%s 龙币', 'ITEMSHOP_PRICE_WITH_DISCOUNT': '原价 %s(优惠 %d%%)', 'ITEMSHOP_LAST_COUNT': '剩余:%d', 'PURCHASES_PRICE_TEXT': '支付:%s 龙币', 'PURCHASES_DATE': '购买时间', 'PURCHASES_ACCOUNTID': '角色', 'PURCHASES_IP': '登录地址', 'PURCHASES_ITEMBOUGHT': '购买道具', 'PURCHASES_PRICE': '支付金额', 'ITEMSHOP_WHEEL_BACK_ISHOP': '返回商城'}
ZH.update({'CATEGORY_0_NAME': '精选优惠', 'CATEGORY_0_SUB_0_NAME': '战令', 'CATEGORY_0_SUB_1_NAME': '超值礼包', 'CATEGORY_0_SUB_2_NAME': '特别优惠', 'CATEGORY_1_NAME': '特殊道具', 'CATEGORY_2_NAME': '外观', 'CATEGORY_2_SUB_0_NAME': '武器外观', 'CATEGORY_2_SUB_1_NAME': '服装', 'CATEGORY_2_SUB_2_NAME': '发型', 'CATEGORY_2_SUB_3_NAME': '披风外观', 'CATEGORY_2_SUB_4_NAME': '坐骑外观', 'CATEGORY_3_NAME': '宠物与坐骑', 'CATEGORY_3_SUB_0_NAME': '坐骑', 'CATEGORY_3_SUB_1_NAME': '成长宠物', 'CATEGORY_3_SUB_2_NAME': '普通宠物', 'CATEGORY_4_NAME': '副本', 'CATEGORY_5_NAME': '外观强化', 'CATEGORY_5_SUB_0_NAME': '武器外观', 'CATEGORY_5_SUB_1_NAME': '服装', 'CATEGORY_5_SUB_2_NAME': '发型', 'CATEGORY_5_SUB_3_NAME': '坐骑外观', 'CATEGORY_5_SUB_4_NAME': '披风外观', 'CATEGORY_5_SUB_5_NAME': '特效', 'CATEGORY_6_NAME': '龙魂炼金', 'CATEGORY_7_NAME': '装备'})
for key,value in LOCALE.items():
if not hasattr(localeInfo,key):setattr(localeInfo,key,L(value))
for key,value in ZH.items():setattr(localeInfo,key,L(value))
)PY";
static const char c_szAva2ItemShopScript[]=R"PY(# -*- coding: utf-8 -*-
import app,chat,constInfo,game,net,os,struct,types,ui
import uiItemShopNew as native
from mt_biolog import L
# AVA2 ui.py calculateRect, retained for the native list's clipping rectangles.
def calculateRect(curValue,maxValue):
try:return -1.0+float(curValue)/float(maxValue)
except:return 0.0
ui.calculateRect=calculateRect
window=None;pending=None;_serial=0;_next=0;_waiting=False;_requested=0;_queued=False;_logAt=0
_product=struct.Struct('<IIqiBiiqiii');_log=struct.Struct('<I25s21si16sIIiq')
ERRORS={1:'龙币不足。',2:'超过本周限购数量。',3:'超过本月限购数量。',4:'商品库存不足。',5:'商品优惠已过期。',6:'商城暂不可用,请稍后重试。',7:'订单编号冲突,请重新登录。',9:'商品或价格已变化,请确认最新信息后重试。'}
# AVA2 image callbacks include an event tag; classic image callbacks omit it.
# Adapt only this module's handlers; preserve the original UI class hierarchy.
_MISSING=object()
def EventTag(original,arity):
# Classic ui.__mem_func__ dispatches arguments using co_argcount; keep an explicit parameter.
def call(self,first=_MISSING,*rest):
args=rest if first is _MISSING else (first,)+rest
if len(args)==arity-1:args=(None,)+args
return original(self,*args)
return call
for owner,name,arity in ((native.ItemShopWindow,'ClickCategory',3),(native.ItemShopWindow,'ClickBanner',3),(native.ItemShopItem,'ClickBuyBtn',1),(native.ItemShopItem,'ClickCount',2),(native.ItemShopItem,'ClickItem',2)):
if hasattr(owner,name):setattr(owner,name,EventTag(getattr(owner,name),arity))
def PreviewItem(self,event=None,vnum=None):
import mt_preview
mt_preview.Preview('item',int(event if vnum is None else vnum))
native.ItemShopItem.ClickItem=PreviewItem
# AVA2 submenu radio buttons notify the parent on tooltip leave.
class ShopRadio(ui.RadioButton):
def SetHideToolTipEvent(self,callback,*args):self.shopLeave=(callback,args)
def HideToolTip(self):
ui.RadioButton.HideToolTip(self)
event=getattr(self,'shopLeave',None)
if event:event[0](*event[1])
localUI=types.ModuleType('itemshop_ui');localUI.__dict__.update(ui.__dict__);localUI.RadioButton=ShopRadio;native.ui=localUI
# No random reward previews from an unported wheel service.
native.ItemShopWindow.SetTrailerMode=lambda self:self.children.update({'wheelStep':0,'circleRotation':0,'wheelRotation':0})
native.ItemShopWindow.UpdateSingleFortune=lambda self:None
_nativeUpdate=native.ItemShopWindow.OnUpdate
def NativeUpdate(self):
if self.children and 'wheelStep' in self.children:_nativeUpdate(self)
native.ItemShopWindow.OnUpdate=NativeUpdate
def Parse(raw):
if not raw:raise ValueError('empty shop frame')
op=struct.unpack_from('<B',raw)[0];offset=1
def read(fmt):
value=struct.unpack_from(fmt,raw,read.offset);read.offset+=struct.calcsize(fmt);return value
read.offset=1
if op==0:
coins,revision,categories=read('<qii')
if coins<0 or not 0<=categories<=8:raise ValueError('shop catalogue')
rows=[];seen=set();groups=set()
for unused in range(categories):
category,subcount=read('<BB')
if category>7 or subcount>10 or category in groups:raise ValueError('shop category')
groups.add(category);subs=set()
for unused2 in range(subcount):
sub,count=read('<BB')
if sub>9 or sub in subs:raise ValueError('shop subcategory')
subs.add(sub)
for unused3 in range(count):
p=read(_product.format)
if p[0] in seen or not p[0] or not p[1] or not 0<=p[2]<=1000000000000 or p[4]>100 or p[7]<0 or p[8]<0 or p[9]<0 or p[10]<-1:raise ValueError('shop product')
seen.add(p[0]);rows.append((category,sub,p))
result=(coins,revision,rows)
elif op==1:
count,=read('<i')
if not 0<=count<=100:raise ValueError('shop log size')
result=[read(_log.format) for unused in range(count)]
elif op==7:
token,status,coins=read('<32sBq')
if status>9 or coins<0 or any(c not in bytearray(b'0123456789abcdefABCDEF') for c in bytearray(token)):raise ValueError('shop result')
result=(token,status,coins)
elif op==8:result=None
else:raise ValueError('unknown shop message')
if read.offset!=len(raw):raise ValueError('trailing shop data')
return op,result
def Request():
global _waiting,_requested,_next,_queued
now=app.GetTime();_waiting=True;_requested=now;_queued=now<_next
if not _queued:net.SendChatPacket('/ishop data -1');_next=now+1.1
def Toggle():
global window
if window and window.IsShow():window.Close();return
if window is None:
window=native.ItemShopWindow();window.SetCenterPosition()
# Explicit refresh on every reopen; no stale balance, stock or expired offers.
window.children['sendPacketData']=1;window.Show();window.SetTop();window.children['LoadingImage'].Show();Request()
# Original ItemShopUpdateItem assigned to a loop variable, leaving stored rows unchanged.
def UpdateItem(itemID,itemVnum,itemPrice,discount,expiry,top,added,sold,stock):
for categories in native.itemshopData.values():
for rows in categories:
for index,row in enumerate(rows):
if row[0]==itemID:rows[index]=[itemID,itemVnum,itemPrice,discount,expiry,top,added,sold,stock]
native.ItemShopUpdateItem=UpdateItem
def Total(unit,count,discount):return unit*count*(100-discount)//100
_setPrice=native.ItemShopItem.SetPrice
def SetPrice(self,unit,discount):
_setPrice(self,unit,discount)
price=unit*self.buyCount
if discount:
text=native.localeInfo.ITEMSHOP_PRICE_WITH_DISCOUNT%(native.NumberToMoneyFormat(price),discount)
text+='\n '+native.localeInfo.ITEMSHOP_PRICE_ONLY_TEXT%native.NumberToMoneyFormat(Total(unit,self.buyCount,discount))
self.childrenTextLine['itemPrice'].SetText(text)
native.ItemShopItem.SetPrice=SetPrice
_setCoins=native.ItemShopWindow.SetDragonCoin
def SetCoins(self,value):
_setCoins(self,value);self.MoneyRange=abs(self.MoneyRange)
native.ItemShopWindow.SetDragonCoin=SetCoins
_buyClick=native.ItemShopItem.ClickBuyBtn
def BuyClick(self,*args):
unit=self.data[native.LIST_ITEM_PRICE];discount=self.data[native.LIST_ITEM_DISCOUNT]
total=Total(unit,self.buyCount,discount)
self.shopQuote=(self.data[native.LIST_ITEM_ID],self.buyCount,total,self.data[native.LIST_ITEM_VNUM])
_buyClick(self,*args)
if native.buyQuestionDialog:
native.item.SelectItem(self.shopQuote[3])
if self.buyCount>1:text=native.localeInfo.ITEMSHOP_BUY_TEXT_COUNT%(native.item.GetItemName(),self.buyCount)
else:text=native.localeInfo.ITEMSHOP_BUY_TEXT%native.item.GetItemName()
text+='\n'+native.localeInfo.ITEMSHOP_PRICE_NEW%total
native.buyQuestionDialog.SetText(text);native.buyQuestionDialog.SetCenterPosition()
native.ItemShopItem.ClickBuyBtn=BuyClick
def AcceptBuy(self):
global pending,_serial
if pending or not getattr(self,'shopQuote',None):return
_serial+=1
token=os.urandom(16).encode('hex')
product,count,total,vnum=self.shopQuote
pending=(token,product,count,app.GetTime(),0,total,vnum)
net.SendChatPacket('/ishop buy %d %d %s %d %d'%(pending[1],pending[2],pending[0],pending[5],pending[6]));self.CloseQuestionDialog()
native.ItemShopItem.AcceptBuy=AcceptBuy
# The source's wheel uses separate game services and reward configuration.
# Keep its entry unavailable until that service has been ported and validated.
def Wheel(self):chat.AppendChat(chat.CHAT_TYPE_INFO,L('幸运转盘尚未开放。'))
def Recharge(self):chat.AppendChat(chat.CHAT_TYPE_INFO,L('充值服务尚未开放。'))
native.ItemShopWindow.WheelBtn=Wheel;native.ItemShopWindow.BuyDragonCoin=Recharge
# Never open the vendor's external website.
native.ItemShopWindow.OpenWeb=lambda self,*args:None
def Receive(self,raw):
global window,pending,_waiting,_logAt
try:op,value=Parse(raw)
except (ValueError,struct.error,TypeError):
chat.AppendChat(chat.CHAT_TYPE_INFO,L('商城数据无效,请重新打开。'));return
if op==8:
_waiting=False;_logAt=0
if window:window.CloseLoading();window.children.pop('sendPacketDataLog',None)
chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS[6]));return
if op==0:
coins,revision,rows=value;native.itemshopData.clear();native.UPDATE_TIME=revision
for category,sub,p in rows:native.ItemShopAppendItem(category,sub,p[0],p[1],p[2],p[4],p[5],p[3],p[6],p[7],p[10])
_waiting=False
if window:window.SetDragonCoin(coins);window.CloseLoading();window.LoadFirstOpening()
elif op==1:
_logAt=0
native.ItemShopLogClear()
for p in value:native.ItemShopAppendLog(p[2].split('\0',1)[0],p[3],p[1].split('\0',1)[0],p[4].split('\0',1)[0],p[6],p[7],p[8])
if window:window.children['sendPacketDataLog']=1;window.CloseLoading();window.RefreshPurchasesWindow()
elif op==7:
token,status,coins=value
if not pending or pending[0]!=token:return
if status==8:return # Commit outcome uncertain: retry the same durable token.
pending=None
if window:window.SetDragonCoin(coins);window.children.pop('sendPacketDataLog',None)
chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS.get(status,'购买成功,道具已发往商城仓库。')))
Request()
_openLog=native.ItemShopWindow.OpenPurchasesWindow
def OpenLog(self):
global _logAt
if 'sendPacketDataLog' not in self.children:_logAt=app.GetTime()
_openLog(self)
native.ItemShopWindow.OpenPurchasesWindow=OpenLog
def Tick():
global pending,_waiting,_queued,_logAt
now=app.GetTime()
if _queued and now>=_next:Request()
if _logAt and now-_logAt>=10:
_logAt=0
if window:window.CloseLoading();window.children.pop('sendPacketDataLog',None)
chat.AppendChat(chat.CHAT_TYPE_INFO,L('购买记录请求超时,请重新打开。'))
if pending and now-pending[3]>=5:
# Re-send exactly the same durable order token; never create a replacement payment.
token,product,count,unused,attempt,total,vnum=pending
if attempt<3:net.SendChatPacket('/ishop buy %d %d %s %d %d'%(product,count,token,total,vnum));pending=(token,product,count,now,attempt+1,total,vnum)
elif attempt==3:
pending=(token,product,count,now,4,total,vnum);chat.AppendChat(chat.CHAT_TYPE_INFO,L('订单处理中,请查看购买记录;重新登录前不会再次扣款。'))
if _waiting and now-_requested>=10:
_waiting=False
if window:window.CloseLoading()
chat.AppendChat(chat.CHAT_TYPE_INFO,L('商城请求超时,请重新打开。'))
def HandleWheel(delta):
if not window or not window.IsShow() or not window.IsIn():return False
for key in ('itemListBox','categoryListBox','PurchasesListBox'):
box=window.children.get(key)
if box and box.IsShow() and box.IsIn():box.OnMouseWheel(delta);return True
return True
def Clear():
global window,pending,_waiting,_queued,_logAt,_next
if window:window.Close();window.Destroy();window=None
pending=None;_waiting=False;_queued=False;_logAt=0;_next=0;native.itemshopData.clear();native.ItemShopLogClear();native.UPDATE_TIME=-1
_open=game.GameWindow.Open;_close=game.GameWindow.Close;_update=game.GameWindow.OnUpdate
def Open(self):
_open(self);Clear()
self.interface.OpenItemMall=Toggle;self.interface.OpenItemShopWindow=Toggle;self.interface.OpenItemShopMainWindow=Toggle
self.onPressKeyDict[app.DIK_F9]=Toggle
# Existing classic cash-shop button now opens the native AVA2 catalogue.
if getattr(self.interface,'wndTaskBar',None):
task=self.interface.wndTaskBar
if hasattr(task,'SetItemShopEvent'):task.SetItemShopEvent(Toggle)
for name in ('rampageGauge1','rampageGauge2'):
gauge=getattr(task,name,None)
if gauge:gauge.OnMouseLeftButtonUp=Toggle
def Close(self):Clear();return _close(self)
def Update(self):_update(self);Tick()
game.GameWindow.Open=Open;game.GameWindow.Close=Close;game.GameWindow.OnUpdate=Update
game.GameWindow.BINARY_Ava2ItemShop=Receive
)PY";
@@ -8,6 +8,10 @@ import wndMgr
import mt_dungeons
import mt_battlepass
import mt_biolog
import player
# Source literals are UTF-8; classic text widgets consume the active locale code page.
L = player.AutoHuntLocalize
class MapTextToolTip(ui.Window):
@@ -25,7 +29,7 @@ class MapTextToolTip(ui.Window):
ui.Window.__del__(self)
def SetText(self, text):
self.textLine.SetText(text)
self.textLine.SetText(L(text))
def SetTooltipPosition(self, PosX, PosY):
self.textLine.SetPosition(PosX - 5, PosY)
@@ -146,7 +150,7 @@ class MinimapOuterRing(object):
btnSwitch.SetDownVisual("d:/ymir work/ui/game/new_inventory/switch_2.tga")
btnSwitch.SetPosition(37, 0)
if hasattr(btnSwitch, 'SetToolTipText'):
btnSwitch.SetToolTipText("自动洗练")
btnSwitch.SetToolTipText(L("自动洗练"))
btnSwitch.SetEvent(lambda: interface.ToggleSwitchbotWindow())
btnSwitch.Show()
wndExpandedTaskBar.btnSwitchbot = btnSwitch
@@ -165,7 +169,7 @@ class MinimapOuterRing(object):
btnWiki.SetDownVisual("d:/ymir work/ui/game/new_inventory/wiki_2.tga")
btnWiki.SetPosition(74, 0)
if hasattr(btnWiki, 'SetToolTipText'):
btnWiki.SetToolTipText("游戏百科")
btnWiki.SetToolTipText(L("游戏百科"))
btnWiki.SetEvent(wiki_toggle)
btnWiki.Show()
wndExpandedTaskBar.btnWiki = btnWiki
+40 -16
View File
@@ -33,6 +33,7 @@ class RoundAction(ui.Window):
self.action = action
self.down = False
self.active = False
self.visualScale = 1.0
self.label = _Text(self, text)
self.label.SetHorizontalAlignCenter()
self.label.SetVerticalAlignCenter()
@@ -51,22 +52,25 @@ class RoundAction(ui.Window):
self.SetSize(int(size), int(size))
self.label.SetPosition(int(size/2), int(size/2))
if self.icon:
edge = size * .62
edge = size * .62 * self.visualScale
self.icon.SetScale(edge / max(1, self.iconSize[0]), edge / max(1, self.iconSize[1]))
self.icon.SetPosition(int((size-edge)/2), int((size-edge)/2))
def OnRender(self):
x, y = self.GetGlobalPosition()
r = self.GetWidth()/2.0
diameter = max(1, int(self.GetWidth()*self.visualScale))
x += (self.GetWidth()-diameter)/2.0
y += (self.GetHeight()-diameter)/2.0
r = diameter/2.0
if getattr(self, "active", False):
grp.SetColor(0xEE207028 if self.down else 0xCC185820)
else:
grp.SetColor(0xE0664B2D if self.down else 0xBB281A16)
# Horizontal strips fill a round button without requiring extra image assets.
for row in xrange(0, self.GetHeight(), 3):
for row in xrange(0, diameter, 3):
dy = min(r, row + 1.5 - r)
half = math.sqrt(max(0, r*r - dy*dy))
grp.RenderBar(x+r-half, y+row, half*2, min(3, self.GetHeight()-row))
grp.RenderBar(x+r-half, y+row, half*2, min(3, diameter-row))
if getattr(self, "active", False):
grp.SetColor(0xFFB0FFB0 if self.down else 0xFF80FF90)
else:
@@ -214,10 +218,27 @@ class HUD(ui.Window):
self.btnAutoHunt,
RoundAction(self, "帮助", interface.OpenHelpWindow),
RoundAction(self, "聊天", interface.ToggleChat)]
import mt_itemshop
self.shop = RoundAction(self, "商城", mt_itemshop.Toggle)
self.menuExpanded = False
self.more = RoundAction(self, "更多", self.ToggleMore)
# Secondary menu art is 28% smaller; hit rectangles remain comfortably tappable.
for button in self.top + self.side + [self.shop, self.more]:
button.visualScale = .72
for button in self.side:
button.Hide()
self.dimensions = None
self.OnUpdate()
self.Show()
def ToggleMore(self):
self.menuExpanded = not self.menuExpanded
self.more.label.SetText(L("收起" if self.menuExpanded else "更多"))
self.more.active = self.menuExpanded
for button in self.side:
if self.menuExpanded: button.Show()
else: button.Hide()
def Show(self):
ui.Window.Show(self)
self.SetTop()
@@ -228,24 +249,27 @@ class HUD(ui.Window):
dimensions = (w, h, target)
if dimensions != self.dimensions:
self.dimensions = dimensions
s = max(target/52.0, min(1.35, max(.65, min(h/600.0, w/800.0))))
# Keep spacing compact while preserving the device's minimum hit target.
s = min(1.1, max(.65, min(h/600.0, w/800.0)))
self.SetSize(w, h)
self.status.Place(s)
self.experience.SetPosition(int(12*s), int(h-self.experience.GetHeight()-6*s))
self.experienceText.SetPosition(self.experience.GetWidth()+6, 10)
size, gap = max(target, 48*s), 8*s
for i, button in enumerate(self.top):
button.Place(w-12*s-(4-i)*(size+gap), 10*s, size)
for i, button in enumerate(self.side):
if h < 520 or s > 1.25:
button.Place(12*s+i*(size+gap), 140*s, size)
else:
button.Place(12*s, 140*s+i*(size+gap), size)
self.window.affectShower.SetPosition(int(18*s), int(104*s))
size, gap = max(target, 48*s), 6*s
minimap = self.window.interface.wndMiniMap
minimap.SetWindowHorizontalAlignLeft()
minimap.SetWindowVerticalAlignTop()
minimap.SetPosition(int(w-minimap.GetWidth()-12*s), int(72*s))
minimap.SetPosition(int(w-minimap.GetWidth()-12*s), int(10*s))
# Compact two-column menu beside the map, outside the combat/thumb regions.
menuX = w-minimap.GetWidth()-30*s-2*size-gap
for i, button in enumerate(self.top):
button.Place(menuX+(i%2)*(size+gap), 10*s+(i//2)*(size+gap), size)
moreY = 10*s+2*(size+gap)
self.shop.Place(menuX, moreY, size)
self.more.Place(menuX+size+gap, moreY, size)
for i, button in enumerate(self.side):
button.Place(menuX+(i%2)*(size+gap), moreY+(1+i//2)*(size+gap), size)
self.window.affectShower.SetPosition(int(18*s), int(104*s))
chat = self.window.interface.wndChat
chat.SetPosition(int(180*s), int(h-86*s))
chat.Refresh()
@@ -275,7 +299,7 @@ class HUD(ui.Window):
self.experience.Hide()
self.experience.SetParent(self.taskbar)
self.experience.SetPosition(*self.experiencePosition)
for button in self.top + self.side:
for button in self.top + self.side + [self.shop, self.more]:
button.action = None
self.window = None
+23
View File
@@ -418,6 +418,15 @@ void UIMouseButton(int button, bool pressed, int x, int y)
void UIMouseWheel(int nLen)
{
// AVA2 native shop consumes wheel input inside its list, before camera zoom.
PyObject* shop=PyDict_GetItemString(PyImport_GetModuleDict(),"mt_itemshop");
if(shop) {
PyObject* result=PyObject_CallMethod(shop,const_cast<char*>("HandleWheel"),const_cast<char*>("i"),nLen);
const bool handled=result && PyObject_IsTrue(result)>0;
Py_XDECREF(result);if(PyErr_Occurred())PyErr_Clear();
if(handled)return;
}
CCameraManager& rkCmrMgr = CCameraManager::Instance();
CCamera* pkCmrCur = rkCmrMgr.GetCurrentCamera();
if (pkCmrCur)
@@ -681,6 +690,15 @@ void CameraRotateBy(float rollDeg, float pitchDeg)
pkCmrCur->RotateEyeAroundTarget(pitchDeg, rollDeg);
}
void CameraZoomBy(float distanceRatio)
{
CCamera* camera = CCameraManager::Instance().GetCurrentCamera();
if (!camera || camera->IsLock() || !std::isfinite(distanceRatio) || distanceRatio <= 0.0f)
return;
camera->SetDistance(camera->GetDistance() * std::clamp(distanceRatio, 0.5f, 2.0f));
// The normal CCamera::Update still enforces its configured min/max and terrain collision.
}
void SetTouchInput(bool touch)
{
g_touch_input = touch;
@@ -1051,6 +1069,8 @@ namespace PythonBoot
#include "Ava2WikiSource.inc"
#include "Ava2DropItemSource.inc"
#include "Ava2NativeInterfacesScript.inc"
#include "Ava2ItemShopNewSource.inc"
#include "Ava2ItemShopScript.inc"
#include "AttrLockSnapshotsScript.inc"
#include "LiveEndpointScript.inc"
#include "NativeChannelScript.inc"
@@ -1170,6 +1190,9 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
install_script_module("uiWiki",c_szAva2WikiSource);
install_script_module("uiDropItem",c_szAva2DropItemSource);
install_script_module("mt_ava2_native_interfaces",c_szAva2NativeInterfacesScript);
install_script_module("mt_ava2_shop_support",c_szAva2ShopSupportScript);
install_script_module("uiItemShopNew",c_szAva2ItemShopNewSource);
install_script_module("mt_itemshop",c_szAva2ItemShopScript);
install_script_module("mt_minimap_buttons", c_szMinimapOuterRingScript);
if (g_touch_input)
install_script_module("mt_mobile_hud", c_szMobileHUDScript);
+2
View File
@@ -102,6 +102,8 @@ bool UIIsAttaching();
void UIDeattachObject();
// Turns the camera around the player immediately, without CCamera::Drag's decaying velocity.
void CameraRotateBy(float rollDeg, float pitchDeg);
// PORT mobile pinch: immediate proportional zoom; native camera update retains distance/collision limits.
void CameraZoomBy(float distanceRatio);
bool IsPointInsideActiveUI(int x, int y);
// Touch hosts: hide 40250's on-screen login keypad (the system keyboard types instead).
// Also drops the mouse arrow: touch hosts run 40250's hardware-cursor mode with no OS cursor, so
+11 -1
View File
@@ -188,7 +188,8 @@ class CMainPacketHeaderMap : public CNetworkPacketHeaderMap
Set(HEADER_GC_SASH, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketSash), STATIC_SIZE_PACKET)); // PORT: AVA2 sash
Set(HEADER_GC_CHESTDROP, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCChestDrop), DYNAMIC_SIZE_PACKET));
Set(HEADER_GC_AVA2_DROP,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Drop),STATIC_SIZE_PACKET));
Set(HEADER_GC_AVA2_EVENTS,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET));
Set(93,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET));
Set(HEADER_GC_AVA2_EVENTS,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET));
Set(HEADER_GC_SWITCHBOT, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCSwitchbot), DYNAMIC_SIZE_PACKET)); // PORT: AVA2 switchbot
}
@@ -545,6 +546,15 @@ bool CPythonNetworkStream::CheckPacket(TPacketHeader * pRetHeader)
return false;
}
// Native shop/calendar use DWORD lengths. Wait for the entire frame before dispatch.
if(header==93 || header==HEADER_GC_AVA2_EVENTS) {
TPacketGCAva2Events p;
if(!Peek(sizeof(p),&p))return false;
const unsigned minimum=sizeof(p)+(header==93?1:6);
if(p.size<minimum || p.size>32768) { ClearRecvBuffer();PostQuitMessage(0);return false; }
if(!Peek(p.size))return false;
*pRetHeader=header;return true;
}
// AVA2 chest preview uses a DWORD length, unlike the base WORD dynamic header.
if(header==HEADER_GC_CHESTDROP) {
TPacketGCChestDrop p;
@@ -562,6 +562,7 @@ class CPythonNetworkStream : public CNetworkStream, public CSingleton<CPythonNet
bool RecvSashPacket(bool bReturn = false); // PORT: AVA2 sash
bool RecvAva2DropQuery();
bool RecvAva2Events();
bool RecvAva2ItemShop();
bool RecvSwitchbotPacket(); // PORT: AVA2 switchbot
// MiniMap Info
@@ -641,6 +641,7 @@ void CPythonNetworkStream::GamePhase()
ret=RecvAva2DropQuery();break;
case HEADER_GC_AVA2_EVENTS:
ret=RecvAva2Events();break;
case 93:ret=RecvAva2ItemShop();break;
case HEADER_GC_SWITCHBOT: // PORT: AVA2 switchbot
ret = RecvSwitchbotPacket();
break;
@@ -4219,8 +4220,8 @@ bool CPythonNetworkStream::SendClientVersionPacket()
TPacketCGClientVersion2 kVersionPacket;
kVersionPacket.header = HEADER_CG_CLIENT_VERSION2;
strncpy(kVersionPacket.filename, filename.c_str(), sizeof(kVersionPacket.filename)-1);
// PORT: " mt20261019" enables the AVA2 switchbot on the server (port_switchbot.cpp); the version check uses atoi.
strncpy(kVersionPacket.timestamp, "1215955205 mt20261019", sizeof(kVersionPacket.timestamp)-1); // # python time.time 앞자리
// PORT: revision mt20261020 adds native itemshop; preserve the numeric prefix for atoi version checks.
strncpy(kVersionPacket.timestamp, "1215955205 mt20261020", sizeof(kVersionPacket.timestamp)-1); // # python time.time 앞자리
//strncpy(kVersionPacket.timestamp, __TIMESTAMP__, sizeof(kVersionPacket.timestamp)-1); // old_string_ver
//strncpy(kVersionPacket.timestamp, "1218055205", sizeof(kVersionPacket.timestamp)-1); // new_future
//strncpy(kVersionPacket.timestamp, "1214055205", sizeof(kVersionPacket.timestamp)-1); // old_past
@@ -4233,9 +4234,8 @@ bool CPythonNetworkStream::SendClientVersionPacket()
TPacketCGClientVersion kVersionPacket;
kVersionPacket.header = HEADER_CG_CLIENT_VERSION;
strncpy(kVersionPacket.filename, filename.c_str(), sizeof(kVersionPacket.filename)-1);
// PORT: protocol date instead of __TIMESTAMP__; the server sends the AVA2 switchbot packets only from
// "mt20261019" on (metin2-server port_switchbot.h PORT_SWITCHBOT_CLIENT_VERSION).
strncpy(kVersionPacket.timestamp, "mt20261019", sizeof(kVersionPacket.timestamp)-1);
// PORT: native itemshop requires mt20261020; older AVA2 services retain their own revision gates.
strncpy(kVersionPacket.timestamp, "mt20261020", sizeof(kVersionPacket.timestamp)-1);
if (!Send(sizeof(kVersionPacket), &kVersionPacket))
Tracef("SendClientReportPacket Error");
@@ -23,3 +23,13 @@ bool CPythonNetworkStream::RecvAva2Events() {
PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_GAME],"BINARY_Ava2Events",Py_BuildValue("(s#)",data.data(),int(data.size())));
return true;
}
// Native AVA2 GC93, parsed atomically by the embedded shop bridge.
bool CPythonNetworkStream::RecvAva2ItemShop() {
TPacketGCAva2Events p;
if (!Recv(sizeof(p),&p) || p.size<sizeof(p)+1 || p.size>32768)return false;
std::vector<char> data(p.size-sizeof(p));
if (!Recv(data.size(),data.data()))return false;
PyCallClassMemberFunc(m_apoPhaseWnd[PHASE_WINDOW_GAME],"BINARY_Ava2ItemShop",Py_BuildValue("(s#)",data.data(),int(data.size())));
return true;
}
+67 -1
View File
@@ -352,6 +352,7 @@ int main(int argc, char** argv)
// by port. TChannelStatus::nPort is a short, so the fake server's ephemeral state port (> 32767)
// never matches its own channel; offline the proof is the second channel (13002) it also lists.
// Live the game port answers for the channels the db knows, the game port among them.
if (!std::getenv("MT_TEST_PINCH"))
{
const int state_port = server ? server->StatePort() : game_port;
const int key = server ? 2 : 1;
@@ -501,6 +502,69 @@ int main(int argc, char** argv)
return g_failures ? 1 : 0;
}
if (mobile_test && std::getenv("MT_TEST_PINCH")) {
CHECK(pump_until(5, [] { return py_true("not _stream.curtain.IsShow()"); }));
CHECK(py("import mt_mobile_hud; _hud=mt_mobile_hud.g_hud\n"
"assert not _hud.menuExpanded and all(not b.IsShow() for b in _hud.side)\n"
"assert _hud.shop.IsShow() and _hud.more.IsShow()\n"
"_hud.ToggleMore()\n"
"assert _hud.menuExpanded and all(b.IsShow() for b in _hud.side)\n"
"_hud.ToggleMore()\n"
"assert not _hud.menuExpanded and all(not b.IsShow() for b in _hud.side)"));
TouchController touch;
touch.set_enabled(true);
touch.update_screen_size(800, 600);
// PORT scene pinch: start across both halves, spread closer, close farther.
CHECK(!PythonBoot::IsPointInsideActiveUI(480, 240));
CHECK(!PythonBoot::IsPointInsideActiveUI(320, 240));
auto* camera = CCameraManager::Instance().GetCurrentCamera();
const float originalDistance = camera->GetDistance();
CHECK(touch.on_finger_down(201, 0.4f, 0.4f));
CHECK(touch.on_finger_down(202, 0.6f, 0.4f));
const float beforePinch = camera->GetDistance();
touch.on_finger_motion(202, 0.7f, 0.4f);
CHECK(camera->GetDistance() < beforePinch * 0.8f);
const float closeDistance = camera->GetDistance();
touch.on_finger_motion(202, 0.6f, 0.4f);
CHECK(camera->GetDistance() > closeDistance * 1.2f);
CHECK(std::abs(camera->GetDistance() - beforePinch) < 1.0f);
touch.on_finger_up(201, 0.4f, 0.4f); // remaining finger becomes look, never tap
touch.on_finger_motion(202, 0.62f, 0.4f);
CHECK(std::abs(camera->GetDistance() - beforePinch) < 1.0f);
touch.on_finger_up(202, 0.62f, 0.4f);
touch.update();
CHECK(std::abs(camera->GetDistance() - beforePinch) < 1.0f);
// Reverse ownership order; right scene finger plus left scene finger also pinches.
touch.on_finger_down(203, 0.6f, 0.4f);
touch.on_finger_down(204, 0.4f, 0.4f);
touch.on_finger_motion(204, 0.3f, 0.4f);
CHECK(camera->GetDistance() < beforePinch * 0.8f);
touch.on_finger_up(204, 0.3f, 0.4f);
touch.on_finger_up(203, 0.6f, 0.4f);
camera->SetDistance(originalDistance);
touch.on_finger_down(207, 0.6f, 0.4f);
touch.on_finger_down(208, 0.4f, 0.4f);
touch.cancel_gestures();
touch.on_finger_motion(208, 0.2f, 0.4f);
CHECK(std::abs(camera->GetDistance() - originalDistance) < 1.0f);
// A moving joystick is not stolen by a second thumb looking around.
touch.on_finger_down(205, 0.3f, 0.45f);
touch.on_finger_motion(205, 0.35f, 0.45f);
touch.on_finger_down(206, 0.6f, 0.4f);
touch.on_finger_motion(206, 0.7f, 0.4f);
CHECK(std::abs(camera->GetDistance() - originalDistance) < 1.0f);
touch.on_finger_up(205, 0.35f, 0.45f);
touch.on_finger_up(206, 0.7f, 0.4f);
CHECK(py("import app; app.Exit()"));
pump_until(2, [] { return !PythonBoot::IsAppLooping(); });
PythonBoot::Stop();
if (server) server->Stop();
std::printf("mobile scene pinch: %s\n", g_failures ? "FAILED" : "PASS");
return g_failures ? 1 : 0;
}
if (mobile_test) {
// Input remains blocked by the original phase curtain until its fade finishes.
CHECK(pump_until(5, [] { return py_true("not _stream.curtain.IsShow()"); }));
@@ -511,7 +575,7 @@ int main(int argc, char** argv)
"_hud.window.interface.wndInventory.Hide()"));
CHECK(py_true("_hud.IsShow()"));
CHECK(py_true("not ui.Window.IsShow(_hud.taskbar)"));
CHECK(py_true("len(_hud.top) == 4 and len(_hud.side) == 3"));
CHECK(py_true("len(_hud.top) == 4 and len(_hud.side) == 4"));
CHECK(py_true("all(button.GetWidth() >= 48 for button in _hud.top + _hud.side)"));
CHECK(py_true("_hud.status.values[0] == player.GetStatus(player.HP)"));
CHECK(py_true("_hud.experience is _hud.taskbar.expGaugeBoard and _hud.experience.IsShow()"));
@@ -1650,6 +1714,8 @@ int main(int argc, char** argv)
CHECK(kept_origin);
touch.on_finger_up(101, 0.325f, 0.46666667f);
}
CHECK(py("import app\napp.Exit()"));
+75
View File
@@ -0,0 +1,75 @@
"""Execute the shipping shop decoder and purchase callbacks with real native layouts."""
import ast,struct,types,unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
SRC=(ROOT/'src/platform/ScriptLib/Ava2ItemShopScript.inc').read_text().split('c_szAva2ItemShopScript[]=R"PY(',1)[1].split(')PY";',1)[0]
class Wire(unittest.TestCase):
def setUp(self):
tree=ast.parse(SRC);fn=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='Parse')
self.ns={'struct':struct,'_product':struct.Struct('<IIqiBiiqiii'),'_log':struct.Struct('<I25s21si16sIIiq')}
exec(compile(ast.Module(body=[fn],type_ignores=[]),'<shop>','exec'),self.ns)
def catalogue(self,discount=25,product=1):
row=self.ns['_product'].pack(product,71084,99,0,discount,0,0,0,2,8,4)
return struct.pack('<BqiiBBBB',0,999,7,1,0,1,0,1)+row
def test_native_sizes_and_product_fields(self):
self.assertEqual(self.ns['_product'].size,49);self.assertEqual(self.ns['_log'].size,90)
op,(coins,rev,rows)=self.ns['Parse'](self.catalogue());self.assertEqual((op,coins,rev),(0,999,7));self.assertEqual(rows[0][2][1],71084)
def test_all_partial_frames_fail_before_mutating_model(self):
packet=self.catalogue()
for size in range(len(packet)):
with self.assertRaises((ValueError,struct.error)):self.ns['Parse'](packet[:size])
def test_invalid_discount_duplicate_ids_trailing_and_unknown(self):
for packet in [self.catalogue(101),self.catalogue()+b'x',b'\x09',struct.pack('<Bqii',0,-1,1,0)]:
with self.assertRaises((ValueError,struct.error)):self.ns['Parse'](packet)
packet=bytearray(self.catalogue());packet[20]=2;packet+=packet[-49:]
with self.assertRaises((ValueError,struct.error)):self.ns['Parse'](bytes(packet))
def test_purchase_reply_exact_token_status_balance(self):
packet=struct.pack('<B32sBq',7,b'0123456789abcdef0123456789abcdef',0,100)
self.assertEqual(self.ns['Parse'](packet)[1][-2:],(0,100))
for packet in (packet[:-1],packet+b'x',struct.pack('<B32sBq',7,b'z'*32,0,100),struct.pack('<B32sBq',7,b'0'*32,10,100)):
with self.assertRaises((ValueError,struct.error)):self.ns['Parse'](packet)
def test_log_count_is_bounded(self):
for count in (-1,101):
with self.assertRaises(ValueError):self.ns['Parse'](struct.pack('<Bi',1,count))
class PurchaseFlow(unittest.TestCase):
def functions(self,*names):
nodes=[n for n in ast.parse(SRC).body if isinstance(n,ast.FunctionDef) and n.name in names]
exec(compile(ast.Module(body=nodes,type_ignores=[]),'<shop-flow>','exec'),self.ns)
def setUp(self):
self.sent=[];self.now=0
class Token:
def encode(self,encoding):assert encoding=='hex';return 'a'*32
self.ns=dict(pending=None,_serial=0,_next=0,_waiting=False,_queued=False,_requested=0,_logAt=0,window=None,
os=types.SimpleNamespace(urandom=lambda size:Token()),app=types.SimpleNamespace(GetTime=lambda:self.now),
net=types.SimpleNamespace(SendChatPacket=self.sent.append),chat=types.SimpleNamespace(CHAT_TYPE_INFO=1,AppendChat=lambda *args:None),L=lambda s:s)
def test_displayed_discount_matches_server_integer_total(self):
self.functions('Total')
self.assertEqual(self.ns['Total'](58,1,50),29)
self.assertEqual(self.ns['Total'](99,2,25),148)
def test_confirmed_quote_is_frozen_and_double_accept_is_blocked(self):
self.functions('AcceptBuy')
item=types.SimpleNamespace(shopQuote=(1,2,148,71084),data=[999],buyCount=20,CloseQuestionDialog=lambda:None)
self.ns['AcceptBuy'](item);self.ns['AcceptBuy'](item)
self.assertEqual(self.sent,['/ishop buy 1 2 '+'a'*32+' 148 71084'])
def test_retry_preserves_order_and_never_creates_second_payment(self):
self.functions('Tick');self.ns['pending']=('a'*32,1,2,0,0,148,71084)
for now in [5,10,15,20,25]:self.now=now;self.ns['Tick']()
self.assertEqual(self.sent,['/ishop buy 1 2 '+'a'*32+' 148 71084']*3)
self.assertEqual(self.ns['pending'][4],4)
def test_catalogue_refresh_is_queued_past_command_throttle(self):
self.functions('Request','Tick');self.ns['Request']();self.now=.5;self.ns['Request']()
self.assertEqual(len(self.sent),1);self.assertTrue(self.ns['_queued'])
self.now=1.2;self.ns['Tick']();self.assertEqual(self.sent,['/ishop data -1']*2)
def test_image_and_button_callbacks_keep_correct_event_arguments(self):
self.ns['_MISSING']=object();self.functions('EventTag');calls=[]
wrapped=self.ns['EventTag'](lambda self,event,category,sub:calls.append((event,category,sub)),3)
self.assertGreater(wrapped.__code__.co_argcount,1) # classic ui.__mem_func__ must retain image arguments
wrapped(None,2,1);wrapped(None,'button',2,1)
self.assertEqual(calls,[(None,2,1),('button',2,1)])
def test_uncertain_commit_keeps_same_pending_order(self):
self.functions('Receive');pending=('a'*32,1,2,0,0,148,71084)
self.ns.update(pending=pending,Parse=lambda raw:(7,('a'*32,8,10000)))
self.ns['Receive'](None,b'');self.assertEqual(self.ns['pending'],pending)
if __name__=='__main__':unittest.main()
+23 -5
View File
@@ -29,6 +29,7 @@ class MockWidget(object):
def SetDownVisual(self, v): self.visuals['down'] = v
def SetEvent(self, ev): self.event = ev
def SetText(self, t): self.text = t
def SetToolTipText(self, t): self.tooltip = t
def SetOutline(self): pass
def SetHorizontalAlignRight(self): pass
def SetPackedFontColor(self, c): pass
@@ -40,11 +41,15 @@ class MockWidget(object):
class MinimapButtonsTests(unittest.TestCase):
def setUp(self):
names = ('app', 'game', 'ui', 'wndMgr', 'mt_dungeons', 'mt_battlepass', 'mt_biolog')
names = ('app', 'game', 'ui', 'wndMgr', 'mt_dungeons', 'mt_battlepass', 'mt_biolog', 'player', 'mt_channel', 'mt_wiki')
mods = {n: types.ModuleType(n) for n in names}
mods['app'].DIK_F5 = 63
mods['app'].DIK_F6 = 64
mods['app'].DIK_F7 = 65
mods['app'].DIK_F8 = 66
mods['player'].AutoHuntLocalize = lambda text: text.encode('gbk')
mods['mt_channel'].Toggle = lambda: None
mods['mt_wiki'].Toggle = lambda: None
self.toggles = {'dungeon': 0, 'battlepass': 0, 'biolog': 0}
mods['mt_dungeons'].Toggle = lambda: self.toggles.__setitem__('dungeon', self.toggles['dungeon'] + 1)
@@ -75,7 +80,10 @@ class MinimapButtonsTests(unittest.TestCase):
self.wndMiniMap.ShowMiniMap = lambda: self.wndMiniMap.OpenWindow.Show()
self.wndMiniMap.OnUpdate = lambda: None
self.gw.interface = types.SimpleNamespace(wndMiniMap=self.wndMiniMap)
self.expanded = MockWidget()
self.expanded.expandedTaskBarBoard = MockWidget()
self.gw.interface = types.SimpleNamespace(
wndMiniMap=self.wndMiniMap, wndExpandedTaskBar=self.expanded)
self.game.GameWindow.Open(self.gw)
self.ring = self.ns['g_ring']
@@ -96,17 +104,27 @@ class MinimapButtonsTests(unittest.TestCase):
# Dungeon: (-10, 40)
self.assertEqual(self.ring.btnDungeon.pos, (-10, 40))
self.assertEqual(self.ring.btnDungeon.visuals['up'], "d:/ymir work/ui/game/minimapa/dungeon_0.tga")
self.assertEqual(self.ring.tipDungeon.textLine.text, "[F5] 副本信息")
self.assertEqual(self.ring.tipDungeon.textLine.text, "[F5] 副本信息".encode("gbk"))
# BattlePass: (0, 80)
self.assertEqual(self.ring.btnBattlePass.pos, (0, 80))
self.assertEqual(self.ring.btnBattlePass.visuals['up'], "d:/ymir work/ui/game/battle_pass/battlepass_icon_0.tga")
self.assertEqual(self.ring.tipBattlePass.textLine.text, "[F6] 战斗通行证")
self.assertEqual(self.ring.tipBattlePass.textLine.text, "[F6] 战斗通行证".encode("gbk"))
# Biolog: (15, 105)
self.assertEqual(self.ring.btnBiolog.pos, (15, 105))
self.assertEqual(self.ring.btnBiolog.visuals['up'], "d:/ymir work/ui/game/minimapa/biolog_0.tga")
self.assertEqual(self.ring.tipBiolog.textLine.text, "[F7] 生物学家")
self.assertEqual(self.ring.tipBiolog.textLine.text, "[F7] 生物学家".encode("gbk"))
def test_all_chinese_tooltips_use_locale_bytes(self):
expected = ((self.ring.tipDungeon, "[F5] 副本信息"),
(self.ring.tipBattlePass, "[F6] 战斗通行证"),
(self.ring.tipBiolog, "[F7] 生物学家"),
(self.ring.tipChannel, "[F8] 点击换线"))
for tooltip, label in expected:
self.assertEqual(tooltip.textLine.text.decode('gbk'), label)
self.assertEqual(self.expanded.btnSwitchbot.tooltip.decode('gbk'), "自动洗练")
self.assertEqual(self.expanded.btnWiki.tooltip.decode('gbk'), "游戏百科")
def test_button_clicks_trigger_subsystems(self):
self.ring.btnDungeon.event()
+1 -1
View File
@@ -4,7 +4,7 @@ from pathlib import Path
import hashlib,json
ROOT=Path(__file__).resolve().parents[2]
REF=ROOT.parent/'AVA2/1. Client DEV/pack_maker/root'
SOURCES={'BattlePassEx':'uibattlepassex.py','EventCalendarNew':'uieventcalendarnew.py','WikiUI':'wikiui.py','Wiki':'uiwiki.py','DropItem':'uidropitem.py'}
SOURCES={'ItemShopNew':'uiitemshopnew.py','BattlePassEx':'uibattlepassex.py','EventCalendarNew':'uieventcalendarnew.py','WikiUI':'wikiui.py','Wiki':'uiwiki.py','DropItem':'uidropitem.py'}
manifest={}
for label,name in SOURCES.items():
raw=(REF/name).read_bytes();s=raw.decode('cp1254').replace('\r\n','\n')
+8
View File
@@ -1,4 +1,12 @@
{
"uiitemshopnew.py": {
"sha256": "b0e76028a37763bf021feaef31979040535174a60ec60c885877f9d19a07cb6d",
"module": "ItemShopNew",
"changes": [
"CP1254 to UTF-8",
"CRLF to LF"
]
},
"uibattlepassex.py": {
"sha256": "c0ac6e2e3dfcd6c6c0716e5da4bfdf29169087109a7216d507f67d7ac3ed00d2",
"module": "BattlePassEx",
+1 -1
View File
@@ -7,7 +7,7 @@ def stage(pack_maker,assets):
spec=importlib.util.spec_from_file_location('ava2_items',ROOT/'tools/server/ava2-items/make_items.py')
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
files=module.pack_index(pack_maker)
prefixes=('d:/ymir work/ui/game/battle_pass/','d:/ymir work/ui/game/event_calendar/','d:/ymir work/ui/game/wiki/','d:/ymir work/ui/game/drop_item/','d:/ymir work/worldard/')
prefixes=('d:/ymir work/ui/game/ishop/','d:/ymir work/ui/game/battle_pass/','d:/ymir work/ui/game/event_calendar/','d:/ymir work/ui/game/wiki/','d:/ymir work/ui/game/drop_item/','d:/ymir work/worldard/')
count=0
for name,source in files.items():
if name.startswith(prefixes):
+1 -1
View File
@@ -315,7 +315,7 @@ def prepare(ava,proto_reader,locale,output,tool,packer,wrap=lambda text:text):
target=assets/q;target.parent.mkdir(parents=True,exist_ok=True)
if not target.exists():shutil.copy2(files[q],target);copied+=1
# Native AVA2 BattlePassEx, event manager, encyclopedia and drop finder.
native_prefixes=('d:/ymir work/ui/game/battle_pass/','d:/ymir work/ui/game/event_calendar/',
native_prefixes=('d:/ymir work/ui/game/ishop/','d:/ymir work/ui/game/battle_pass/','d:/ymir work/ui/game/event_calendar/',
'd:/ymir work/ui/game/wiki/','d:/ymir work/ui/game/drop_item/','d:/ymir work/worldard/')
for q in files:
if q.startswith(native_prefixes):