diff --git a/audit/xxf-ch5/features.json b/audit/xxf-ch5/features.json index d1a98cb4..18745e06 100644 --- a/audit/xxf-ch5/features.json +++ b/audit/xxf-ch5/features.json @@ -2,8 +2,8 @@ "schema_version": "1.1", "description": "XXF-CH5 to Cross-Platform Client Feature Migration Tracking Manifest", "baseline": { - "client_head": "ee00dff71e7121f699be25d1fc954d5b7f4c3730", - "server_head": "c979b53762d198222c2ab4f83067d29a26188a49", + "client_head": "60ed66692e2daccd66c4485b3632ae3fdb100933", + "server_head": "5b7442ea37cf162c4aadf18ea6b26c817e30b768", "preserves_dirty_worktree": true, "gate_script": "scripts/port_gate.sh", "snapshot_kind": "dirty_working_tree_heads_only", @@ -1600,20 +1600,23 @@ "version": "1.0", "provenance": "XXF-CH5", "unresolved": [ - "Specific subtype enum and duration check" + "79501 excluded due conflicting price/duration metadata; timed 79502-79504 candidate generated but not installed", + "Native arrow-type visual sync and matched live/device/item-lifecycle acceptance" ], "accepted_differences": [ - "Preserves ordinary arrow consumption when quiver unequipped" + "AVA2 active quiver9 semantics; claw8 reserved only; explicit pre-shot expiry checks; classic arrow visual fallback; whole-feature macro stays off" ] }, "dependencies": [], "implementation": { - "client": "src/port/GameLib/ItemData.h", - "server": "game/src/char_battle.cpp", + "client": "src/port/UserInterface/PythonPlayerSkill.cpp", + "server": "src/server/game/src/port_quiver.h", "data": "item_proto", "resources": null, "entrypoints": [ - "CPythonPlayer::CanShoot" + "CHARACTER::GetArrowAndBow", + "CHARACTER::UseArrow", + "CPythonPlayer::__HasEnoughArrow" ] }, "protocol_contract_ref": "AVA2-IMPLEMENTATION-SPEC.md#quiver", @@ -1623,7 +1626,7 @@ "safe_default": "Standard arrow requirements" }, "status": { - "source": "pending_review", + "source": "partially_verified", "implementation": "partial", "build": "pending", "unit": "pending", @@ -1656,8 +1659,8 @@ "locale_cases_ref": null, "observation_and_shutdown_ref": null, "blockers": [ - "Specific subtype enum and duration check", - "Current candidate source/resource hashes and feature-specific acceptance evidence required" + "79501 excluded due conflicting price/duration metadata; timed 79502-79504 candidate generated but not installed", + "Native arrow-type visual sync and matched live/device/item-lifecycle acceptance" ], "rollback_contract_ref": null }, diff --git a/audit/xxf-ch5/quiver-20261022.json b/audit/xxf-ch5/quiver-20261022.json new file mode 100644 index 00000000..a13aa192 --- /dev/null +++ b/audit/xxf-ch5/quiver-20261022.json @@ -0,0 +1,160 @@ +{ + "schema_version": 1, + "date": "2026-10-22", + "feature": "F19", + "implementation": "ammunition_core_connected; feature_partial", + "rule_policy": "Verified active AVA2 implementation; no invented duration or price; expiry-gap hardening explicitly recorded", + "baseline": { + "client_head": "60ed66692e2daccd66c4485b3632ae3fdb100933", + "server_head": "5b7442ea37cf162c4aadf18ea6b26c817e30b768", + "new_changes_uncommitted": true, + "prior_snapshots_pushed_and_verified": true + }, + "source_sha256": { + "client": { + "src/port/UserInterface/PythonPlayerSkill.cpp": "6f54fad0580409fd54174fcad0ac1632a9c5a7c314af508f6b10e1d51eb475a8", + "src/platform/ScriptLib/ModelPreviewScript.inc": "35550dc01636c7fff80b3c8d5f26e863ee5abd9a0e8bb0c1934dbf27f68d10d7", + "src/platform/ScriptLib/Ava2NativeDataScript.inc": "ea6bdcd1dbb010bf9ba65e785c61387d00747941bc7372637ab438a3ab425d91", + "tests/wiki/test_model_preview.py": "7751b9da104a9676eac04c77038073ed2cd144ba15cf07183dbf28c87e5b3adf", + "tests/wiki/test_ava2_ui.py": "55b4b9e8229dce60178bd1f811115a1935b5a8dcba01a8e7417467a9427d1260", + "tests/wiki/test_quiver_runtime.py": "6eb2f06150180f8d50759fa0c2156ef6f972e024e423690fcb978161ce79cfb6", + "scripts/build_xxf_features_json.py": "2d758112bef5e03829198878830189739d7ba3a18329175d03581626a73aedfc" + }, + "server": { + "src/server/common/item_length.h": "cade3abc77f08c2e0fc4273177c8d940a852a0a653d6e82d5256df3cd7e09965", + "src/server/db/src/ProtoReader.cpp": "295014b2c58ae942b933bad61f3b712546f3139669a1953154ddc5a938c4c3ea", + "src/server/game/src/Makefile": "5d5a2ac54f77a937aad1bf9b936ed8e97aa3830a3129500a14204201ab0049db", + "src/server/game/src/char_battle.cpp": "f053a6bcc2c2d0425e9ff1ced341ac877b008aea3dd532ec9d79421bf5532df7", + "src/server/game/src/constants.cpp": "2ae9d79c9c079b0dfea5294399cfbe66bf64ef1461c8e70413ff5354c3d780b7", + "src/server/game/src/item_attribute.cpp": "72cc7aa63299e25be89e22a7f21122da0452bd6448ee7799530d0aabe1af6f64", + "src/server/game/src/port_quiver.h": "1d258dbc74608d413f632580f8f8653daada4394751598709f6c7d8e35aabe64", + "tests/features/test_quiver_runtime.py": "f4dd439215922f5066e603145cd1f7c62fe5614d5e4648b6c7e58d6ff8067d37" + } + }, + "provenance": { + "archive": "AVA2/2. Backup SF+SRC and SQL/FILES+SRC.tgz", + "members": [ + { + "path": "home/Ava2_src/Srcs/Server/game/src/char_battle.cpp", + "sha256": "5fa1cb8464b9fa3cbbdbf0a8670e301381c6e38c182a2e11b56b2bb4aac46cef", + "authority": "Unguarded GetArrowAndBow/UseArrow branches; quiver cap200 and no consumption" + }, + { + "path": "home/srv1/db/item_proto.txt", + "sha256": "708fa44f9fdbb8b66bf8b134b2946ba6724a092fc7e5b1a008672584561cf3b4" + }, + { + "path": "home/srv1/share/conf/item_proto.txt", + "sha256": "5394bc83413dbf6705470f6ae7b36d0ad8fbf55e56736d90fbc4692f9704f75b" + } + ], + "conflicts": [ + "79501 name suggests one day but both prototypes set LIMIT_NONE", + "79501 db price100000 versus share/conf price0", + "No automatic proto import or product activation" + ] + }, + "artifacts": { + "client": { + "build/port-gate/macos/src/port/port_login_flow_test": "0e960b14119c19a1e56667ad03617bb53bd9904cb65f6dc9dd12274479d31a61", + "build/port-gate/macos/src/port/port_python_ui_modules_test": "a7d64733e43678677bbfcd47d832527e65adfd8598e93fb8c5518a51141adcf7", + "build/port-gate/macos/Testing/Temporary/LastTest.log": "956f913897508c30fa0465bdcba4d3e943f2c0af1dcb69d6b0d8bccd9026ca7f" + }, + "freebsd": { + "host": "192.168.21.203", + "scratch": "/root/deploy-features/ch5-continuation.fXhzELfT", + "sha256": { + "bin/game": "c7b602b6096249bcfe6c6859b202ff3acddaf533389f74e802a15063444f3b29", + "bin/db": "798fc26be1b4757fc57bb0d0c44101a1ad6cd694520fba9b933ecfddbce7e832", + "quiver-final-build.log": "17a4644454359fed56025dab3dd4edb8845505a234233b3413da56322428dab0", + "src/server/common/item_length.h": "cade3abc77f08c2e0fc4273177c8d940a852a0a653d6e82d5256df3cd7e09965", + "src/server/db/src/ProtoReader.cpp": "295014b2c58ae942b933bad61f3b712546f3139669a1953154ddc5a938c4c3ea", + "src/server/game/src/Makefile": "5d5a2ac54f77a937aad1bf9b936ed8e97aa3830a3129500a14204201ab0049db", + "src/server/game/src/char_battle.cpp": "f053a6bcc2c2d0425e9ff1ced341ac877b008aea3dd532ec9d79421bf5532df7", + "src/server/game/src/constants.cpp": "2ae9d79c9c079b0dfea5294399cfbe66bf64ef1461c8e70413ff5354c3d780b7", + "src/server/game/src/item_attribute.cpp": "72cc7aa63299e25be89e22a7f21122da0452bd6448ee7799530d0aabe1af6f64", + "src/server/game/src/port_quiver.h": "1d258dbc74608d413f632580f8f8653daada4394751598709f6c7d8e35aabe64" + }, + "matching_runtime_sources": 7, + "logs": { + "initial": "quiver-full-build.log", + "final": "quiver-final-build.log" + }, + "production_deployed": false + } + }, + "verification": [ + { + "command": "python3 -m unittest discover -s tests/wiki", + "result": "pass", + "tests": 188 + }, + { + "command": "python3 -m unittest discover -s tests/features -p 'test_quiver_runtime.py'", + "result": "pass", + "tests": 1, + "note": "Actual enum, DB subtype parser, ammunition functions and expiry helper; explicit substitutes; ASan/UBSan" + }, + { + "command": "python3 -m unittest discover -s tests/features -p 'test_magic_reduction.py'", + "result": "pass", + "tests": 1 + }, + { + "command": "python3 -m unittest discover -s tests/features -p 'test_rank_runtime.py'", + "result": "pass", + "tests": 1 + }, + { + "command": "python3 tests/features/test_applies.py", + "result": "pass" + }, + { + "command": "python3 tests/features/test_queries.py", + "result": "pass" + }, + { + "command": "cmake --build build/port-gate/macos --target port_login_flow_test port_python_ui_modules_test -j4", + "result": "pass" + }, + { + "command": "ctest --test-dir build/port-gate/macos -R '^port\\.(login_flow|python_ui_modules)$' --output-on-failure --timeout 150", + "result": "pass", + "tests": 2, + "elapsed_seconds": 62.8 + }, + { + "command": "gmake -C SCRATCH/src/server MAKE=gmake -j2 BINDIR=SCRATCH/work GAMEDIR=SCRATCH/bin DBDIR=SCRATCH/bin all", + "result": "initial_failure_corrected", + "reason": "port_quiver.h included before item.h/utils.h; moved after dependency headers" + }, + { + "command": "gmake -C SCRATCH/src/server/game/src -j2 BINDIR=SCRATCH/work GAMEDIR=SCRATCH/bin default", + "result": "pass", + "note": "Completed clean game build from interrupted full snapshot build" + }, + { + "command": "gmake -C SCRATCH/src/server/db/src clean && gmake -C SCRATCH/src/server/db/src -j2 BINDIR=SCRATCH/work DBDIR=SCRATCH/bin default", + "result": "pass" + } + ], + "corrections": [ + "Original AVA2 WikiUI source restored byte-equivalent; existing adapter invokes corrected model preview", + "Python3-only test fixture adapts Python2 exec statement; runtime script remains unchanged" + ], + "activation": { + "client_macro": "ENABLE_QUIVER_SYSTEM=0; whole-feature readiness gate, not C++ ammo dispatch", + "items_issued": false, + "shops_changed": false, + "database_migration": false, + "production_deployed": false + }, + "pending": [ + "Confirm current authoritative proto and conflicting 79501 fields/anti-flag mapping; build matching client/server data patch", + "Native PART_ARROW_TYPE synchronization and special projectile visuals; classic arrow fallback only", + "Actual equip/unequip/move/trade/storage/reconnect and offline-expiry persistence acceptance", + "Matched live server combat/skill burst/mounted/costume-weapon scenarios", + "Android build/device acceptance", + "No full feature or 35/35 completion claim" + ] +} diff --git a/audit/xxf-ch5/quiver-data-20261022.json b/audit/xxf-ch5/quiver-data-20261022.json new file mode 100644 index 00000000..f8e02fc8 --- /dev/null +++ b/audit/xxf-ch5/quiver-data-20261022.json @@ -0,0 +1,344 @@ +{ + "schema_version": 1, + "date": "2026-10-22", + "feature": "F19", + "status": "candidate_data_generated; full feature remains partial and disabled", + "source_sha256": { + "tools/server/ava2-items/make_items.py": "47404c91ec8adc33887f8f371f96fb499937f9be22aeba64b80ccc99b583ab8c", + "tools/server/ava2-items/make_quiver.py": "f406ad470c566dcbead41061a1cedfe6954a60faed671ea215c0b8c7df2a7f65", + "tools/server/ava2-items/tests/test_quiver.py": "592bc4bc6ab8e36636ba29bad61856a2cedc3c834efba759d36083b4a0faf479", + "tests/port/eterpack_pack.cpp": "9a56de118f95fb8cddabab6254746f7d4a472ee559c77a3a0fc889bb7ff5a6f7", + "scripts/build_xxf_features_json.py": "926659cb5d857de3119b7829b4e38e5f48a2bfd4621f67d7611915a19086f4c2" + }, + "native_tool_sha256": { + "build/port-gate/macos/src/port/eterpack_pack": "b44de48903568ff22cda5a92e6429953b1d5b997f80f8733b40e3b118e7e97a7", + "build/port-gate/macos/src/port/item_proto_patch": "f7fa76145189a2d48f0c344a2c96ef1e4528a968acf1a5c6e3bca9bcaad353c8" + }, + "candidate": { + "directory": "build/ch5-quiver-bound-20261022", + "manifest_sha256": "10b112b337283b953c26a5c7c82499dd1ef0154532b4c49842757450b4cac29b", + "manifest": { + "version": 1, + "items": [ + 79502, + 79503, + 79504 + ], + "excluded": [ + 79501 + ], + "installed": false, + "verified_unchanged_proto_records": 11542, + "source_sha256": { + "home/srv1/db/item_proto.txt": "708fa44f9fdbb8b66bf8b134b2946ba6724a092fc7e5b1a008672584561cf3b4", + "home/srv1/share/conf/item_proto.txt": "5394bc83413dbf6705470f6ae7b36d0ad8fbf55e56736d90fbc4692f9704f75b" + }, + "base_proto_sha256": "ea2a000cb33f5c9c94d3668a4e0b7840ada284c190281ac26dbe2ad05d3d402e", + "proto_reader_sha256": "295014b2c58ae942b933bad61f3b712546f3139669a1953154ddc5a938c4c3ea", + "effective_client_base": { + "files": { + "locale/newcibn/item_proto": "ea2a000cb33f5c9c94d3668a4e0b7840ada284c190281ac26dbe2ad05d3d402e", + "locale/newcibn/item_list.txt": "24e768fb6a70a5433672662bbaeaba5ae195a5c28531382f3da7247115c0e519", + "locale/newcibn/itemdesc.txt": "ab7f0e07f217e5bfe5b3a93fa4baec0ed77ef846546fbe3235dcb2841876b993" + }, + "index_sha256": "02c49fda69adf9325fb5b3231f47c3544711185526fbf47985010d1c3e59cf7a" + }, + "explicit_replacements": { + "79502": { + "before": [ + 79502, + 1, + 9, + 1, + 467124, + 20, + 512, + 0, + 550000, + 0, + 0, + 0, + 0, + 7, + 604800, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 17, + 4, + 0, + 25, + 0, + 0, + 0, + 0 + ], + "after": [ + 79502, + 1, + 9, + 1, + 204980, + 20, + 512, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 604800, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 17, + 4, + 0, + 25, + 0, + 0, + 0, + 0 + ] + }, + "79503": { + "before": [ + 79503, + 1, + 9, + 1, + 278580, + 20, + 512, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 1296000, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 17, + 4, + 0, + 25, + 0, + 0, + 0, + 0 + ], + "after": [ + 79503, + 1, + 9, + 1, + 16436, + 20, + 512, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 1296000, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 17, + 4, + 0, + 25, + 0, + 0, + 0, + 0 + ] + }, + "79504": { + "before": [ + 79504, + 1, + 9, + 1, + 278580, + 20, + 512, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 2592000, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 17, + 4, + 0, + 25, + 0, + 0, + 0, + 0 + ], + "after": [ + 79504, + 1, + 9, + 1, + 16436, + 20, + 512, + 0, + 0, + 0, + 0, + 0, + 0, + 7, + 2592000, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 17, + 4, + 0, + 25, + 0, + 0, + 0, + 0 + ] + } + }, + "differences": [ + "ANTI_WOLFMAN omitted like existing converter: Wolfman disabled; re-evaluate before enabling fifth job", + "Chinese names/descriptions; no price/duration invention" + ], + "requires": [ + "matched client/server build", + "verified test-only proto install", + "live item lifecycle and Android acceptance" + ], + "files": { + "assets/icon/ch5_quiver/79501.tga": "0738cbe501addf84908409e750a59b979f5f8c02793bd3475f20f100d712cb94", + "assets/locale/newcibn/item_list.txt": "7717ae83efabde42f62b60794440aca4c53f7d65bf5a58bd0259f91f35a1cb26", + "assets/locale/newcibn/item_proto": "2d000254e242a7afd4d1e74176b8cdded0209d8b9c4102f7e0bdb7ac37afbdb6", + "assets/locale/newcibn/itemdesc.txt": "7080fd36cd26575abb77c9462ab491bc503bf808c6b954d8a174676dc4cefa55", + "assets/locale/zh/item_list.txt": "7717ae83efabde42f62b60794440aca4c53f7d65bf5a58bd0259f91f35a1cb26", + "assets/locale/zh/item_proto": "2d000254e242a7afd4d1e74176b8cdded0209d8b9c4102f7e0bdb7ac37afbdb6", + "assets/locale/zh/itemdesc.txt": "7080fd36cd26575abb77c9462ab491bc503bf808c6b954d8a174676dc4cefa55", + "base-item-proto": "ea2a000cb33f5c9c94d3668a4e0b7840ada284c190281ac26dbe2ad05d3d402e", + "items-client.tsv": "95a5b0296a8e995ecd76b9f2cd0fb9861bf2aa33414c34535ca009e0b5fab705", + "items-server.tsv": "5026bc377b0c12d89037844e6c91e58a09b331ce75f7f3823c2c9ce72baea986", + "quiver.eix": "322fe2d93b795521cc49ce159f9f0fa7cde2affea0ac4415b283fecb6d7f6693", + "quiver.epk": "0f80794412175aa46f13ee68ffde29ccc36674a6feb565faed12c8a65a0041c5" + } + } + }, + "rule_decision": "User-authorized verified AVA2 reconstruction; only timed variants79502-79504; exclude79501. AVA2 price0 is not authorization to stock/sell for free.", + "server_readonly_observation": { + "production_cwd": "/usr/metin2/server/db", + "production_proto": "../share/conf/item_proto.txt", + "production_proto_sha256": "20a1bf5acab3ca29b1448a45654bb521c46eafaf93b6f686e8769b7a24ba3551", + "sandbox_cwd": "/usr/metin2/server/sbtest/db", + "sandbox_proto_sha256": "e7eb2df58d2547bc7bcc4c4ec34a91cf5e91394542e1dffde8ed7043f11fb4d0", + "ids79501_to79504": "absent in both text files", + "files_modified": false + }, + "verification": [ + { + "command": "cmake --build build/port-gate/macos --target eterpack_pack item_proto_patch -j4", + "result": "pass" + }, + { + "command": "python3 -m unittest discover -s tools/server/ava2-items/tests", + "result": "pass", + "tests": 31, + "note": "Includes actual native pack probing, first registration wins, no loose file masking, no overwrite and invalid-argument protection" + }, + { + "command": "python3 -m unittest discover -s tests/wiki", + "result": "pass", + "tests": 188 + }, + { + "command": "make_quiver.py --ava ../AVA2 --reader ../metin2-server/src/server/db/src/ProtoReader.cpp --client-root Client --output build/ch5-quiver-bound-20261022 --proto-tool build/port-gate/macos/src/port/item_proto_patch --packer build/port-gate/macos/src/port/eterpack_pack --replace-existing-quivers --expected-base-sha256 ea2a000cb33f5c9c94d3668a4e0b7840ada284c190281ac26dbe2ad05d3d402e", + "result": "pass", + "records": 11545, + "replaced": 3, + "unaffected": 11542, + "packed_files": 7, + "note": "Native item proto decode/encode roundtrip; numeric/name checks; actual CEterPack file-by-file readback" + }, + { + "case": "Existing output directory", + "result": "rejected; existing candidate manifest unchanged" + }, + { + "case": "Stale optional extracted itemdesc reference", + "result": "rejected before output directory creation" + }, + { + "case": "Stale expected base SHA256", + "result": "rejected before output directory creation" + }, + { + "case": "Implicit replacement without explicit flag", + "result": "rejected before output directory creation" + } + ], + "scope_notes": [ + "The first legacy-locale experimental build is superseded, not accepted as the current candidate", + "Current effective proto matched the extracted proto, but effective itemdesc did not; generator now reads all three inputs through runtime registration", + "Native key-fallback may log first-key decode failures before successful XXF fallback; input SHA and return-code checks verified final bytes", + "Private icon path avoids changing the excluded79501 shared icon", + "No client Index/locale.cfg/package installation, server proto writes, database changes, item issuance, stock changes or production restarts", + "No new gameplay runtime changes in this data batch; previous FreeBSD/game/db and C++ gameplay evidence remains historical in quiver-20261022.json", + "No Android build/device or matched live item persistence acceptance; whole-feature switch remains0", + "Selected file and data hashes are not a full-client resource closure or release attestation" + ], + "remaining": [ + "Native arrow-type visual synchronization and projectile/animation support", + "Controlled matched-server proto installation and equip/unequip/trade/storage/reconnect/offline-expiry validation", + "Android build/device acceptance before enabling whole feature" + ] +} diff --git a/docs/AVA2-IMPLEMENTATION-SPEC.md b/docs/AVA2-IMPLEMENTATION-SPEC.md index e2561908..d3c1ed79 100644 --- a/docs/AVA2-IMPLEMENTATION-SPEC.md +++ b/docs/AVA2-IMPLEMENTATION-SPEC.md @@ -16,9 +16,12 @@ - F24复用`/mt_features 1 REQ rank BOARD 0`及MTF1会话序列,新增能力位1024。BOARD按五区顺序0等级、1石头、2怪物、3首领、4副本、5在线时长、6金币、7Gaya、8钓鱼、9宝箱。当前提供0/5/6,其他返回`unsupported`。快照为`begin REQ rank BOARD 0 COUNT 0 ASOF`,0至10条`rank REQ INDEX NAME_HEX EMPIRE VALUE`,再`end REQ COUNT`;每帧有`MTF1 `前缀。姓名为原编码1至24字节的小写十六进制,帝国1至3,值为正有符号64位。排序值降序、角色ID升序;取DB已保存值(时长分钟),不等于未落盘在线余额或总资产。单核心异步查询合并、缓存60秒、最多32个等待者;按连接handle/handshake、账号和角色校验。跨核心快照时间可能不同;以上为兼容适配,不冒称五区原规则。 - F20仅保留关闭的候选实现:归档`common/CommonDefines.h:117`为`// #define ENABLE_MAGIC_REDUCTION_SYSTEM`,不能当作活动规则。客户端宏为0,服务端两个伤害入口受同名未定义宏保护,默认仍执行原魔抗公式。候选`APPLY_RESIST_MAGIC_REDUCTION=98`映射`POINT_RESIST_MAGIC_REDUCTION=144`,保持255点数组/原封包;DB文本proto reader、apply映射、PointChange、说明与独立测试已准备,未投放属性道具。候选算法来自归档`char_skill.cpp`/`char_battle.cpp`的非活动分支:魔抗夹至0至100;攻击削抗按修罗减半后夹至0至50;差值夹至0至100,再计算`damage*(100-effective_resistance)/100`,中间乘法64位。该属性为攻击削抗,不是额外防御减伤。启用需另行确认玩法规则并完成固定装备/技能/目标联机验收,不能依据“按活动AVA2重建”的授权自行启用。 - F22实际龙魂布局维持5档/960格,与当前服务端步长一致;保留神话枚举但禁用入口,等两端升级与迁移。F31保持4槽创角,网络预留5槽读取不算服务端完成。其他仍缺配套的玩法宏保持关闭,不能以常量导出计入完成。 +- F19弹药内核按AVA2活动代码接入:`WEAPON_QUIVER=9`,8保留为爪类型但不启用狼人;箭筒沿用箭槽,不增封包字段,普通箭扣量/补箭不变,箭筒不扣量,单次请求最多200。新增到期硬化检查:实时期限遵循既有事件的`now > socket0`,首次使用期限在socket1非0时检查,穿戴计时剩余量非正时拒绝;不自行发明有效期。ProtoReader、零镶孔、禁止随机属性与客户端弹药检查同步。原AVA2专用箭类型外观同步/投射物仍未移植,沿用当前弓箭表现;整体客户端宏保持0,原型投放、联机/持久化/真机验收未完成,不计F19完整实现。归档79501虽名称写1天,实际期限为NONE,且db/share两份价格不同,禁止根据名称推导时间或直接覆盖生产proto。见[箭筒实施记录](XXF-CH5-QUIVER-20261022.md)。 本文历史主体为计划;2026-10-22增量已涉及运行代码,范围与验证见[继续实施记录](XXF-CH5-CONTINUATION-20261022.md)。下文标为“待实现”的工具加固和恢复机制仍须实现与测试证据才能通过门槛;当前两个历史基线提交不因此获得生产可用认证。 +F19数据增量:专用工具仅生成两份AVA2归档一致的79502~79504候选,79501排除。输入必须绑定当前实际注册包的原型/清单/说明;既有型号替换必须显式开启并绑定原型SHA256,前后数值留档。五区79502买价550000改用AVA2归档0,移除当前未启用的狼人禁用位,其余限制保留;不意味着允许免费售卖。只生成隔离产物,不修改Index、服务器原型或商店。完整过程和门槛见[箭筒记录](XXF-CH5-QUIVER-20261022.md)。 + ## 1. 基线、范围和事实来源 diff --git a/docs/XXF-CH5-AUTOMATED-TESTS.md b/docs/XXF-CH5-AUTOMATED-TESTS.md new file mode 100644 index 00000000..a3bd65e0 --- /dev/null +++ b/docs/XXF-CH5-AUTOMATED-TESTS.md @@ -0,0 +1,28 @@ +# 五区统一自动回归 + +入口:`scripts/test_xxf_all.py`。覆盖全部 35 项功能的**状态清单**,执行现有客户端、服务端和数据工具本地测试,不声称已自动验收全部玩法。 + +在 metin2-client 仓库运行: + +```sh +python3 scripts/test_xxf_all.py --list +python3 scripts/test_xxf_all.py +python3 scripts/test_xxf_all.py --suite client --suite data +python3 scripts/test_xxf_all.py --require-complete +``` + +默认服务端仓库为相邻 `metin2-server`,可用 `--server-root` 指定。需要 Python 3、本地 C++ 编译器及各原测试依赖。默认并发 2 个独立进程,每个测试文件超时 180 秒;可用 `--jobs` / `--timeout` 调整。 + +生物学家原版对照测试需 `--ava2-game-source /绝对路径/AVA2/game/src`(包含 constants.cpp 和 cmd_general.cpp)。未提供时记为 blocked,不伪装成通过;生物学家当前战斗测试和传送 Lua 测试的参数由入口自动传入。 + +每次生成新的 `build/ch5-tests/<时间-随机后缀>/`,包含 report.json、report.md 和每个文件的完整日志。`--output` 可指定新目录,不覆盖历史结果。报告包含两个仓库前后 Git 快照、差异摘要、未跟踪代码摘要和测试文件哈希;运行中源码变更会使本次执行失败。资源闭包、构建产物与原服务端规则还需独立证据,Git 快照不能替代它们。 + +测试文件隔离运行,兼容 unittest 和旧式顶层编译/断言脚本。顶层脚本单独标记 `top_level_script_exit_only`,不捏造用例数量。跳过记为 partial;提前退出且没有正常结果标记记为 unverified;失败、超时均保留日志并继续其他测试。 + +退出码:0 表示已选本地测试无硬失败(仍可能有 partial/unverified/blocked);1 表示失败、超时、执行错误或源码在运行中变动;严格模式 `--require-complete` 在存在未完成完整验收时返回 2。参数错误也使用标准 argparse 的退出码 2,应结合报告和终端错误区分。 + +功能关联由脚本中的 ASSOCIATIONS 显式维护:仅说明文件包含该功能的相关检查,不说明全部行为覆盖。比如 F20 测试默认关闭的候选实现,而不是魔法减免已上线。没有登记测试的功能显示 not_covered。共享协议、边界和经济测试仍全部执行,但不随意分配成某项功能已完成。 + +此入口不启动/部署正式服,不发物品、不执行 SQL,不安装 APK,不修改资源 Index,不更新 features.json 的验收状态。自动执行的是现有本地测试(部分测试会在临时目录编译 C++ 探针);尚未接入原生完整构建、隔离真服联机和 Android 真机控制。因此每项功能的 behavior_acceptance、live、android_device 仍标为待验收,可发布始终为否。 + +后续完善顺序:先为 not_covered 功能增加明确断言,再增加隔离服账号/数据生命周期及设备验收适配器。涉及经济和物品的联机测试必须使用独立测试环境及可恢复的数据,不能仅给此脚本配置生产地址后自动执行。 diff --git a/docs/XXF-CH5-CONTINUATION-20261022.md b/docs/XXF-CH5-CONTINUATION-20261022.md index 130010ec..bfaf661d 100644 --- a/docs/XXF-CH5-CONTINUATION-20261022.md +++ b/docs/XXF-CH5-CONTINUATION-20261022.md @@ -2,6 +2,8 @@ 状态:部分实现,未部署。不是35项完成报告。 +同日后续:[F19箭筒内核实施记录](XXF-CH5-QUIVER-20261022.md)。本记录及其散列保留为前一批历史快照,不随新代码覆盖;箭筒后续仍为部分实现。 + ## 规则与证据边界 用户确认:原服规则缺失时采用能够核实的AVA2活动实现,记录与五区原规则可能不同。归档中有代码不等于活动实现,必须同时核对宏定义及实际入口;本轮不恢复或宣称找回五区原服务端。 diff --git a/docs/XXF-CH5-QUIVER-20261022.md b/docs/XXF-CH5-QUIVER-20261022.md new file mode 100644 index 00000000..1fb3d937 --- /dev/null +++ b/docs/XXF-CH5-QUIVER-20261022.md @@ -0,0 +1,62 @@ +# F19箭筒内核实施记录(2026-10-22) + +状态:弹药核心已接入,整体功能部分实现,未部署生产;不等于五区全部功能完成。 + +## 活动来源及适配边界 + +来源为`AVA2/2. Backup SF+SRC and SQL/FILES+SRC.tgz`: + +- `home/Ava2_src/Srcs/Server/common/CommonDefines.h`启用狼人宏,故原`item_length.h`爪编号8、箭筒编号9。当前只补齐编号,不启用狼人创建、技能或伤害类型。 +- `game/src/char_battle.cpp`的`GetArrowAndBow`与`UseArrow`实际活动分支:箭筒可作为箭槽弹药,每次最多200,不扣数量;普通箭按实际数量返回,耗尽后寻找同vnum补箭。 +- `game/src/item_attribute.cpp`排除箭筒的随机属性;原socket表对应零孔。 +- `home/srv1/db/item_proto.txt`和`home/srv1/share/conf/item_proto.txt`均含79501~79504。79502/79503/79504为7/15/30天REAL_TIME;79501虽然名字写1天,实际为LIMIT_NONE,不能自行改成一天。两份79501价格分别100000与0,因此本轮不导入、不改价、不投放。 + +沿用现有定宽子类型与箭装备槽,不新增角色或物品网络字段,也不改变普通弓箭伤害公式。AVA2通过`PART_ARROW_TYPE`同步的专属箭筒外观/飞行特效未移植,当前沿用普通弓箭显示,不能称为视觉还原。 + +## 本轮改动 + +服务端: + +1. `common/item_length.h`加入明确8/9编号;`ProtoReader.cpp`支持对应文本,武器socket表增补两行。 +2. `GetArrowAndBow`接受箭和箭筒,仍要求佩戴弓及正确的武器弹药类型;`UseArrow`只对箭筒跳过扣量。 +3. `port_quiver.h`在返回可用弹药之前检查数量、实时/首次使用/穿戴期限。到期比较沿用既有`real_time_expire_event`的严格大于语义;不删除道具,删除及存储仍走既有事件,避免攻击过程中悬空指针。 +4. `item_attribute.cpp`禁止箭筒进入普通武器随机属性集合;Makefile补充新头依赖。 + +客户端: + +1. `PythonPlayerSkill.cpp::__HasEnoughArrow`识别箭筒,不绕过外层弓/技能条件。 +2. 模型预览、百科分类适配层排除箭筒,避免将其当作手持武器。原AVA2 `WikiUI`源码保持原样,实际预览由已有适配器调用修正后的模型预览判断。 +3. `ENABLE_QUIVER_SYSTEM`仍为0,表示整体功能未验收;它不是上述C++核心分支的运行开关。未投放原型的生产环境不受此候选实现影响。 + +## 验证及修复记录 + +- 服务端`test_quiver_runtime.py`编译实际`GetArrowAndBow/UseArrow`及新到期函数,ASan/UBSan下验证缺弓/缺弹药/错误类型、普通箭扣量补箭、200上限、1000轮不扣箭筒、三种计时边界与移除后拒绝。 +- 客户端同名测试编译实际弹药检查函数,验证箭/箭筒允许,空格/错误子类型/非武器拒绝。 +- 模型预览测试加入箭筒原型与导出常量;全体`tests/wiki`共188项通过。 +- 全体脚本测试暴露既有Python3夹具无法解析Python2的`exec code in dict`,只在测试夹具中转换语法,运行源码未更改;C++回归使用真实内嵌Python2。 +- 首次FreeBSD构建发现新头文件放在`item.h`之前导致不完整类型错误,已将include移到依赖头之后;独立函数测试通过并不能替代真实构建。 + +原生及FreeBSD最终验证结果、源码与产物散列见[本轮候选证据](../audit/xxf-ch5/quiver-20261022.json)。没有Android或生产联机验收结论。 + +## 尚缺的闭环 + +- 确认当前服务器采用哪份proto、79501价格/有效期和禁用标志映射,生成两端一致的原型补丁;未核对前不自动合入生产或商城。 +- 原专用箭类型外观同步及特效;实机弓/技能连发、下马、武器时装组合测试。 +- 真实装备、卸下、移动、交易/仓库、重登、离线到期及过期移除后状态恢复验收。当前测试验证攻击判断,不冒充物品持久化测试。 +- 匹配的测试客户端/服务端联机及Android构建/真机验收,通过后才考虑开启整体宏。 + +前一轮Git快照已推送:客户端`60ed6669`、服务端`5b7442e`,分支均为`feature/ava2-unlock`。本文件所述箭筒增量不包含在那两个历史提交内。 + +## 同日后续:三个限时型号的数据链 + +新增[候选生成工具说明](../tools/server/ava2-items/QUIVER.md),实现仅处理79502~79504的显式转换、两份归档规则交叉校验、冻结输入、完整数值覆盖差异、未涉及记录校验、双语言原型及文本合并、私有图标打包。 + +只读核对203进程工作目录与文件:正式db使用`/usr/metin2/server/db/item_proto.txt`(链接至share/conf),隔离db使用`/usr/metin2/server/sbtest/db/item_proto.txt`,均没有79501~79504。没有据此修改服务器文件。 + +另核对五区当前客户端:79501实际是1天REAL_TIME、79502买价550000,与AVA2归档原型不同。按用户确认的AVA2重建策略,候选只覆盖三个明确限时型号;79502买价采用归档服务端的0并记录差异,不构成免费售卖或上架授权。79501不变。 + +实际预检还发现解包参考目录的`itemdesc.txt`与当前有效包不一致。新增`eterpack_pack --read-client`原生只读模式,经真实Index及密钥回退读取三个输入,禁止松散文件覆盖和已有输出覆盖;生成器现在默认直接使用这些有效资源,参考目录只能用于额外校验。 + +最终候选产物在`build/ch5-quiver-bound-20261022/`:总数11545,替换3,另外11542条记录保持;7个包内文件全部原生回读通过。`ANTI_WOLFMAN`按现有四职业转换器移除,其余限制保留,未来开放狼人前须重新核对。31项数据/工具测试与188项脚本回归通过,详见[本批数据证据](../audit/xxf-ch5/quiver-data-20261022.json)。之前基于旧目录生成的实验产物不作为当前候选。 + +此进展只收尾候选数据生成,不关闭上述专用外观、真实装备/存储/重登/到期、匹配联机及Android门槛;`ENABLE_QUIVER_SYSTEM`仍为0,未投放或部署。本批未改运行逻辑,FreeBSD内核构建证据仍是前一批,而不是本次又执行一次构建。 diff --git a/scripts/build_xxf_features_json.py b/scripts/build_xxf_features_json.py index 84164ccb..22d90792 100644 --- a/scripts/build_xxf_features_json.py +++ b/scripts/build_xxf_features_json.py @@ -666,6 +666,14 @@ def main(): ] for feature in features: + if feature['id'] == 'F19': + feature['implementation']['server'] = 'src/server/game/src/port_quiver.h' + feature['implementation']['client'] = 'src/port/UserInterface/PythonPlayerSkill.cpp' + feature['implementation']['entrypoints'] = ['CHARACTER::GetArrowAndBow', 'CHARACTER::UseArrow', 'CPythonPlayer::__HasEnoughArrow'] + feature['rules']['unresolved'] = ['79501 excluded due conflicting price/duration metadata; timed 79502-79504 candidate generated but not installed', 'Native arrow-type visual sync and matched live/device/item-lifecycle acceptance'] + feature['rules']['accepted_differences'] = ['AVA2 active quiver9 semantics; claw8 reserved only; explicit pre-shot expiry checks; classic arrow visual fallback; whole-feature macro stays off'] + feature['blockers'] = list(feature['rules']['unresolved']) + feature['status']['source'] = 'partially_verified' for source in feature['source']: path = os.path.join(os.path.dirname(repo_root), source['path']) source['sha256'] = sha256_file(path) diff --git a/scripts/test_xxf_all.py b/scripts/test_xxf_all.py new file mode 100644 index 00000000..72ec88fa --- /dev/null +++ b/scripts/test_xxf_all.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +"""Local CH5 regression orchestrator. Never deploys, connects to a game server or grants release readiness.""" +import argparse +import concurrent.futures +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import signal +import subprocess +import sys +import tempfile +import time +import unittest + +ROOT = Path(__file__).resolve().parents[1] +MARKER = 'CH5_TEST_RESULT=' + +# File-level associations, not claims that every behavior of a feature is tested. +ASSOCIATIONS = { + 'F01': ['test_feature_manifest', 'test_model_preview'], + 'F02': ['test_queries', 'test_drops'], + 'F03': [], 'F04': [], 'F05': [], 'F06': [], 'F07': [], 'F08': [], + 'F09': ['test_special_storage', 'test_legacy_item_ids'], + 'F10': ['test_channel', 'test_native_channel', 'test_ava2_channel_registry', 'test_live_endpoint'], + 'F11': ['test_catalogue', 'test_chest', 'test_ava2_chest', 'test_pickup', 'test_ava2_pickup', 'test_drops', 'test_queries'], + 'F12': ['test_attr_lock', 'test_attr_lock_snapshots', 'test_attr_lock_ui', 'test_attr_lock_use', 'test_attr_lock_views', 'test_switchbot', 'test_switchbot_matching'], + 'F13': ['test_sash'], 'F14': ['test_pendant', 'test_applies'], + 'F15': ['test_costume_slots', 'test_mount', 'test_product_costume_runtime', 'test_costume_products', 'test_costume_attr'], + 'F16': ['test_shop_appearance'], 'F17': ['test_extended_items'], + 'F18': ['test_extended_items'], 'F19': ['test_quiver', 'test_quiver_runtime'], + 'F20': ['test_magic_reduction'], 'F21': ['test_cube_gold_debit'], + 'F22': ['test_dragonsoul_alchemy'], 'F23': ['test_dragonsoul_alchemy'], + 'F24': ['test_rank', 'test_rank_runtime'], 'F25': [], + 'F26': ['test_ticket_shop', 'test_ava2_ticket_shop', 'test_gaya_market', 'test_gaya_runtime', 'test_gaya_catalog'], + 'F27': ['test_offline_search_names', 'test_offline_shop', 'test_offlineshop'], + 'F28': ['test_offline_shop', 'test_offlineshop', 'test_shop_economy_runtime', 'test_economy_reconcile', 'test_economy_coordinator'], + 'F29': ['test_gold64', 'test_economy', 'test_economy_game_ui', 'test_economy_view', 'test_economy_reconcile'], + 'F30': [], 'F31': [], 'F32': [], 'F33': [], + 'F34': ['test_pet_system', 'test_pet_commands_runtime', 'test_rare_attrs_and_skills'], + 'F35': ['test_battlepass', 'test_calendar', 'test_boss', 'test_bosses', 'test_track_config', 'test_ava2_track', 'test_ava2_dungeon_track', 'test_native_track', 'test_timers'], +} + + +def sha(path): + return hashlib.sha256(Path(path).read_bytes()).hexdigest() + + +def child(path, arguments=()): + """Import in its own process: supports unittest classes AND legacy top-level probes.""" + path = Path(path).resolve() + sys.argv = [str(path), *arguments] # never leak the orchestrator's --child option + sys.path.insert(0, str(path.parent)) + spec = importlib.util.spec_from_file_location('ch5_isolated_test', path) + mod = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = mod + spec.loader.exec_module(mod) + suite = unittest.defaultTestLoader.loadTestsFromModule(mod) + result = unittest.TextTestRunner(verbosity=2).run(suite) + details = dict(tests=result.testsRun, skipped=len(result.skipped), + failures=len(result.failures), errors=len(result.errors), + mode='unittest' if result.testsRun else 'top_level_script_exit_only', + skip_reasons=[reason for _, reason in result.skipped]) + print(MARKER + json.dumps(details), flush=True) + return 0 if result.wasSuccessful() else 1 + + +def discover(root=ROOT, server=None, ava2_game_source=None): + server = server or root.parent / 'metin2-server' + groups = {'client': [root / 'tests/wiki'], + 'server': [server / 'tests/features', server / 'tests/wiki'], + 'data': [root / 'tools/server/ava2-items/tests', + root / 'tools/server/biolog/tests', root / 'tools/server/ring-warp/tests'], + 'runner': [root / 'tests/ch5']} + jobs = [] + for group, folders in groups.items(): + for folder in folders: + for path in sorted(folder.glob('test_*.py')): + job = dict(id=group + ':' + str(path.relative_to(root if group != 'server' else server)), + suite=group, path=str(path), stem=path.stem, + cwd=str(root if group != 'server' else server), arguments=[]) + if path == root / 'tools/server/biolog/tests/test_combat.py': + job['arguments'] = [str(server / 'src/server/game/src/battle.cpp')] + elif path == root / 'tools/server/ring-warp/tests/test_ring.py': + job['arguments'] = [str(server / 'src/server/liblua')] + elif path == root / 'tools/server/biolog/tests/test_ava2.py': + if ava2_game_source: + job['arguments'] = [str(ava2_game_source)] + else: + job['blocked_reason'] = 'Needs original AVA2 game source: --ava2-game-source (constants.cpp and cmd_general.cpp)' + jobs.append(job) + return jobs + + +def execute(job, output, timeout): + started = time.monotonic() + log = output / (hashlib.sha256(job['id'].encode()).hexdigest()[:16] + '.log') + result = dict(job, log=log.name, test_sha256=sha(job['path'])) + if job.get('blocked_reason'): + log.write_text(job['blocked_reason'] + '\n') + result.update(status='blocked', seconds=0) + return result + with log.open('wb') as stream: + try: + env = dict(os.environ, PYTHONUNBUFFERED='1', PYTHONDONTWRITEBYTECODE='1') + command = [sys.executable, str(Path(__file__).resolve()), '--child', job['path'], + '--child-args', json.dumps(job.get('arguments', []))] + result['command'] = command + proc = subprocess.Popen(command, + cwd=job['cwd'], stdout=stream, stderr=subprocess.STDOUT, + env=env, start_new_session=True) + try: + code = proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + os.killpg(proc.pid, signal.SIGKILL) + proc.wait() + result.update(status='timeout', returncode=proc.returncode) + else: + result.update(status='pass' if code == 0 else 'fail', returncode=code) + except OSError as exc: + result.update(status='error', error=str(exc)) + raw = log.read_text(errors='replace') + for line in reversed(raw.splitlines()): + if line.startswith(MARKER): + result['details'] = json.loads(line[len(MARKER):]) + if result['status'] == 'pass' and result['details']['skipped']: + result['status'] = 'partial' # unittest's exit 0 may hide skipped native probes + break + if result['status'] == 'pass' and 'details' not in result: + result['status'] = 'unverified' # premature sys.exit(0) is not accepted as test evidence + result['seconds'] = round(time.monotonic() - started, 3) + return result + + +def feature_results(features, results): + out = [] + for feature in features: + fid = feature['id'] + linked = [r for r in results if r['stem'] in ASSOCIATIONS.get(fid, [])] + statuses = {r['status'] for r in linked} + local = ('fail' if statuses & {'fail', 'timeout', 'error'} else + 'partial' if statuses & {'partial', 'unverified', 'blocked'} else + 'related_tests_pass' if linked else 'not_covered') + out.append(dict(id=fid, name=feature['name'], local=local, + related_tests=[r['id'] for r in linked], + implementation=feature['status']['implementation'], + behavior_acceptance='pending', live='not_run', android_device='not_run', + release_ready=False)) + return out + + +def snapshot(repo): + def git(*args): + return subprocess.check_output(['git', '-C', str(repo), *args], stderr=subprocess.DEVNULL) + try: + status = git('status', '--porcelain=v1', '-uall').decode(errors='replace') + untracked = git('ls-files', '--others', '--exclude-standard', '-z').split(b'\0') + # Bind source changes including new files, without hashing multi-GB resource packs. + hashes = {os.fsdecode(p): sha(repo / os.fsdecode(p)) for p in untracked if p + and (repo / os.fsdecode(p)).is_file() + and Path(os.fsdecode(p)).suffix in {'.py', '.cpp', '.h', '.inc', '.json', '.md'}} + return dict(head=git('rev-parse', 'HEAD').decode().strip(), status=status, + diff_sha256=hashlib.sha256(git('diff', 'HEAD', '--binary')).hexdigest(), + untracked_source_sha256=hashes) + except (OSError, subprocess.CalledProcessError): + return dict(error='git snapshot unavailable') + + +def render(report): + lines = ['# 五区自动回归报告', '', + '这是本地回归结果,不是全部功能、真服或 Android 验收结论。', '', + f"本地汇总:{json.dumps(report['summary'], ensure_ascii=False)}", '', + '| 功能 | 关联本地测试 | 真服 | Android | 可发布 |', + '| --- | --- | --- | --- | --- |'] + for f in report['features']: + lines.append(f"| {f['id']} {f['name']} | {f['local']} | 未测 | 未测 | 否 |") + lines += ['', '## 非通过测试', ''] + for r in report['results']: + if r['status'] != 'pass': + lines.append(f"- {r['id']}: {r['status']},日志 [{r['log']}]({r['log']})") + lines += ['', '全部测试的命令、耗时、跳过原因和源码快照见 report.json。', + '未覆盖表示没有登记的直接关联测试;关联测试通过也不代表该功能完整通过。', ''] + return '\n'.join(lines) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--child', help=argparse.SUPPRESS) + parser.add_argument('--child-args', default='[]', help=argparse.SUPPRESS) + parser.add_argument('--suite', action='append', choices=['client', 'server', 'data', 'runner']) + parser.add_argument('--jobs', type=int, default=2) + parser.add_argument('--timeout', type=float, default=180) + parser.add_argument('--server-root', type=Path, default=ROOT.parent / 'metin2-server') + parser.add_argument('--ava2-game-source', type=Path, help='Original AVA2 game/src for biology source comparison (optional)') + parser.add_argument('--output', type=Path, help='New directory only; existing directories are never overwritten') + parser.add_argument('--list', action='store_true') + parser.add_argument('--require-complete', action='store_true', help='Exit 2 when any full acceptance gate is pending') + args = parser.parse_args(argv) + if args.child: + return child(args.child, json.loads(args.child_args)) + if args.jobs < 1 or args.timeout <= 0: + parser.error('jobs and timeout must be positive') + jobs = discover(server=args.server_root.resolve(), + ava2_game_source=args.ava2_game_source.resolve() if args.ava2_game_source else None) + selected = set(args.suite or ['client', 'server', 'data', 'runner']) + jobs = [j for j in jobs if j['suite'] in selected] + missing = selected - {j['suite'] for j in jobs} + if missing: + parser.error('missing test suites: ' + ', '.join(sorted(missing))) + if args.list: + for j in jobs: + print(j['id']) + return 0 + manifest = ROOT / 'audit/xxf-ch5/features.json' + features = json.loads(manifest.read_text())['features'] + if {f['id'] for f in features} != set(ASSOCIATIONS) or len(features) != len(ASSOCIATIONS): + parser.error('feature manifest changed; update explicit coverage mapping first') + if args.output: + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=False) + else: + parent = ROOT / 'build/ch5-tests' + parent.mkdir(parents=True, exist_ok=True) + output = Path(tempfile.mkdtemp(prefix=time.strftime('%Y%m%d-%H%M%S-'), dir=parent)) + before = {str(p): snapshot(p) for p in [ROOT, args.server_root.resolve()]} + results = [] + print('Report directory:', output, flush=True) + with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as pool: + pending = [pool.submit(execute, j, output, args.timeout) for j in jobs] + for future in concurrent.futures.as_completed(pending): + result = future.result() + results.append(result) + print(f"[{len(results)}/{len(jobs)}] {result['status']}: {result['id']}", flush=True) + results.sort(key=lambda r: r['id']) + after = {str(p): snapshot(p) for p in [ROOT, args.server_root.resolve()]} + summary = {s: sum(r['status'] == s for r in results) + for s in ['pass', 'partial', 'fail', 'timeout', 'error', 'unverified', 'blocked']} + report = dict(schema_version=1, manifest_sha256=sha(manifest), results=results, + summary=summary, features=feature_results(features, results), + source_before=before, source_after=after, source_changed=before != after, + release_ready=False, scope='local regression only; no native build, live or device acceptance') + (output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n') + (output / 'report.md').write_text(render(report)) + print(json.dumps(summary), '\nReport:', output / 'report.md') + if any(summary[s] for s in ['fail', 'timeout', 'error']) or before != after: + return 1 + if args.require_complete: + return 2 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/src/platform/ScriptLib/Ava2NativeDataScript.inc b/src/platform/ScriptLib/Ava2NativeDataScript.inc index b203ba2e..c736adc8 100644 --- a/src/platform/ScriptLib/Ava2NativeDataScript.inc +++ b/src/platform/ScriptLib/Ava2NativeDataScript.inc @@ -26,7 +26,7 @@ def Load(): if r['refined']:_parents[r['refined']]=v if not item.SelectItemWiki(v):continue # AVA2 lists the last refine stage; the original UI expands its complete chain. - category=0 if r['kind']=='ITEM_WEAPON' and r['subtype']!='WEAPON_ARROW' else armor.get(r['subtype']) if r['kind']=='ITEM_ARMOR' else 8 if r['kind']=='ITEM_BELT' else 10 if r['kind']=='ITEM_NEW_RINGS' else None + category=0 if r['kind']=='ITEM_WEAPON' and r['subtype'] not in ('WEAPON_ARROW','WEAPON_QUIVER') else armor.get(r['subtype']) if r['kind']=='ITEM_ARMOR' else 8 if r['kind']=='ITEM_BELT' else 10 if r['kind']=='ITEM_NEW_RINGS' else None if category is not None and not r['refined']: for job in xrange(4): if not item.IsAntiFlag(jobs[job]):_categories.setdefault((job,category),[]).append(v) diff --git a/src/platform/ScriptLib/FeatureServiceScript.inc b/src/platform/ScriptLib/FeatureServiceScript.inc index 6450e88e..e63c5251 100644 --- a/src/platform/ScriptLib/FeatureServiceScript.inc +++ b/src/platform/ScriptLib/FeatureServiceScript.inc @@ -7,8 +7,8 @@ import ui import binascii from mt_wiki_data import Number -BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32,'bosses':256,'travel':512,'rank':1024} -WHOLE=('stats','dungeons','bosses') # one reply with every row; no subject or page +BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32,'bosses':256,'travel':512,'rank':1024,'quiver':2048} +WHOLE=('stats','dungeons','bosses','quiver') # one reply with every row; no subject or page g_service=None g_tick=None _serial=0 @@ -155,6 +155,9 @@ _command=game.GameWindow.BINARY_ServerCommand_Run def Open(self): global g_service,g_tick _open(self);g_service=Service();g_tick=TickWindow() + # Triggers the existing capability handshake. Old servers never receive an + # unknown quiver command: unsupported capabilities are filtered in Tick. + g_service.Request('quiver',0,0,lambda result,error:None) def Close(self): global g_service,g_tick diff --git a/src/platform/ScriptLib/ModelPreviewScript.inc b/src/platform/ScriptLib/ModelPreviewScript.inc index 6fc0f784..ecc288c3 100644 --- a/src/platform/ScriptLib/ModelPreviewScript.inc +++ b/src/platform/ScriptLib/ModelPreviewScript.inc @@ -43,7 +43,7 @@ def ItemSpec(vnum): item.SelectItem(vnum) kind=item.GetItemType();sub=item.GetItemSubType() except (RuntimeError,TypeError):return None - if kind==item.ITEM_TYPE_WEAPON and sub!=item.WEAPON_ARROW:slot='weapon' + if kind==item.ITEM_TYPE_WEAPON and sub not in (item.WEAPON_ARROW,item.WEAPON_QUIVER):slot='weapon' elif kind==item.ITEM_TYPE_ARMOR and sub==item.ARMOR_BODY:slot='armor' elif kind==item.ITEM_TYPE_COSTUME and sub==item.COSTUME_TYPE_BODY:slot='armor' elif kind==item.ITEM_TYPE_COSTUME and sub==item.COSTUME_TYPE_HAIR:slot='hair' diff --git a/src/platform/ScriptLib/PythonBoot.cpp b/src/platform/ScriptLib/PythonBoot.cpp index 6918df6c..72796531 100644 --- a/src/platform/ScriptLib/PythonBoot.cpp +++ b/src/platform/ScriptLib/PythonBoot.cpp @@ -1064,6 +1064,7 @@ namespace PythonBoot #include "BattlePassScript.inc" #include "AppliesScript.inc" #include "ArmorShapesScript.inc" +#include "QuiverMotionScript.inc" #include "SashScript.inc" #include "MountScript.inc" #include "Ava2MapsScript.inc" @@ -1188,6 +1189,7 @@ bool RunMainScript(const char* lpCmdLine, std::string* error) install_script_module("mt_battlepass", c_szBattlePassScript); install_script_module("mt_applies", c_szAppliesScript); install_script_module("mt_shapes", c_szArmorShapesScript); + install_script_module("mt_quiver_motion", c_szQuiverMotionScript); install_script_module("mt_sash", c_szSashScript); install_script_module("mt_mount", c_szMountScript); install_script_module("mt_ava2maps", c_szAva2MapsScript); diff --git a/src/platform/ScriptLib/QuiverMotionScript.inc b/src/platform/ScriptLib/QuiverMotionScript.inc new file mode 100644 index 00000000..ce123414 --- /dev/null +++ b/src/platform/ScriptLib/QuiverMotionScript.inc @@ -0,0 +1,38 @@ +// PORT: register the active AVA2 special bow mode without changing packed scripts. +static const char c_szQuiverMotionScript[] = R"PY( +import chr +import chrmgr +import pack +import playersettingmodule + +loaded={} +FILES=(('MOTION_WAIT','wait.msa',70),('MOTION_WAIT','wait_1.msa',30), + ('MOTION_WALK','walk.msa',100),('MOTION_RUN','run.msa',100), + ('MOTION_DAMAGE','damage.msa',50),('MOTION_DAMAGE','damage_1.msa',50), + ('MOTION_DAMAGE_BACK','damage_2.msa',50),('MOTION_DAMAGE_BACK','damage_3.msa',50), + ('MOTION_COMBO_ATTACK_1','attack_special.msa',100)) + +def Register(): + for race,folder in ((playersettingmodule.RACE_ASSASSIN_W,'pc'), + (playersettingmodule.RACE_ASSASSIN_M,'pc2')): + path='d:/ymir work/%s/assassin/bow/'%folder + if not all(pack.Exist(path+name) for _,name,_ in FILES): + loaded[race]=False + continue + chrmgr.SelectRace(race) + chrmgr.SetPathName(path) + mode=chr.MOTION_MODE_BOW_SPECIAL + chrmgr.RegisterMotionMode(mode) + for motion,name,weight in FILES: + chrmgr.RegisterCacheMotionData(mode,getattr(chr,motion),name,weight) + chrmgr.ReserveComboAttackNew(mode,0,1) + chrmgr.RegisterComboAttackNew(mode,0,0,chr.MOTION_COMBO_ATTACK_1) + loaded[race]=True + +_load=playersettingmodule.LoadGameData +def LoadGameData(name): + result=_load(name) + if name=='ASSASSIN':Register() + return result +playersettingmodule.LoadGameData=LoadGameData +)PY"; diff --git a/src/port/GameLib/ActorInstance.cpp b/src/port/GameLib/ActorInstance.cpp index a5db53d5..94015cba 100644 --- a/src/port/GameLib/ActorInstance.cpp +++ b/src/port/GameLib/ActorInstance.cpp @@ -258,7 +258,7 @@ bool CActorInstance::IsTwoHandMode() bool CActorInstance::IsBowMode() { - if (CRaceMotionData::MODE_BOW==GetMotionMode()) + if (CRaceMotionData::MODE_BOW==GetMotionMode() || CRaceMotionData::MODE_BOW_SPECIAL==GetMotionMode()) return true; if (CRaceMotionData::MODE_HORSE_BOW==GetMotionMode()) diff --git a/src/port/GameLib/RaceMotionData.h b/src/port/GameLib/RaceMotionData.h index 684ee886..4456b23d 100644 --- a/src/port/GameLib/RaceMotionData.h +++ b/src/port/GameLib/RaceMotionData.h @@ -53,6 +53,7 @@ class CRaceMotionData MODE_CLAW, MODE_HORSE_CLAW, + MODE_BOW_SPECIAL, // PORT: AVA2 quiver, append without renumbering existing modes. MODE_MAX_NUM, }; @@ -305,4 +306,4 @@ class CRaceMotionData protected: static CDynamicPool ms_kPool; -}; \ No newline at end of file +}; diff --git a/src/port/UserInterface/InstanceBase.cpp b/src/port/UserInterface/InstanceBase.cpp index 57cee2b8..b7e180c7 100644 --- a/src/port/UserInterface/InstanceBase.cpp +++ b/src/port/UserInterface/InstanceBase.cpp @@ -11,6 +11,7 @@ #include "../EterLib/StateManager.h" #include "../GameLib/ItemManager.h" +#include "../GameLib/RaceManager.h" BOOL HAIR_COLOR_ENABLE=FALSE; BOOL USE_ARMOR_SPECULAR=FALSE; @@ -2864,6 +2865,29 @@ UINT CInstanceBase::__GetRefinedEffect(CItemData* pItem) return 0; } +bool CInstanceBase::HasQuiverMotion() const +{ + CRaceData* race=nullptr;MOTION_KEY key; + return m_arrowType==CItemData::WEAPON_QUIVER && + CRaceManager::Instance().GetRaceDataPointer(m_dwRace,&race) && + race->GetMotionKey(CRaceMotionData::MODE_BOW_SPECIAL,CRaceMotionData::NAME_COMBO_ATTACK_1,&key); +} + +void CInstanceBase::SetArrowType(BYTE type) +{ + if (type!=0 && type!=CItemData::WEAPON_ARROW && type!=CItemData::WEAPON_QUIVER)return; + if(m_arrowType==type)return; + m_arrowType=type; + CItemData* weapon=nullptr; + if (IsPoly() || IsWearingDress() || m_kHorse.IsMounting())return; + if(CItemManager::Instance().GetItemDataPointer(m_GraphicThingInstance.GetPartItemID(CRaceData::PART_WEAPON),&weapon)) + { + bool bow=weapon->GetType()==CItemData::ITEM_TYPE_WEAPON && weapon->GetWeaponType()==CItemData::WEAPON_BOW; + bow=bow || (weapon->GetType()==CItemData::ITEM_TYPE_COSTUME && weapon->GetSubType()==CItemData::COSTUME_WEAPON && weapon->GetValue(3)==CItemData::WEAPON_BOW); + if(bow)SetMotionMode(HasQuiverMotion()?CRaceMotionData::MODE_BOW_SPECIAL:CRaceMotionData::MODE_BOW); + } +} + bool CInstanceBase::SetWeapon(DWORD eWeapon) { if (IsPoly()) @@ -2987,6 +3011,9 @@ void CInstanceBase::RefreshState(DWORD dwMotIndex, bool isLoop) { byItemType = pItemData->GetType(); bySubType = pItemData->GetWeaponType(); + // PORT: costume weapon subtype is not its underlying weapon class. + if(byItemType==CItemData::ITEM_TYPE_COSTUME && bySubType==CItemData::COSTUME_WEAPON) + bySubType=BYTE(pItemData->GetValue(3)); } if (IsPoly()) @@ -3069,7 +3096,7 @@ void CInstanceBase::RefreshState(DWORD dwMotIndex, bool isLoop) break; case CItemData::WEAPON_BOW: - SetMotionMode(CRaceMotionData::MODE_BOW); // Only Assassin + SetMotionMode(HasQuiverMotion()?CRaceMotionData::MODE_BOW_SPECIAL:CRaceMotionData::MODE_BOW); break; case CItemData::WEAPON_FAN: @@ -3215,6 +3242,7 @@ void CInstanceBase::__Initialize() m_stName = ""; memset(m_awPart, 0, sizeof(m_awPart)); + m_arrowType=0; memset(m_adwCRCAffectEffect, 0, sizeof(m_adwCRCAffectEffect)); //memset(m_adwCRCEmoticonEffect, 0, sizeof(m_adwCRCEmoticonEffect)); memset(&m_kMovAfterFunc, 0, sizeof(m_kMovAfterFunc)); diff --git a/src/port/UserInterface/InstanceBase.h b/src/port/UserInterface/InstanceBase.h index bcd54fdc..610cfd49 100644 --- a/src/port/UserInterface/InstanceBase.h +++ b/src/port/UserInterface/InstanceBase.h @@ -509,6 +509,9 @@ class CInstanceBase void SetShape(DWORD eShape, float fSpecular=0.0f); void SetHair(DWORD eHair); bool SetWeapon(DWORD eWeapon); + void SetArrowType(BYTE type); + BYTE GetArrowType() const { return m_arrowType; } + bool HasQuiverMotion() const; bool ChangeArmor(DWORD dwArmor); void ChangeWeapon(DWORD eWeapon); void ChangeHair(DWORD eHair); @@ -914,6 +917,7 @@ class CInstanceBase std::string m_stName; DWORD m_awPart[CRaceData::PART_MAX_NUM]; + BYTE m_arrowType; // PORT: transient, never part of persisted/wire part arrays. DWORD m_dwLevel; DWORD m_dwEmpireID; diff --git a/src/port/UserInterface/NetworkActorManager.cpp b/src/port/UserInterface/NetworkActorManager.cpp index b96e7b9f..3350e9f3 100644 --- a/src/port/UserInterface/NetworkActorManager.cpp +++ b/src/port/UserInterface/NetworkActorManager.cpp @@ -78,6 +78,7 @@ void SNetworkActorData::__copy__(const SNetworkActorData& src) m_dwWeapon = src.m_dwWeapon; m_dwHair = src.m_dwHair; m_dwSash = src.m_dwSash; // PORT: AVA2 sash + m_arrowType = src.m_arrowType; m_dwOwnerVID = src.m_dwOwnerVID; @@ -106,6 +107,7 @@ SNetworkActorData::SNetworkActorData() m_dwWeapon=0; m_dwHair=0; m_dwSash=0; // PORT: AVA2 sash + m_arrowType=0; m_dwEmpireID=0; m_dwOwnerVID=0; @@ -383,6 +385,7 @@ CInstanceBase* CNetworkActorManager::__AppendCharacterManagerActor(SNetworkActor CInstanceBase* pNewInstance = rkChrMgr.CreateInstance(kCreateData); if (!pNewInstance) return NULL; + pNewInstance->SetArrowType(rkNetActorData.m_arrowType); if (kCreateData.m_isMain) { @@ -408,6 +411,16 @@ CInstanceBase* CNetworkActorManager::__AppendCharacterManagerActor(SNetworkActor return pNewInstance; } +void CNetworkActorManager::SetActorArrowType(DWORD vid, BYTE type) +{ + if (type!=0 && type!=6 && type!=9)return; + auto it=m_kNetActorDict.find(vid); + if (it==m_kNetActorDict.end())return; // Never queue unknown/stale VIDs for a future spawn. + it->second.m_arrowType=type; + CInstanceBase* instance=CPythonCharacterManager::Instance().GetInstancePtr(vid); + if(instance)instance->SetArrowType(type); +} + void CNetworkActorManager::AppendActor(const SNetworkActorData& c_rkNetActorData) { if (__IsMainActorVID(c_rkNetActorData.m_dwVID)) diff --git a/src/port/UserInterface/NetworkActorManager.h b/src/port/UserInterface/NetworkActorManager.h index 420be5b4..e04c9202 100644 --- a/src/port/UserInterface/NetworkActorManager.h +++ b/src/port/UserInterface/NetworkActorManager.h @@ -32,6 +32,7 @@ struct SNetworkActorData DWORD m_dwWeapon; DWORD m_dwHair; DWORD m_dwSash; // PORT: AVA2 sash + BYTE m_arrowType; // PORT: transient, separate negotiated packet, not actor wire parts. DWORD m_dwOwnerVID; @@ -127,6 +128,7 @@ class CNetworkActorManager : public CReferenceObject void RemoveActor(DWORD dwVID); void AppendActor(const SNetworkActorData& c_rkNetActorData); + void SetActorArrowType(DWORD vid, BYTE type); void UpdateActor(const SNetworkUpdateActorData& c_rkNetUpdateActorData); void MoveActor(const SNetworkMoveActorData& c_rkNetMoveActorData); diff --git a/src/port/UserInterface/Packet.h b/src/port/UserInterface/Packet.h index d723f792..571397bd 100644 --- a/src/port/UserInterface/Packet.h +++ b/src/port/UserInterface/Packet.h @@ -390,6 +390,7 @@ enum HEADER_GC_AVA2_DROP = 220, HEADER_GC_SWITCHBOT = 171, // PORT: AVA2 switchbot, DYNAMIC_SIZE_PACKET HEADER_GC_EXTENDED_POINTS = 218, // PORT: AVA2 64-bit gold and extended points + HEADER_GC_PORT_QUIVER = 219, // PORT: sent only after quiver capability subscription. #if defined(ENABLE_ATTR_6TH_7TH) HEADER_GC_OPEN_67_ATTR = 242, #endif @@ -1362,6 +1363,14 @@ enum ECharacterEquipmentPart CHR_EQUIPPART_NUM, }; +struct TPacketGCQuiverState +{ + BYTE header; + DWORD vid; + BYTE type; +}; +static_assert(sizeof(TPacketGCQuiverState)==6,"quiver state wire size"); + typedef struct packet_char_additional_info { BYTE header; diff --git a/src/port/UserInterface/PythonCharacterModule.cpp b/src/port/UserInterface/PythonCharacterModule.cpp index 113b532e..cc731e5b 100644 --- a/src/port/UserInterface/PythonCharacterModule.cpp +++ b/src/port/UserInterface/PythonCharacterModule.cpp @@ -1441,6 +1441,7 @@ void initchr() PyModule_AddIntConstant(poModule, "MOTION_MODE_TWOHAND_SWORD", CRaceMotionData::MODE_TWOHAND_SWORD); PyModule_AddIntConstant(poModule, "MOTION_MODE_DUALHAND_SWORD", CRaceMotionData::MODE_DUALHAND_SWORD); PyModule_AddIntConstant(poModule, "MOTION_MODE_BOW", CRaceMotionData::MODE_BOW); + PyModule_AddIntConstant(poModule, "MOTION_MODE_BOW_SPECIAL", CRaceMotionData::MODE_BOW_SPECIAL); PyModule_AddIntConstant(poModule, "MOTION_MODE_FAN", CRaceMotionData::MODE_FAN); PyModule_AddIntConstant(poModule, "MOTION_MODE_BELL", CRaceMotionData::MODE_BELL); PyModule_AddIntConstant(poModule, "MOTION_MODE_CLAW", CRaceMotionData::MODE_CLAW); diff --git a/src/port/UserInterface/PythonNetworkStream.cpp b/src/port/UserInterface/PythonNetworkStream.cpp index 7130d708..099e2fd8 100644 --- a/src/port/UserInterface/PythonNetworkStream.cpp +++ b/src/port/UserInterface/PythonNetworkStream.cpp @@ -187,6 +187,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_PORT_QUIVER, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCQuiverState), STATIC_SIZE_PACKET)); Set(HEADER_GC_CHESTDROP, CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCChestDrop), DYNAMIC_SIZE_PACKET)); Set(HEADER_GC_AVA2_DROP,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Drop),STATIC_SIZE_PACKET)); Set(93,CNetworkPacketHeaderMap::TPacketType(sizeof(TPacketGCAva2Events),DYNAMIC_SIZE_PACKET)); diff --git a/src/port/UserInterface/PythonNetworkStream.h b/src/port/UserInterface/PythonNetworkStream.h index 7f020bce..ad50ebc2 100644 --- a/src/port/UserInterface/PythonNetworkStream.h +++ b/src/port/UserInterface/PythonNetworkStream.h @@ -598,6 +598,7 @@ class CPythonNetworkStream : public CNetworkStream, public CSingletonSetActorArrowType(packet.vid,packet.type); + return true; +} + bool CPythonNetworkStream::RecvCharacterUpdatePacket() { TPacketGCCharacterUpdate chrUpdatePacket; diff --git a/src/port/UserInterface/PythonPlayerSkill.cpp b/src/port/UserInterface/PythonPlayerSkill.cpp index 6fd32103..007017ca 100644 --- a/src/port/UserInterface/PythonPlayerSkill.cpp +++ b/src/port/UserInterface/PythonPlayerSkill.cpp @@ -827,7 +827,9 @@ bool CPythonPlayer::__HasEnoughArrow() CItemData * pItemData; if (CItemManager::Instance().GetItemDataPointer(GetItemIndex(TItemPos(INVENTORY, c_Equipment_Arrow)), &pItemData)) if (CItemData::ITEM_TYPE_WEAPON == pItemData->GetType()) - if (CItemData::WEAPON_ARROW == pItemData->GetSubType()) + // PORT: AVA2 quivers occupy the arrow slot; this does not bypass bow checks. + if (CItemData::WEAPON_ARROW == pItemData->GetSubType() || + CItemData::WEAPON_QUIVER == pItemData->GetSubType()) { return true; } diff --git a/tests/ch5/test_runner.py b/tests/ch5/test_runner.py new file mode 100644 index 00000000..1563b2c5 --- /dev/null +++ b/tests/ch5/test_runner.py @@ -0,0 +1,59 @@ +"""Regression checks for the regression orchestrator's evidence semantics.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('xxf_runner', ROOT / 'scripts/test_xxf_all.py') +runner = importlib.util.module_from_spec(spec) +spec.loader.exec_module(runner) + + +class RunnerTests(unittest.TestCase): + def probe(self, text, timeout=5): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / 'probe.py' + path.write_text(text) + return runner.execute(dict(id='probe', path=str(path), stem='probe', cwd=folder, + suite='runner'), Path(folder), timeout) + + def test_assertion_failure_is_failure(self): + self.assertEqual(self.probe('assert False')['status'], 'fail') + + def test_top_level_probe_is_distinguished(self): + result = self.probe('assert 1 + 1 == 2') + self.assertEqual(result['status'], 'pass') + self.assertEqual(result['details']['mode'], 'top_level_script_exit_only') + + def test_skip_is_not_pass(self): + result = self.probe("import unittest\nclass T(unittest.TestCase):\n @unittest.skip('no device')\n def test_a(self):pass\n") + self.assertEqual(result['status'], 'partial') + self.assertEqual(result['details']['skip_reasons'], ['no device']) + + def test_timeout(self): + self.assertEqual(self.probe('import time\ntime.sleep(10)', .1)['status'], 'timeout') + + def test_premature_success_is_unverified(self): + self.assertEqual(self.probe('raise SystemExit(0)')['status'], 'unverified') + + def test_orchestrator_arguments_do_not_leak(self): + self.assertEqual(self.probe('import sys\nassert len(sys.argv)==1')['status'], 'pass') + + def test_missing_reference_is_explicitly_blocked(self): + jobs = runner.discover() + job = next(j for j in jobs if j['path'].endswith('biolog/tests/test_ava2.py')) + with tempfile.TemporaryDirectory() as folder: + self.assertEqual(runner.execute(job, Path(folder), 5)['status'], 'blocked') + + def test_uncovered_and_related_pass_never_grant_release(self): + features = [dict(id=fid, name=fid, status=dict(implementation='pending')) for fid in ['F03', 'F19']] + results = [dict(stem='test_quiver_runtime', id='quiver', status='pass')] + mapped = runner.feature_results(features, results) + self.assertEqual(mapped[0]['local'], 'not_covered') + self.assertEqual(mapped[1]['local'], 'related_tests_pass') + self.assertTrue(all(not f['release_ready'] for f in mapped)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/port/eterpack_pack.cpp b/tests/port/eterpack_pack.cpp index 7c85be1e..603d18ef 100644 --- a/tests/port/eterpack_pack.cpp +++ b/tests/port/eterpack_pack.cpp @@ -2,6 +2,7 @@ // the original locale packs are made: every file COMPRESS (LZO), index LZO + TEA encrypted. // // eterpack_pack +// eterpack_pack --read-client // // Pack names are , lowercased with '/' (inlineConvertPackFilename). // An existing .eix/.epk is replaced. The result is reopened read-only and every file read back @@ -30,6 +31,37 @@ static std::vector read_file(const fs::path& path) int main(int argc, char** argv) { + // PORT: resolve data through the actual runtime Index/key-fallback path. + // Pack-only reads prevent a loose file in the shell cwd from masking a pack. + if (argc > 1 && std::strcmp(argv[1], "--read-client") == 0) + { + if (argc != 5) + { + std::fprintf(stderr, "usage: %s --read-client \n", argv[0]); + return 2; + } + PackSingletons(); + const auto folder = fs::absolute(fs::path(argv[2]) / "pack"); + if (!fs::is_regular_file(folder / "Index") || !PackInitialize(folder.string().c_str())) + return 1; + CMappedFile mapped; + LPCVOID data = nullptr; + if (!CEterPackManager::Instance().GetFromPack(mapped, argv[3], &data)) + { + std::fprintf(stderr, "registered entry unavailable: %s\n", argv[3]); + return 1; + } + // Exclusive creation: a read-only probe must never overwrite user data. + FILE* output = std::fopen(argv[4], "wbx"); + if (!output) + return 1; + const bool written = std::fwrite(data, 1, mapped.Size(), output) == mapped.Size(); + const bool closed = std::fclose(output) == 0; + if (!written || !closed) + return 1; + std::printf("read registered entry %s: %u bytes\n", argv[3], unsigned(mapped.Size())); + return 0; + } if (argc != 4) { std::fprintf(stderr, "usage: %s \n", argv[0]); diff --git a/tests/port/port_login_flow_server.cpp b/tests/port/port_login_flow_server.cpp index dbe264c2..d93a559b 100644 --- a/tests/port/port_login_flow_server.cpp +++ b/tests/port/port_login_flow_server.cpp @@ -942,7 +942,13 @@ bool FakeLoginServer::ServeGame(Connection& c, int index) return c.Send(chat)&&c.Send(cmd.c_str(),cmd.size()+1); }; const std::string r=std::to_string(request); - if(kind=="cap") {if(!reply("MTF1 cap "+r+" 1 63 1700000000"))return Fail(name+": feature cap");} + if(kind=="cap") {if(!reply("MTF1 cap "+r+" 1 "+(std::getenv("MT_TEST_QUIVER")?"2111":"63")+" 1700000000"))return Fail(name+": feature cap");} + else if(kind=="quiver" && std::getenv("MT_TEST_QUIVER")) { + if(!reply("MTF1 begin "+r+" quiver 0 0 0 0 1700000000") || !reply("MTF1 end "+r+" 0"))return Fail(name+": quiver ack"); + std::uint8_t state[6]={219,0,0,0,0,9};std::uint32_t vid=kMainVID; + std::memcpy(state+1,&vid,4); + if(!c.Send(state,sizeof(state)))return Fail(name+": quiver state"); + } else if(kind=="calendar") { if(!reply("MTF1 begin "+r+" calendar 1 0 2 0 1700000000") || !reply("MTF1 event "+r+" 0 1 1 1700000000 1700003600 0 0 1") || @@ -976,6 +982,13 @@ bool FakeLoginServer::ServeGame(Connection& c, int index) if(!reply("MTF1 end "+r+" "+std::to_string(sent)))return Fail(name+": feature end"); } } + else if (std::getenv("MT_TEST_QUIVER") && text.rfind("/quiver_test ",0)==0) { + unsigned type=0; + if(sscanf(text.c_str()+13,"%u",&type)!=1 || (type!=0 && type!=6 && type!=9))return Fail(name+": invalid test quiver"); + std::uint8_t state[6]={219,0,0,0,0,std::uint8_t(type)};std::uint32_t vid=kMainVID; + std::memcpy(state+1,&vid,4); + if(!c.Send(state,sizeof(state)))return Fail(name+": test quiver state"); + } else if (text == "/server_bonuses") { const std::string cmd = "ServerBonuses 200 200 200 200 200 0 200 0"; GCChatHead chat = {HDR_GC_CHAT, static_cast(sizeof(GCChatHead) + cmd.size() + 1), 5, 0, 1}; diff --git a/tests/port/port_login_flow_test.cpp b/tests/port/port_login_flow_test.cpp index f7f4e7aa..1c2c1172 100644 --- a/tests/port/port_login_flow_test.cpp +++ b/tests/port/port_login_flow_test.cpp @@ -445,6 +445,21 @@ int main(int argc, char** argv) CHECK(py("import net\nassert net.IsConnect(), 'disconnected in the game phase'")); // Focused batch-pickup regression avoids unrelated legacy economy wire fixtures. + if (server && std::getenv("MT_TEST_QUIVER")) { + auto type=[] {auto* actor=CPythonCharacterManager::Instance().GetInstancePtr(FakeLoginServer::kMainVID);return actor?int(actor->GetArrowType()):-1;}; + CHECK(pump_until(8,[&] {return type()==9 || failed();})); + CHECK(type()==9 && !failed()); + for (int expected:{6,0,9}) { + CHECK(py("net.SendChatPacket('/quiver_test "+std::to_string(expected)+"')")); + CHECK(pump_until(5,[&] {return type()==expected || failed();})); + CHECK(type()==expected && !failed()); + } + CHECK(py("import app\napp.Exit()")); + pump_until(2,[] {return !PythonBoot::IsAppLooping();}); + PythonBoot::Stop(); + std::printf("quiver negotiated packet fixture: %s\n",g_failures?"FAILED":"PASS"); + return g_failures?1:0; + } if (server && std::getenv("MT_TEST_AUTOHUNT_BATCH")) { CHECK(CPythonPlayer::Instance().NEW_GetMainActorPtr()); CHECK(CPythonCharacterManager::Instance().GetInstancePtr(FakeLoginServer::kMobVID)); diff --git a/tests/wiki/test_ava2_ui.py b/tests/wiki/test_ava2_ui.py index f99524b8..739f180b 100644 --- a/tests/wiki/test_ava2_ui.py +++ b/tests/wiki/test_ava2_ui.py @@ -35,6 +35,9 @@ class CompatTests(unittest.TestCase): m.Window=type('Window',(Window,),{});m.ImageBox=type('Image',(Image,),{}) sys.modules['ui']=m;self.ui=m source=(ROOT/'src/platform/ScriptLib/Ava2UICompatScript.inc').read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0] + # The embedded runtime is Python 2; adapt only its exec statement for this + # Python 3 fixture. Native C++ tests run the unmodified runtime script. + source=source.replace('exec code in dict','exec(code, dict)') exec(source,{}) def tearDown(self): if self.previous is None:sys.modules.pop('ui',None) diff --git a/tests/wiki/test_model_preview.py b/tests/wiki/test_model_preview.py index fe57f559..ee053248 100644 --- a/tests/wiki/test_model_preview.py +++ b/tests/wiki/test_model_preview.py @@ -32,7 +32,7 @@ class Action(Widget): # vnum -> (type, subtype, antiflags) ITEMS={11299:(1,0,0),11499:(1,0,0x08|0x10|0x20),12049:(2,0,0x04|0x10|0x20|0x40),8000:(1,6,0), - 41001:(28,0,0x01),45001:(28,1,0x02),27001:(3,0,0),11259:(2,1,0)} + 41001:(28,0,0x01),45001:(28,1,0x02),27001:(3,0,0),11259:(2,1,0),8001:(1,9,0)} class Targets(object): @@ -64,7 +64,7 @@ class PreviewTests(unittest.TestCase): mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None)) grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None it=mods['item'] - for k,v in dict(ITEM_TYPE_WEAPON=1,ITEM_TYPE_ARMOR=2,ITEM_TYPE_COSTUME=28,WEAPON_ARROW=6,ARMOR_BODY=0, + for k,v in dict(ITEM_TYPE_WEAPON=1,ITEM_TYPE_ARMOR=2,ITEM_TYPE_COSTUME=28,WEAPON_ARROW=6,WEAPON_QUIVER=9,ARMOR_BODY=0, COSTUME_TYPE_BODY=0,COSTUME_TYPE_HAIR=1,ITEM_ANTIFLAG_FEMALE=0x01,ITEM_ANTIFLAG_MALE=0x02, ITEM_ANTIFLAG_WARRIOR=0x04,ITEM_ANTIFLAG_ASSASSIN=0x08,ITEM_ANTIFLAG_SURA=0x10, ITEM_ANTIFLAG_SHAMAN=0x20).items():setattr(it,k,v) @@ -106,7 +106,7 @@ class PreviewTests(unittest.TestCase): self.assertEqual(spec(12049),('armor',[5,1])) # assassin only self.assertEqual(spec(41001),('armor',[0,5,2,7])) # anti-female costume self.assertEqual(spec(45001),('hair',[4,1,6,3])) - for vnum in (8000,27001,11259):self.assertIsNone(spec(vnum)) # arrow, potion, helmet + for vnum in (8000,8001,27001,11259):self.assertIsNone(spec(vnum)) # arrow, quiver, potion, helmet self.assertTrue(self.ns['Previewable']('mob',101));self.assertFalse(self.ns['Previewable']('item',27001)) def test_item_preview_races_and_reset(self): diff --git a/tests/wiki/test_quiver_runtime.py b/tests/wiki/test_quiver_runtime.py new file mode 100644 index 00000000..18f972f2 --- /dev/null +++ b/tests/wiki/test_quiver_runtime.py @@ -0,0 +1,55 @@ +"""Compile the actual client arrow-slot check without invoking the game UI.""" +from pathlib import Path +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class QuiverClientTests(unittest.TestCase): + def test_actual_client_ammunition_gate(self): + text = (ROOT/'src/port/UserInterface/PythonPlayerSkill.cpp').read_text() + body = text[text.index('bool CPythonPlayer::__HasEnoughArrow()'):text.index('bool CPythonPlayer::__HasItem(')] + code = r''' +#include +enum {INVENTORY,c_Equipment_Arrow}; +struct TItemPos{TItemPos(int,int){}}; +struct CItemData{ + enum {ITEM_TYPE_WEAPON=1,WEAPON_ARROW=6,WEAPON_QUIVER=9}; + int type=ITEM_TYPE_WEAPON,subtype=WEAPON_ARROW; + int GetType(){return type;}int GetSubType(){return subtype;} +}; +struct CItemManager{ + CItemData* item=nullptr;static CItemManager& Instance(){static CItemManager m;return m;} + bool GetItemDataPointer(int,CItemData** out){*out=item;return item!=nullptr;} +}; +int errors=0; +#define Py_BuildValue(...) nullptr +void PyCallClassMemberFunc(void*,const char*,void*){++errors;} +struct CPythonPlayer{ + void* m_ppyGameWindow=nullptr; + int GetItemIndex(TItemPos){return 0;}bool __HasEnoughArrow(); +}; +''' + body + r''' +int main(){ + CPythonPlayer player;CItemData item; + assert(!player.__HasEnoughArrow() && errors==1); + CItemManager::Instance().item=&item; + assert(player.__HasEnoughArrow()); + item.subtype=CItemData::WEAPON_QUIVER;assert(player.__HasEnoughArrow()); + item.subtype=2;assert(!player.__HasEnoughArrow()); + item.subtype=CItemData::WEAPON_QUIVER;item.type=3; + assert(!player.__HasEnoughArrow() && errors==3); +} +''' + with tempfile.TemporaryDirectory(prefix='ch5-quiver-client-') as folder: + root = Path(folder) + (root/'probe.cpp').write_text(code) + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined', + str(root/'probe.cpp'),'-o',str(root/'probe')],check=True) + subprocess.run([str(root/'probe')],check=True) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/server/ava2-items/QUIVER.md b/tools/server/ava2-items/QUIVER.md new file mode 100644 index 00000000..cb449cee --- /dev/null +++ b/tools/server/ava2-items/QUIVER.md @@ -0,0 +1,46 @@ +# 限时箭筒候选数据生成 + +这是F19隔离测试数据生成器,不是安装器。只处理79502/79503/79504,79501因客户端/服务端及价格期限冲突排除。 + +先构建工具: + +```sh +cmake --build build/port-gate/macos --target item_proto_patch eterpack_pack -j4 +``` + +从当前注册资源包读取基线,按照用户确认的AVA2重建规则,明确覆盖三个限时型号: + +```sh +python3 tools/server/ava2-items/make_quiver.py \ + --ava ../AVA2 \ + --reader ../metin2-server/src/server/db/src/ProtoReader.cpp \ + --client-root Client \ + --output build/ch5-quiver-candidate-01 \ + --proto-tool build/port-gate/macos/src/port/item_proto_patch \ + --packer build/port-gate/macos/src/port/eterpack_pack \ + --replace-existing-quivers \ + --expected-base-sha256 ea2a000cb33f5c9c94d3668a4e0b7840ada284c190281ac26dbe2ad05d3d402e +``` + +散列绑定本批当前基线;基线改变须重新审查差异,不要直接换成新散列绕过检查。输出目录必须不存在;复跑需使用新的目录名。没有覆盖参数时,现有定义不一致会被拒绝;覆盖只限三个型号,完整数值前后差异进入manifest。 + +生成内容: + +- `items-server.tsv`:三个服务端文本行,GBK中文名称。 +- `items-client.tsv`:匹配的客户端数值行。 +- `quiver.eix/.epk`:`locale/zh`、`locale/newcibn`原型、物品清单与说明,以及私有图标,共7文件;打包后通过客户端读取器逐文件回读。 +- `base-item-proto`、`manifest.json`:冻结的原型基线、实际Index/输入文件散列、两份归档来源散列、覆盖差异、产物散列和未完成门槛。 + +输入原型/清单/说明都通过原生`PackInitialize`和`GetFromPack`读取,支持当前标准/五区密钥回退,不从当前工作目录的松散文件取值。可选`--locale DIR`仅作额外一致性校验,三个文件中任何一个与有效资源不同就失败;不再将解包目录默认当作有效资源。 + +默认转换器仍锁定箭筒;只有专用生成器显式启用三个经过严格校验的限时型号。两份归档字段必须一致,不接受改变价格、期限、穿戴位置、效果或标志的输入。沿用当前四职业转换器,移除暂未启用的`ANTI_WOLFMAN`标志;其余职业/交易/丢弃限制保留。未来启用狼人前必须重新核对该限制,不能复用本批数据直接开放第五职业。 + +本轮接受的重建差异:五区客户端79502的买价字段550000改为AVA2两份服务端原型的0;7/15/30天REAL_TIME不变。0只是归档原型字段,**不是免费出售的授权**;本工具不添加任何商店库存、NPC售卖或物品获得途径。 + +不要直接将本输出安装到生产或优先挂载到正式客户端。仍须匹配的服务端构建、隔离服原型/角色生命周期验证、外观/弹道、Android构建与真机验收。生成器不会修改Client的Index、locale.cfg或包文件,也不会修改数据库、服务器配置或重启进程。 + +测试: + +```sh +python3 -m unittest discover -s tools/server/ava2-items/tests +``` diff --git a/tools/server/ava2-items/make_items.py b/tools/server/ava2-items/make_items.py index 8eddcbef..e01a3160 100644 --- a/tools/server/ava2-items/make_items.py +++ b/tools/server/ava2-items/make_items.py @@ -126,10 +126,33 @@ def names(): for month in range(1,13):result[25149+month]='%d月战令票'%month return result -def convert(cols,E,imported): +QUIVER_DURATIONS={79502:604800,79503:1296000,79504:2592000} + +def validate_quiver(cols,E): + """Only the three unambiguous archived timed variants; never enable 79501.""" + if len(cols)<33:raise ValueError('truncated quiver row') + c=[x.strip() for x in cols[:33]] + v=int(c[0]) + if v not in QUIVER_DURATIONS or c[2:5]!=['ITEM_WEAPON','WEAPON_QUIVER','1']: + raise ValueError('unsupported quiver variant') + if c[14:18]!=['REAL_TIME',str(QUIVER_DURATIONS[v]),'LIMIT_NONE','0']: + raise ValueError('quiver duration differs from verified archive') + if c[7]!='WEAR_ARROW' or c[8]!='NONE' or c[9:14]!=['0']*5: + raise ValueError('quiver wear/price/refine contract differs') + if c[18:24]!=['APPLY_NONE','0']*3 or c[24:33]!=['17','4','0','25','0','0','0','0','0']: + raise ValueError('quiver applies/values differ') + expected={'ANTI_MUSA','ANTI_SURA','ANTI_MUDANG','ANTI_WOLFMAN'} + expected |= {'ANTI_DROP','ANTI_GIVE','ANTI_MYSHOP','ANTI_SAFEBOX'} if v==79502 else {'ANTI_PKDROP'} + if set(tokens(c[5]))!=expected or set(tokens(c[6]))!={'ITEM_STACKABLE','ITEM_SLOW_QUERY'}: + raise ValueError('quiver flags differ') + if E['sub'][E['type'].index('ITEM_WEAPON')].index('WEAPON_QUIVER')!=9: + raise ValueError('quiver runtime subtype must be 9') + +def convert(cols,E,imported,enable_quiver=False): """AVA2 item_proto.txt row (str columns) -> (server row columns, client numeric fields, kept?).""" c=[x.strip() for x in cols[:33]] t,st=c[2],c[3] + if enable_quiver:validate_quiver(cols,E) kept=t in KEEP_TYPES or (t,st) in KEEP_SUBTYPES or ((t,st)==('ITEM_USE','USE_CHANGE_ATTRIBUTE') and any(lo<=int(c[0])<=hi for lo,hi in ENCHANT_KEEP)) or ( (t,st) in (('ITEM_USE','USE_CHANGE_ATTRIBUTE'),('ITEM_USE','USE_ADD_ATTRIBUTE')) and int(c[0]) in PENDANT_SCROLLS) or ( @@ -139,6 +162,7 @@ def convert(cols,E,imported): int(c[0]) in (70002,39063,39064) and (t,st)==('ITEM_USE','USE_SPECIAL')) if t=='ITEM_COSTUME' and st in ('COSTUME_BODY','COSTUME_HAIR') and int(c[0]) in (41119,41120,41121,41122,45005,45006,45057,45058):kept=True if stone_lock_reason(c,E):kept=False + if enable_quiver:kept=True anti=tokens(c[5]);flags=tokens(c[6]) if 'ITEM_STACKABLE' in anti:anti.remove('ITEM_STACKABLE');flags.append('ITEM_STACKABLE') anti=[a for a in dict.fromkeys(anti) if a in E['anti']];flags=[f for f in dict.fromkeys(flags) if f in E['flag']] diff --git a/tools/server/ava2-items/make_quiver.py b/tools/server/ava2-items/make_quiver.py new file mode 100644 index 00000000..630b1613 --- /dev/null +++ b/tools/server/ava2-items/make_quiver.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +"""Build a private, opt-in timed-quiver proto/resource patch; never install it. + +Both archived server configurations must agree. Nonmatching base vnums require +explicit hash-bound reconstruction. 79501 and server/shop files remain untouched. +""" +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import subprocess +import tarfile +import tempfile + +import make_items +import quiver_assets + +IDS=set(make_items.QUIVER_DURATIONS) +MEMBERS=('home/srv1/db/item_proto.txt','home/srv1/share/conf/item_proto.txt') + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def dump_proto(tool,raw): + # Read a frozen snapshot, never a base file another build can rewrite. + with tempfile.TemporaryDirectory(prefix='ch5-quiver-proto-') as folder: + path=Path(folder)/'item_proto';path.write_bytes(raw) + return subprocess.run([str(tool),'--dump',str(path)],capture_output=True,check=True).stdout + + +def selected(raw): + result={} + for line in raw.splitlines(): + c=line.split(b'\t') + if not c[0].strip().isdigit() or int(c[0]) not in IDS:continue + v=int(c[0]) + if v in result:raise ValueError('duplicate quiver row: '+str(v)) + if len(c)<33:raise ValueError('truncated quiver row') + # Source name is replaced with a Chinese display name, never used as a rule. + result[v]=[x.decode('latin1' if i==1 else 'ascii').strip() for i,x in enumerate(c[:33])] + if set(result)!=IDS:raise ValueError('archive must contain all three timed quivers') + return result + + +def merge_text(raw,rows): + output=[] + for line in raw.splitlines(): + key=line.split(b'\t',1)[0] + if not key.isdigit() or int(key) not in IDS:output.append(line) + return b'\n'.join(output+[rows[v] for v in sorted(rows)])+b'\n' + + +def dump_rows(raw): + rows={} + for line in raw.splitlines(): + fields=line.split(b'\t',1)[0].split() + if len(fields)!=31:raise ValueError('invalid proto tool dump') + key=int(fields[0]) + if key in rows:raise ValueError('duplicate proto dump row') + rows[key]=line + return rows + + +def verify_patch(before,after,expected): + before=dump_rows(before);after=dump_rows(after) + if set(after)!=set(before)|IDS:raise ValueError('proto patch changed unexpected IDs') + for v,line in before.items(): + if v not in IDS and after[v]!=line:raise ValueError('unrelated proto changed: '+str(v)) + for v in IDS: + if list(map(int,after[v].split(b'\t',1)[0].split()))!=expected[v]: + raise ValueError('patched client numeric fields differ: '+str(v)) + return len(set(before)-IDS) + + +def validate_base(raw,expected,replace_existing=False,expected_base_sha256=None,base_sha256=None): + if expected_base_sha256 is not None and expected_base_sha256!=base_sha256: + raise ValueError('base proto SHA256 mismatch') + if replace_existing and not expected_base_sha256: + raise ValueError('replacing existing quivers requires expected base SHA256') + conflicts={} + for v,line in dump_rows(raw).items(): + if v in IDS: + fields=list(map(int,line.split(b'\t',1)[0].split())) + if fields!=expected[v]:conflicts[v]={'before':fields,'after':expected[v]} + if conflicts and not replace_existing: + raise ValueError('base client vnum conflicts: '+','.join(map(str,sorted(conflicts)))) + return conflicts + + +def client_inputs(client_root,packer): + config=(client_root/'locale.cfg').read_text().split() + if len(config)!=3 or config[2] not in ('zh','newcibn'): + raise ValueError('only verified zh/newcibn locale targets are supported') + index_hash=digest((client_root/'pack/Index').read_bytes()) + verified={};files={} + with tempfile.TemporaryDirectory(prefix='ch5-quiver-effective-') as folder: + for name in ('item_proto','item_list.txt','itemdesc.txt'): + probe=Path(folder)/name;entry='locale/'+config[2]+'/'+name + subprocess.run([str(packer),'--read-client',str(client_root),entry,str(probe)],check=True,capture_output=True) + files[name]=probe.read_bytes();verified[entry]=digest(files[name]) + if digest((client_root/'pack/Index').read_bytes())!=index_hash: + raise ValueError('client Index changed during generation') + return files,{'files':verified,'index_sha256':index_hash} + + +def build(ava,reader,locale,output,proto_tool,packer,replace_existing=False,expected_base_sha256=None,client_root=None,with_motion_assets=False): + output=output.resolve() + if output.exists():raise ValueError('output must be a new directory') + if client_root is None:raise ValueError('client root required to bind the effective catalogue') + source=ava/'2. Backup SF+SRC and SQL/FILES+SRC.tgz' + with tarfile.open(source,'r:gz') as archive: + sources={name:archive.extractfile(name).read() for name in MEMBERS} + sets=[selected(raw) for raw in sources.values()] + for v in sorted(IDS): + if sets[0][v][:1]+sets[0][v][2:]!=sets[1][v][:1]+sets[1][v][2:]: + raise ValueError('archived quiver rules conflict: '+str(v)) + enums=make_items.enums(reader) + server_rows={};client_rows={};expected={};names={} + for v in sorted(IDS): + name='无限箭筒(%d天)'%(make_items.QUIVER_DURATIONS[v]//86400) + s,c,kept=make_items.convert(sets[0][v],enums,IDS,enable_quiver=True) + assert kept + s[1]=name;names[v]=name + server_rows[v]='\t'.join(s).encode('gbk') + client_rows[v]=('\t'.join(map(str,c))+'\t'+name).encode('gbk') + expected[v]=c + # By default reject replacements. An explicit, hash-bound AVA2 reconstruction + # may replace only these three IDs, recording their complete numeric delta. + files,effective=client_inputs(client_root,packer) + if locale is not None: + for name,raw in files.items(): + if digest((locale/name).read_bytes())!=digest(raw): + raise ValueError('locale source does not match effective client pack: '+name) + base_bytes=files['item_proto'];base_hash=digest(base_bytes) + raw_text={name:files[name] for name in ('item_list.txt','itemdesc.txt')} + dumped=dump_proto(proto_tool,base_bytes) + conflicts=validate_base(dumped,expected,replace_existing,expected_base_sha256,base_hash) + pack_maker=ava/'1. Client DEV/pack_maker' + assets_index=make_items.pack_index(pack_maker) + source_icon='icon/item/79501.tga' + if source_icon not in assets_index or not assets_index[source_icon].is_file(): + raise ValueError('verified quiver icon missing') + motion_files={};motion_records={} + if with_motion_assets: + with tempfile.TemporaryDirectory(prefix='ch5-quiver-motion-') as folder: + def current(path): + probe=Path(folder)/'entry' + if probe.exists():probe.unlink() + result=subprocess.run([str(packer),'--read-client',str(client_root),path,str(probe)],capture_output=True) + return probe.read_bytes() if result.returncode==0 else None + def reference(path): + source=assets_index.get(path) + return source.read_bytes() if source and source.is_file() else None + motion_files,motion_records=quiver_assets.collect(current,reference) + if digest((client_root/'pack/Index').read_bytes())!=effective['index_sha256']: + raise ValueError('client Index changed during motion discovery') + output.mkdir(parents=True,exist_ok=False) + frozen=output/'base-item-proto';frozen.write_bytes(base_bytes) + (output/'items-server.tsv').write_bytes(b'\n'.join(server_rows.values())+b'\n') + (output/'items-client.tsv').write_bytes(b'\n'.join(client_rows.values())+b'\n') + assets=output/'assets' + for name,raw in motion_files.items(): + dest=assets/name;dest.parent.mkdir(parents=True,exist_ok=True);dest.write_bytes(raw) + # Private path: updating three variants must not change 79501's shared icon. + icon='icon/ch5_quiver/79501.tga' + (assets/icon).parent.mkdir(parents=True) + shutil.copy2(assets_index[source_icon],assets/icon) + for code in ('zh','newcibn'): + target=assets/'locale'/code;target.mkdir(parents=True) + subprocess.run([str(proto_tool),str(frozen),str(output/'items-client.tsv'),str(target/'item_proto')],check=True) + after=dump_proto(proto_tool,(target/'item_proto').read_bytes()) + unchanged=verify_patch(dumped,after,expected) + listing={v:('%d\tETC\t%s'%(v,icon)).encode() for v in sorted(IDS)} + descriptions={v:('%d\t%s\t弓手箭槽弹药,射击不消耗数量;获得后按实时期限到期,离线也计时。'% + (v,names[v])).encode('gbk') for v in sorted(IDS)} + (target/'item_list.txt').write_bytes(merge_text(raw_text['item_list.txt'],listing)) + (target/'itemdesc.txt').write_bytes(merge_text(raw_text['itemdesc.txt'],descriptions)) + subprocess.run([str(packer),str(output/'quiver'),str(assets),''],check=True) + report={'version':1,'items':sorted(IDS),'excluded':[79501],'installed':False, + 'verified_unchanged_proto_records':unchanged, + 'source_sha256':{p:digest(raw) for p,raw in sources.items()}, + 'base_proto_sha256':base_hash,'proto_reader_sha256':digest(reader.read_bytes()), + 'effective_client_base':effective, + 'explicit_replacements':conflicts, + 'motion_assets':motion_records, + 'differences':['ANTI_WOLFMAN omitted like existing converter: Wolfman disabled; re-evaluate before enabling fifth job', + 'Chinese names/descriptions; no price/duration invention'], + 'requires':['matched client/server build','verified test-only proto install','live item lifecycle and Android acceptance'], + 'files':{p.relative_to(output).as_posix():digest(p.read_bytes()) for p in sorted(output.rglob('*')) if p.is_file()}} + (output/'manifest.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') + return report + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + for name in ('ava','reader','output','proto_tool','packer'): + parser.add_argument('--'+name.replace('_','-'),type=Path,required=True) + parser.add_argument('--locale',type=Path,help='optional reference folder; every file must equal the effective runtime bytes') + parser.add_argument('--replace-existing-quivers',action='store_true',help='replace only three timed variants using the verified AVA2 rules') + parser.add_argument('--expected-base-sha256',help='required with replacement; must match the exact base proto') + parser.add_argument('--client-root',type=Path,required=True,help='bind proto/list/description to actual registered runtime packs') + parser.add_argument('--with-motion-assets',action='store_true',help='resolve quiver motion/effect closure; stage only files missing from registered packs') + args=parser.parse_args() + result=build(args.ava,args.reader,args.locale,args.output,args.proto_tool.resolve(),args.packer.resolve(), + args.replace_existing_quivers,args.expected_base_sha256,args.client_root,args.with_motion_assets) + print(json.dumps({'items':result['items'],'installed':False,'output':str(args.output)})) + + +if __name__=='__main__':main() diff --git a/tools/server/ava2-items/quiver_assets.py b/tools/server/ava2-items/quiver_assets.py new file mode 100644 index 00000000..93cc0421 --- /dev/null +++ b/tools/server/ava2-items/quiver_assets.py @@ -0,0 +1,40 @@ +"""Resolve quiver motion/effect dependencies without replacing existing artwork.""" +import hashlib +import posixpath +import re + +TEXT_EXTENSIONS=('.msa','.msf','.mse','.mde','.mss') +REFERENCE=re.compile(rb'["\']([^"\'\r\n]+\.(?:msa|msf|mse|mde|mss|gr2|dds|tga|jpg|png|wav|mp3))["\']',re.I) +MOTIONS=('wait.msa','wait_1.msa','walk.msa','run.msa','damage.msa', + 'damage_1.msa','damage_2.msa','damage_3.msa','attack_special.msa') + + +def dependencies(path,raw): + out=[] + for value in REFERENCE.findall(raw): + name=value.decode('ascii').lower().replace('\\','/') + if not name.startswith(('d:/','sound/','icon/')): + name=posixpath.dirname(path)+'/'+name + name=posixpath.normpath(name) + if not name.startswith(('d:/ymir work/','sound/','icon/')): + raise ValueError('invalid quiver dependency: '+name) + out.append(name) + return out + + +def collect(read_current,read_reference,maximum=256): + queue=['d:/ymir work/%s/assassin/bow/%s'%(sex,name) + for sex in ('pc','pc2') for name in MOTIONS] + records={};missing={} + while queue: + path=queue.pop() + if path in records:continue + if len(records)>=maximum:raise ValueError('quiver resource closure exceeds limit') + raw=read_current(path);origin='registered_client' + if raw is None: + raw=read_reference(path);origin='ava2_reference' + if raw is None:raise ValueError('missing quiver dependency: '+path) + missing[path]=raw + records[path]={'origin':origin,'sha256':hashlib.sha256(raw).hexdigest(),'bytes':len(raw)} + if path.endswith(TEXT_EXTENSIONS):queue.extend(dependencies(path,raw)) + return missing,records diff --git a/tools/server/ava2-items/tests/test_quiver.py b/tools/server/ava2-items/tests/test_quiver.py new file mode 100644 index 00000000..f4968e25 --- /dev/null +++ b/tools/server/ava2-items/tests/test_quiver.py @@ -0,0 +1,114 @@ +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +HERE=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(HERE)) +import make_items as m +import make_quiver as q + +READER=HERE.parents[3]/'metin2-server/src/server/db/src/ProtoReader.cpp' +PACKER=HERE.parents[2]/'build/port-gate/macos/src/port/eterpack_pack' + + +def row(v=79502): + anti='ANTI_MUSA | ANTI_SURA | ANTI_MUDANG | ANTI_WOLFMAN' + anti+=' | ANTI_DROP | ANTI_GIVE | ANTI_MYSHOP | ANTI_SAFEBOX' if v==79502 else ' | ANTI_PKDROP' + return [str(v),'original','ITEM_WEAPON','WEAPON_QUIVER','1',anti, + 'ITEM_STACKABLE | ITEM_SLOW_QUERY','WEAR_ARROW','NONE',*(['0']*5), + 'REAL_TIME',str(m.QUIVER_DURATIONS.get(v,0)),'LIMIT_NONE','0', + *(['APPLY_NONE','0']*3),'17','4','0','25','0','0','0','0','0'] + + +class QuiverDataTests(unittest.TestCase): + def setUp(self):self.enums=m.enums(READER) + + def test_default_is_locked_and_opt_in_preserves_both_sides(self): + for v in sorted(q.IDS): + self.assertFalse(m.convert(row(v),self.enums,q.IDS)[2]) + server,client,kept=m.convert(row(v),self.enums,q.IDS,enable_quiver=True) + self.assertTrue(kept) + self.assertEqual(server[2:4],['ITEM_WEAPON','WEAPON_QUIVER']) + self.assertEqual(client[1:3],[1,9]) + self.assertEqual(server[14:18],['REAL_TIME',str(m.QUIVER_DURATIONS[v]),'LIMIT_NONE','0']) + self.assertEqual(client[13:17],[self.enums['limit'].index('REAL_TIME'),m.QUIVER_DURATIONS[v],0,0]) + self.assertEqual(server[7],'WEAR_ARROW') + self.assertEqual(client[6],1<