From 9077aa389a57ccf5e7889c635d4bfea130cde12f Mon Sep 17 00:00:00 2001 From: shenlei Date: Thu, 8 Oct 2026 10:43:01 +0900 Subject: [PATCH] AVA2 client Windows parity passes (gr2 BitKnit2/64-bit, GamePhase handlers, python modules) - gr2: BitKnit2 decompression, 64-bit LE files, compressed curves - net: remaining GamePhase handlers, generated GC packet table - python: event/chat/chr/minimap/guild/quest/messenger/shop-search and other native modules ported against the AVA2 Windows client - render: D3D8 fixed-function lighting in Gr2ModelRenderer, terrain without baked shade; cape/NPC equipment attachment - tests + audits updated; docs/PORT-PLAN.md and WINDOWS-PARITY.md Batch 4 (render pipeline: background.*, app.RenderGame/UpdateGame, camera bindings, main.cpp fake-content removal) is still in progress. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + CMakeLists.txt | 121 +- docs/AVA2-PACKET-CONSTANTS.json | 2 +- docs/AVA2-PYTHON-INTERFACES.json | 612 +-- docs/PORT-PLAN.md | 415 ++ docs/WINDOWS-PARITY-INVENTORY.json | 3554 +---------------- docs/WINDOWS-PARITY.md | 338 +- shared/common/PortPythonPointer.h | 11 +- shared/gr2/CMakeLists.txt | 1 + shared/gr2/README.md | 12 +- shared/gr2/include/gr2/types.h | 5 +- shared/gr2/src/bitknit2.cpp | 256 ++ shared/gr2/src/bitknit2.h | 37 + shared/gr2/src/gr2_anim.cpp | 248 +- shared/gr2/src/gr2_decompress.cpp | 16 +- shared/gr2/src/gr2_file.cpp | 10 +- shared/gr2/src/gr2_mesh.cpp | 12 +- shared/gr2/src/gr2_typetree.cpp | 76 +- shared/gr2/src/internal.h | 19 +- src/ava2_text_file.h | 26 + src/ava2_text_file_loader.h | 127 + src/battlepass_state.h | 18 + src/cube_renewal_state.h | 15 + src/drop_item_state.h | 17 + src/dungeon_info_state.h | 14 + src/eter_base/Random.cpp | 52 + src/eter_base/Random.h | 13 + src/eter_effect/EffectData.cpp | 78 +- src/eter_image/GrpImage.h | 4 +- src/eter_image/GrpImageInstance.cpp | 31 + src/eter_image/GrpImageInstance.h | 6 + src/eter_lib/parser.cpp | 342 ++ src/eter_lib/parser.h | 43 + src/eter_net/Ava2GcPacketTable.inc | 144 + src/eter_net/NetworkActorManager.cpp | 715 +++- src/eter_net/NetworkActorManager.h | 168 +- src/eter_net/Packet.h | 556 ++- src/eter_net/PythonNetworkStream.cpp | 647 ++- src/eter_net/PythonNetworkStream.h | 187 +- src/eter_net/PythonNetworkStreamCommand.cpp | 287 ++ .../PythonNetworkStreamPhaseGameRecv.cpp | 1355 +++++++ src/eter_render/ActorInstance.cpp | 222 +- src/eter_render/ActorInstance.h | 71 +- src/eter_render/EnvironmentData.cpp | 5 + src/eter_render/EnvironmentData.h | 1 + src/eter_render/Gr2ModelRenderer.cpp | 124 +- src/eter_render/Gr2ModelRenderer.h | 21 + src/eter_render/RaceData.cpp | 455 +++ src/eter_render/RaceData.h | 135 + src/eter_render/TerrainHeightmap.cpp | 38 +- src/eter_render/TerrainHeightmap.h | 29 +- src/eter_render/TextTailManager.h | 1 + src/eter_resource/ResourceManager.h | 21 +- src/eter_ui/PythonWindow.cpp | 46 +- src/eter_ui/PythonWindow.h | 20 +- src/eter_ui/PythonWindowManager.cpp | 62 +- src/eter_ui/PythonWindowManager.h | 2 + src/game_type.cpp | 74 + src/game_type.h | 15 + src/guild_state.h | 32 + src/item_proto.h | 8 +- src/item_sound.cpp | 36 + src/item_sound.h | 17 + src/login_client.cpp | 11 +- src/login_client.h | 5 +- src/login_session.cpp | 13 +- src/login_session.h | 10 +- src/main.cpp | 41 +- src/messenger_state.h | 31 + src/nonplayer_data.cpp | 38 + src/nonplayer_data.h | 13 + src/offline_shop_state.h | 30 + src/pet_skill_state.h | 21 + src/player_settings.cpp | 297 ++ src/player_settings.h | 5 + src/python_app.cpp | 183 +- src/python_app.h | 9 + src/python_battlepass.cpp | 51 + src/python_chat.cpp | 1680 ++++++++ src/python_chat.h | 307 ++ src/python_chr.cpp | 1483 +++++++ src/python_cube_renewal.cpp | 44 + src/python_drop_item.cpp | 37 + src/python_dungeon_info.cpp | 51 + src/python_event_manager.cpp | 1466 +++++++ src/python_event_manager.h | 220 + src/python_gameplay_modules.cpp | 1543 +++---- src/python_gameplay_modules.h | 32 +- src/python_guild.cpp | 109 + src/python_messenger.cpp | 68 + src/python_minimap.cpp | 1361 +++++++ src/python_minimap.h | 269 ++ src/python_native_modules.cpp | 1237 ++---- src/python_native_modules.h | 7 +- src/python_net.cpp | 521 ++- src/python_net.h | 2 + src/python_offline_shop.cpp | 92 + src/python_pet_skill.cpp | 62 + src/python_quest.cpp | 65 + src/python_runtime.cpp | 41 + src/python_shop_search.cpp | 55 + src/python_switchbot.cpp | 75 + src/python_system.cpp | 1722 +++++++- src/python_system.h | 271 +- src/python_wiki.cpp | 458 +++ src/python_wiki.h | 13 + src/quest_state.h | 55 + src/shop_search_state.h | 7 + src/skill_description.h | 37 +- src/switchbot_state.h | 13 + tests/ava2_render_3d_test.cpp | 44 +- tests/ava2_window_tree_test.cpp | 2 + tests/battlepass_test.cpp | 75 + tests/chat_test.cpp | 176 + tests/check_completion.py | 15 + tests/chr_test.cpp | 144 + tests/cube_renewal_test.cpp | 50 + tests/drop_item_test.cpp | 63 + tests/dungeon_info_test.cpp | 75 + tests/event_test.cpp | 133 + tests/gr2/animation.cpp | 17 + tests/gr2/loader_errors.cpp | 48 +- tests/guild_test.cpp | 131 + tests/item_data_test.cpp | 57 + tests/item_sound_test.cpp | 94 + tests/itemshop_test.cpp | 62 + tests/login_oracle_test.cpp | 7 + tests/mark_manager_test.cpp | 4 +- tests/messenger_test.cpp | 53 + tests/minimap_test.cpp | 183 + tests/offline_shop_test.cpp | 93 + tests/python_test.cpp | 504 ++- tests/quest_test.cpp | 58 + tests/shop_search_test.cpp | 52 + tests/skill_test.cpp | 114 + tests/speedtree_forest_test.cpp | 12 +- tests/switchbot_test.cpp | 91 + tests/system_setting_test.cpp | 135 + tests/test_rundir.h | 38 + tests/windows_item_oracle_test.cpp | 211 + tools/audit_ava2_packet_constants.py | 2 +- tools/audit_ava2_python_interfaces.py | 21 +- tools/generate_ava2_gc_packet_table.py | 134 + tools/generate_ava2_item_oracle.py | 58 +- tools/make_test_rundir.py | 131 + 145 files changed, 22692 insertions(+), 6584 deletions(-) create mode 100644 shared/gr2/src/bitknit2.cpp create mode 100644 shared/gr2/src/bitknit2.h create mode 100644 src/ava2_text_file.h create mode 100644 src/ava2_text_file_loader.h create mode 100644 src/battlepass_state.h create mode 100644 src/cube_renewal_state.h create mode 100644 src/drop_item_state.h create mode 100644 src/dungeon_info_state.h create mode 100644 src/eter_base/Random.cpp create mode 100644 src/eter_base/Random.h create mode 100644 src/eter_lib/parser.cpp create mode 100644 src/eter_lib/parser.h create mode 100644 src/eter_net/Ava2GcPacketTable.inc create mode 100644 src/eter_net/PythonNetworkStreamCommand.cpp create mode 100644 src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp create mode 100644 src/eter_render/RaceData.cpp create mode 100644 src/eter_render/RaceData.h create mode 100644 src/game_type.cpp create mode 100644 src/game_type.h create mode 100644 src/guild_state.h create mode 100644 src/item_sound.cpp create mode 100644 src/item_sound.h create mode 100644 src/messenger_state.h create mode 100644 src/offline_shop_state.h create mode 100644 src/pet_skill_state.h create mode 100644 src/player_settings.cpp create mode 100644 src/player_settings.h create mode 100644 src/python_battlepass.cpp create mode 100644 src/python_chat.cpp create mode 100644 src/python_chat.h create mode 100644 src/python_chr.cpp create mode 100644 src/python_cube_renewal.cpp create mode 100644 src/python_drop_item.cpp create mode 100644 src/python_dungeon_info.cpp create mode 100644 src/python_event_manager.cpp create mode 100644 src/python_event_manager.h create mode 100644 src/python_guild.cpp create mode 100644 src/python_messenger.cpp create mode 100644 src/python_minimap.cpp create mode 100644 src/python_minimap.h create mode 100644 src/python_offline_shop.cpp create mode 100644 src/python_pet_skill.cpp create mode 100644 src/python_quest.cpp create mode 100644 src/python_shop_search.cpp create mode 100644 src/python_switchbot.cpp create mode 100644 src/python_wiki.cpp create mode 100644 src/python_wiki.h create mode 100644 src/quest_state.h create mode 100644 src/shop_search_state.h create mode 100644 src/switchbot_state.h create mode 100644 tests/battlepass_test.cpp create mode 100644 tests/chat_test.cpp create mode 100644 tests/check_completion.py create mode 100644 tests/chr_test.cpp create mode 100644 tests/cube_renewal_test.cpp create mode 100644 tests/drop_item_test.cpp create mode 100644 tests/dungeon_info_test.cpp create mode 100644 tests/event_test.cpp create mode 100644 tests/guild_test.cpp create mode 100644 tests/item_data_test.cpp create mode 100644 tests/item_sound_test.cpp create mode 100644 tests/itemshop_test.cpp create mode 100644 tests/messenger_test.cpp create mode 100644 tests/minimap_test.cpp create mode 100644 tests/offline_shop_test.cpp create mode 100644 tests/quest_test.cpp create mode 100644 tests/shop_search_test.cpp create mode 100644 tests/skill_test.cpp create mode 100644 tests/switchbot_test.cpp create mode 100644 tests/system_setting_test.cpp create mode 100644 tests/test_rundir.h create mode 100644 tools/generate_ava2_gc_packet_table.py create mode 100644 tools/make_test_rundir.py diff --git a/.gitignore b/.gitignore index 5e386f45..d84d8c05 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ build/ __pycache__/ *.pyc *.pyo +# CPythonSystem runtime option files (Windows writes them next to the client) +metin2.cfg +interface.cfg diff --git a/CMakeLists.txt b/CMakeLists.txt index e264dd09..1f88afa4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -21,7 +21,7 @@ find_package(SDL3 CONFIG REQUIRED) add_library(ava2_transport src/login_client.cpp) target_include_directories(ava2_transport PUBLIC src) target_link_libraries(ava2_transport PUBLIC ava2_protocol Threads::Threads) -add_library(ava2_render src/eter_render/Gr2ModelRenderer.cpp src/eter_render/TerrainHeightmap.cpp src/eter_render/MapObjectManager.cpp src/eter_render/WaterManager.cpp src/eter_render/OrbitCamera.cpp src/eter_render/MinimapManager.cpp src/eter_render/ActorInstance.cpp src/eter_render/FloatingTextManager.cpp src/eter_render/TargetManager.cpp src/eter_render/TextTailManager.cpp src/eter_sound/SoundManager.cpp src/eter_resource/dxt.cpp src/eter_effect/EffectData.cpp src/eter_effect/EffectInstance.cpp src/eter_effect/FlyTrace.cpp src/eter_effect/FlyingManager.cpp src/eter_effect/EffectManager.cpp src/eter_net/NetworkActorManager.cpp src/eter_render/EnvironmentData.cpp src/eter_render/SkyBox.cpp src/eter_render/SpeedTreeRT.cpp src/eter_render/SpeedTreeForest.cpp src/eter_image/MarkManager.cpp src/eter_render/CRenderTarget.cpp shared/common/CRC32.cpp src/eter_image/GrpImageInstance.cpp src/eter_image/GrpDevice.cpp src/eter_resource/texture_decode.cpp) +add_library(ava2_render src/eter_render/Gr2ModelRenderer.cpp src/eter_render/TerrainHeightmap.cpp src/eter_render/MapObjectManager.cpp src/eter_render/WaterManager.cpp src/eter_render/OrbitCamera.cpp src/eter_render/MinimapManager.cpp src/eter_render/ActorInstance.cpp src/eter_render/RaceData.cpp src/eter_render/FloatingTextManager.cpp src/eter_render/TargetManager.cpp src/eter_render/TextTailManager.cpp src/eter_sound/SoundManager.cpp src/eter_resource/dxt.cpp src/eter_effect/EffectData.cpp src/eter_effect/EffectInstance.cpp src/eter_effect/FlyTrace.cpp src/eter_effect/FlyingManager.cpp src/eter_effect/EffectManager.cpp src/eter_net/NetworkActorManager.cpp src/eter_render/EnvironmentData.cpp src/eter_render/SkyBox.cpp src/eter_render/SpeedTreeRT.cpp src/eter_render/SpeedTreeForest.cpp src/eter_image/MarkManager.cpp src/eter_render/CRenderTarget.cpp shared/common/CRC32.cpp src/eter_image/GrpImageInstance.cpp src/eter_image/GrpDevice.cpp src/eter_resource/texture_decode.cpp) target_include_directories(ava2_render PUBLIC src ${CMAKE_CURRENT_SOURCE_DIR} third_party/extern_include) target_link_libraries(ava2_render PUBLIC libgr2 SDL3::SDL3) option(AVA2_EMBED_PYTHON "Build embedded Python 2.7 runtime" ON) @@ -30,19 +30,90 @@ if(AVA2_EMBED_PYTHON) add_library(ava2_lzo STATIC third_party/ava2-lzo/lzo1x_d2.c) target_include_directories(ava2_lzo PUBLIC third_party/ava2-lzo) set_target_properties(ava2_lzo PROPERTIES POSITION_INDEPENDENT_CODE ON) - add_library(ava2_python src/nonplayer_data.cpp src/python_runtime.cpp src/python_net.cpp src/python_dbg.cpp src/python_system.cpp src/python_app.cpp src/python_wndmgr.cpp src/python_gameplay_modules.cpp src/python_ime.cpp src/python_grp.cpp src/python_native_modules.cpp src/eter_ui/PythonWindow.cpp src/eter_ui/PythonWindowManager.cpp src/eter_net/PythonNetworkStream.cpp src/eter_net/PythonExchange.cpp src/eter_net/PythonSafeBox.cpp) + add_library(ava2_python src/python_pet_skill.cpp src/item_sound.cpp src/python_offline_shop.cpp src/python_switchbot.cpp src/python_dungeon_info.cpp src/python_drop_item.cpp src/python_battlepass.cpp src/python_guild.cpp src/python_shop_search.cpp src/python_cube_renewal.cpp src/python_messenger.cpp src/python_quest.cpp src/nonplayer_data.cpp src/python_wiki.cpp src/python_runtime.cpp src/python_net.cpp src/python_dbg.cpp src/python_system.cpp src/python_minimap.cpp src/python_chr.cpp src/python_app.cpp src/player_settings.cpp src/python_wndmgr.cpp src/python_gameplay_modules.cpp src/python_ime.cpp src/python_grp.cpp src/python_native_modules.cpp src/python_event_manager.cpp src/python_chat.cpp src/eter_lib/parser.cpp src/eter_base/Random.cpp src/game_type.cpp src/eter_ui/PythonWindow.cpp src/eter_ui/PythonWindowManager.cpp src/eter_net/PythonNetworkStream.cpp src/eter_net/PythonNetworkStreamCommand.cpp src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp src/eter_net/PythonExchange.cpp src/eter_net/PythonSafeBox.cpp) target_include_directories(ava2_python PUBLIC src ${CMAKE_CURRENT_SOURCE_DIR} third_party/extern_include) - target_link_libraries(ava2_python PUBLIC SDL3::SDL3 mtpython ava2_render PRIVATE ava2_transport ava2_lzo ava2_poly) + target_link_libraries(ava2_python PUBLIC SDL3::SDL3 mtpython ava2_render PRIVATE mt_codepage ava2_transport ava2_lzo ava2_poly) endif() if(NOT WIN32 AND NOT ANDROID) add_executable(ava2_login src/login_cli.cpp) target_link_libraries(ava2_login PRIVATE ava2_protocol) endif() if(BUILD_TESTING AND NOT ANDROID) + # Asset-backed tests resolve original client paths against a client-root style run + # directory (python-root + merged lowercase `ymir work`, bgm, sound, map, mark...) made by + # tools/make_test_rundir.py. Without it they exit 77 and CTest reports them skipped. + set(AVA2_PACK_MAKER_DIR "${CMAKE_SOURCE_DIR}/../AVA2/TEST/1. Client DEV/pack_maker" CACHE PATH "Decoded AVA2 pack_maker tree") + set(AVA2_TEST_RUNDIR "${CMAKE_BINARY_DIR}/test-rundir" CACHE PATH "Run directory from tools/make_test_rundir.py") if(AVA2_EMBED_PYTHON) + find_package(Python3 COMPONENTS Interpreter REQUIRED) add_executable(python_test tests/python_test.cpp) target_link_libraries(python_test PRIVATE ava2_python ava2_lzo ava2_protocol) add_dependencies(python_test mtpython_stdlib) + add_executable(item_data_test tests/item_data_test.cpp) + target_link_libraries(item_data_test PRIVATE ava2_python) + add_dependencies(item_data_test mtpython_stdlib) + add_test(NAME ava2.item_data COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 item resource loading and selected data parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(item_sound_test tests/item_sound_test.cpp) + target_link_libraries(item_sound_test PRIVATE ava2_python) + add_dependencies(item_sound_test mtpython_stdlib) + add_test(NAME ava2.item_sound COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 item sound selection and storage playback parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(offline_shop_test tests/offline_shop_test.cpp) + target_link_libraries(offline_shop_test PRIVATE ava2_python) + add_dependencies(offline_shop_test mtpython_stdlib) + add_test(NAME ava2.offline_shop COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 offline shop state, wire and Python callback parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(itemshop_test tests/itemshop_test.cpp) + target_link_libraries(itemshop_test PRIVATE ava2_python) + add_dependencies(itemshop_test mtpython_stdlib) + add_test(NAME ava2.itemshop COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 itemshop wire and Python callback parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(switchbot_test tests/switchbot_test.cpp) + target_link_libraries(switchbot_test PRIVATE ava2_python) + add_dependencies(switchbot_test mtpython_stdlib) + add_test(NAME ava2.switchbot COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 switchbot state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(dungeon_info_test tests/dungeon_info_test.cpp) + target_link_libraries(dungeon_info_test PRIVATE ava2_python) + add_dependencies(dungeon_info_test mtpython_stdlib) + add_test(NAME ava2.dungeon_info COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 dungeon info state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(drop_item_test tests/drop_item_test.cpp) + target_link_libraries(drop_item_test PRIVATE ava2_python) + add_dependencies(drop_item_test mtpython_stdlib) + add_test(NAME ava2.drop_item COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 drop item state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(battlepass_test tests/battlepass_test.cpp) + target_link_libraries(battlepass_test PRIVATE ava2_python) + add_dependencies(battlepass_test mtpython_stdlib) + add_test(NAME ava2.battlepass COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 battlepass state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(guild_test tests/guild_test.cpp) + target_link_libraries(guild_test PRIVATE ava2_python) + add_dependencies(guild_test mtpython_stdlib) + add_test(NAME ava2.guild COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 guild state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(shop_search_test tests/shop_search_test.cpp) + target_link_libraries(shop_search_test PRIVATE ava2_python) + add_dependencies(shop_search_test mtpython_stdlib) + add_test(NAME ava2.shop_search COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 shop search state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(cube_renewal_test tests/cube_renewal_test.cpp) + target_link_libraries(cube_renewal_test PRIVATE ava2_python) + add_dependencies(cube_renewal_test mtpython_stdlib) + add_test(NAME ava2.cube_renewal COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 cube renewal state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(messenger_test tests/messenger_test.cpp) + target_link_libraries(messenger_test PRIVATE ava2_python) + add_dependencies(messenger_test mtpython_stdlib) + add_test(NAME ava2.messenger COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 messenger state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(quest_test tests/quest_test.cpp) + target_link_libraries(quest_test PRIVATE ava2_python) + add_dependencies(quest_test mtpython_stdlib) + add_test(NAME ava2.quest COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 quest state, wire and Python parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") add_executable(python_view_test tests/python_view_test.cpp) target_link_libraries(python_view_test PRIVATE ava2_python) add_dependencies(python_view_test mtpython_stdlib) @@ -50,7 +121,8 @@ if(BUILD_TESTING AND NOT ANDROID) add_test(NAME ava2.python_view COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/view_fixture.py" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root" "${CMAKE_SOURCE_DIR}/runtime/login_view.py") set_tests_properties(ava2.python_view PROPERTIES TIMEOUT 70) - add_test(NAME ava2.python COMMAND python_test "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_test(NAME ava2.python COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "Embedded Python 2 original AVA2 modules, gameplay constants, networkModule, ui, prototype & chr 3D passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") add_executable(ava2_window_tree_test tests/ava2_window_tree_test.cpp) target_link_libraries(ava2_window_tree_test PRIVATE ava2_python mtpython) add_dependencies(ava2_window_tree_test mtpython_stdlib) @@ -65,7 +137,7 @@ if(BUILD_TESTING AND NOT ANDROID) add_test(NAME ava2.protocol COMMAND protocol_test) add_executable(ava2_render_3d_test tests/ava2_render_3d_test.cpp) target_link_libraries(ava2_render_3d_test PRIVATE ava2_render) - add_test(NAME ava2.render_3d COMMAND ava2_render_3d_test "${CMAKE_SOURCE_DIR}/ymir work/pc/warrior/warrior_assasin1.gr2") + add_test(NAME ava2.render_3d COMMAND ava2_render_3d_test "ymir work/pc/warrior/warrior_assasin1.gr2") add_executable(environment_skybox_test tests/environment_skybox_test.cpp) target_link_libraries(environment_skybox_test PRIVATE ava2_render) add_test(NAME ava2.environment_skybox COMMAND environment_skybox_test) @@ -97,6 +169,39 @@ if(BUILD_TESTING AND NOT ANDROID) target_include_directories(nonplayer_oracle_test PRIVATE "${CMAKE_BINARY_DIR}/generated") target_link_libraries(nonplayer_oracle_test PRIVATE ava2_python) add_test(NAME ava2.nonplayer_oracle COMMAND nonplayer_oracle_test) + if(AVA2_EMBED_PYTHON) + add_executable(event_test tests/event_test.cpp "${ITEM_ORACLE}") + target_include_directories(event_test PRIVATE "${CMAKE_BINARY_DIR}/generated") + target_link_libraries(event_test PRIVATE ava2_python) + add_dependencies(event_test mtpython_stdlib) + add_test(NAME ava2.event COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 event manager and simple lookups parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(chat_test tests/chat_test.cpp) + target_link_libraries(chat_test PRIVATE ava2_python) + add_dependencies(chat_test mtpython_stdlib) + add_test(NAME ava2.chat COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 chat parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(skill_test tests/skill_test.cpp) + target_link_libraries(skill_test PRIVATE ava2_python) + add_dependencies(skill_test mtpython_stdlib) + add_test(NAME ava2.skill COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 skill parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(system_setting_test tests/system_setting_test.cpp) + target_link_libraries(system_setting_test PRIVATE ava2_python) + add_dependencies(system_setting_test mtpython_stdlib) + add_test(NAME ava2.system_setting COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 systemSetting parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(minimap_test tests/minimap_test.cpp) + target_link_libraries(minimap_test PRIVATE ava2_python) + add_dependencies(minimap_test mtpython_stdlib) + add_test(NAME ava2.minimap COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 miniMap parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + add_executable(chr_test tests/chr_test.cpp) + target_link_libraries(chr_test PRIVATE ava2_python) + add_dependencies(chr_test mtpython_stdlib) + add_test(NAME ava2.chr COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/check_completion.py" + "AVA2 chr parity passed" "$" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root") + endif() add_executable(item_proto_oracle_test tests/item_proto_oracle_test.cpp "${ITEM_ORACLE}") target_include_directories(item_proto_oracle_test PRIVATE src "${CMAKE_BINARY_DIR}/generated") target_link_libraries(item_proto_oracle_test PRIVATE ava2_protocol ava2_lzo) @@ -112,6 +217,12 @@ if(BUILD_TESTING AND NOT ANDROID) target_include_directories(login_oracle_test PRIVATE "${CMAKE_BINARY_DIR}/generated") target_link_libraries(login_oracle_test PRIVATE ava2_protocol) add_test(NAME ava2.login_oracle COMMAND login_oracle_test) + foreach(asset_test ava2.python ava2.window_tree ava2.render_3d ava2.mark_manager) + if(TEST ${asset_test}) + set_tests_properties(${asset_test} PROPERTIES SKIP_RETURN_CODE 77 + ENVIRONMENT "AVA2_PACK_MAKER=${AVA2_PACK_MAKER_DIR};AVA2_TEST_RUNDIR=${AVA2_TEST_RUNDIR}") + endif() + endforeach() if(TARGET ava2_login) find_package(Python3 COMPONENTS Interpreter REQUIRED) add_test(NAME ava2.login_loopback COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/login_fixture.py" "$") diff --git a/docs/AVA2-PACKET-CONSTANTS.json b/docs/AVA2-PACKET-CONSTANTS.json index 49cfd60e..4186ec17 100644 --- a/docs/AVA2-PACKET-CONSTANTS.json +++ b/docs/AVA2-PACKET-CONSTANTS.json @@ -1,6 +1,6 @@ { "reference": "upstream/ava2-client/UserInterface/Packet.h preprocessed with AVA2 Windows feature headers", - "checked": 125, + "checked": 229, "mismatches": [], "unmatched": [] } diff --git a/docs/AVA2-PYTHON-INTERFACES.json b/docs/AVA2-PYTHON-INTERFACES.json index 0bc67f56..f2272e0c 100644 --- a/docs/AVA2-PYTHON-INTERFACES.json +++ b/docs/AVA2-PYTHON-INTERFACES.json @@ -1,5 +1,5 @@ { - "basis": "AVA2 Windows active method tables; module constants/signatures/behavior require further audit", + "basis": "AVA2 Windows project-compiled active method tables; module constants/signatures/behavior require further audit", "modules": [ { "module": "ServerStateChecker", @@ -24,7 +24,6 @@ "missing": [], "extra": [], "placeholder": [ - "CloseTextFile", "EnablePerformanceTime", "EnableSpecialCameraMode", "FlashApplication", @@ -43,12 +42,9 @@ "GetImageInfo", "GetInfo", "GetLoad", - "GetRandom", "GetRenderFPS", "GetRenderTime", "GetRotatingDirection", - "GetTextFileLine", - "GetTextFileLineCount", "GetUpdateFPS", "GetUpdateTime", "HideCursor", @@ -67,7 +63,6 @@ "IsWebPageMode", "LoadCameraSetting", "LoadLocaleAddr", - "LoadLocaleData", "MoveWebPage", "MoviePitchCamera", "MovieResetCamera", @@ -77,7 +72,6 @@ "OnLogoOpen", "OnLogoRender", "OnLogoUpdate", - "OpenTextFile", "PitchCamera", "Process", "RenderGame", @@ -109,7 +103,6 @@ "SetSpecularSpeed", "SetTextTailLivingTime", "SetTitle", - "SetTwoHandedWeaponAttSpeedDecreaseValue", "SetVisibleNotice", "ShowCursor", "ShowWebPage", @@ -146,8 +139,6 @@ "GetRenderedGraphicThingInstanceNum", "GetRenderedSplatNum", "GetShadowMapColor", - "GlobalPositionToLocalPosition", - "GlobalPositionToMapInfo", "IsSoftwareTiling", "IsVisiblePart", "RegisterDungeonMapName", @@ -177,171 +168,53 @@ "SetXMasTree", "TextureChange", "Update", - "VisibleGuildArea", - "WarpTest" + "VisibleGuildArea" ] }, + { + "module": "battlepass", + "windows_file": "upstream/ava2-client/UserInterface/PythonBattlePass.cpp", + "port_file": "src/python_battlepass.cpp", + "windows_methods": 8, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "chat", "windows_file": "upstream/ava2-client/UserInterface/PythonChatModule.cpp", - "port_file": "src/python_gameplay_modules.cpp", + "port_file": "src/python_chat.cpp", "windows_methods": 33, "missing": [], "extra": [], - "placeholder": [ - "AppendChat", - "AppendChatWithDelay", - "AppendWhisper", - "ArrangeShowingChat", - "Clear", - "ClearWhisper", - "Close", - "CreateChatSet", - "CreateWhisper", - "DeleteChatSet", - "DisableChatMode", - "DisableCountryMode", - "EnableChatMode", - "EnableCountryMode", - "GetLineCount", - "GetLineStep", - "GetLinkFromHyperlink", - "GetVisibleLineCount", - "IgnoreCharacter", - "InitWhisper", - "IsIgnoreCharacter", - "Render", - "RenderWhisper", - "SetBoardState", - "SetChatColor", - "SetEndPos", - "SetHeight", - "SetPosition", - "SetStep", - "SetWhisperBoxSize", - "SetWhisperPosition", - "ToggleChatMode", - "Update" - ] + "placeholder": [] }, { "module": "chr", "windows_file": "upstream/ava2-client/UserInterface/PythonCharacterModule.cpp", - "port_file": "src/python_gameplay_modules.cpp", + "port_file": "src/python_chr.cpp", "windows_methods": 80, "missing": [], - "extra": [ - "RequestPetName" - ], - "placeholder": [ - "AttachEffectByID", - "AttachEffectByName", - "BlendLoopMotion", - "BlendRotation", - "DeleteInstanceByFade", - "Die", - "DismountHorse", - "FaintTest", - "GetBoundBoxOnlyXY", - "GetGuildID", - "GetInstanceType", - "GetProjectPosition", - "GetRotation", - "GetVirtualNumber", - "IsEnemy", - "IsGameMaster", - "IsNPC", - "IsPartyMember", - "IsStone", - "LookAt", - "MountHorse", - "MoveToDestPosition", - "Pick", - "PickAll", - "PushLoopMotion", - "PushOnceMotion", - "RaceToJob", - "RaceToSex", - "Refresh", - "Render", - "RenderCollision", - "Revive", - "Select", - "SetAddRenderMode", - "SetArmor", - "SetAttackSpeed", - "SetBlendRenderMode", - "SetDirection", - "SetInstanceType", - "SetLoopMotion", - "SetMotionMode", - "SetMoveSpeed", - "SetSash", - "SetVirtualID", - "Unselect", - "WeaponTraceSetTexture", - "WeaponTraceUseAlpha", - "WeaponTraceUseTexture", - "testGetPKData", - "testRestoreRenderMode", - "testSetAddRenderMode", - "testSetAddRenderModeRGB", - "testSetComboType", - "testSetModulateRenderMode", - "testSetModulateRenderModeRGB", - "testSetRideMan", - "testSetSpecularRenderMode", - "testSetSpecularRenderMode2" - ] + "extra": [], + "placeholder": [] }, { "module": "chrmgr", "windows_file": "upstream/ava2-client/UserInterface/PythonCharacterManagerModule.cpp", - "port_file": "src/python_gameplay_modules.cpp", + "port_file": "src/python_chr.cpp", "windows_methods": 37, "missing": [], - "extra": [ - "RegisterMotion" - ], - "placeholder": [ - "AppendShapeSkin", - "CreateRace", - "GetPickedVID", - "GetVIDInfo", - "IsPossibleEmoticon", - "LoadLocalRaceData", - "LoadRaceData", - "RegisterAttachingBoneName", - "RegisterCacheEffect", - "RegisterCacheMotionData", - "RegisterComboAttack", - "RegisterComboAttackNew", - "RegisterEffect", - "RegisterMotionData", - "RegisterMotionMode", - "RegisterNameColor", - "RegisterNormalAttack", - "RegisterPointEffect", - "RegisterRaceName", - "RegisterRaceSrcName", - "RegisterTitleColor", - "RegisterTitleName", - "ReserveComboAttack", - "ReserveComboAttackNew", - "SelectRace", - "SetAffect", - "SetDustGap", - "SetEmoticon", - "SetEmpireNameMode", - "SetHorseDustGap", - "SetMotionRandomWeight", - "SetMovingSpeed", - "SetPathName", - "SetRaceHeight", - "SetShapeModel", - "ShowPointEffect", - "ToggleDirectionLine" - ] + "extra": [], + "placeholder": [] + }, + { + "module": "cube_renewal", + "windows_file": "upstream/ava2-client/UserInterface/PythonCubeRenewal.cpp", + "port_file": "src/python_cube_renewal.cpp", + "windows_methods": 5, + "missing": [], + "extra": [], + "placeholder": [] }, { "module": "dbg", @@ -352,6 +225,24 @@ "extra": [], "placeholder": [] }, + { + "module": "drop_item", + "windows_file": "upstream/ava2-client/UserInterface/PythonDropItem.cpp", + "port_file": "src/python_drop_item.cpp", + "windows_methods": 8, + "missing": [], + "extra": [], + "placeholder": [] + }, + { + "module": "dungeon_info", + "windows_file": "upstream/ava2-client/UserInterface/PythonDungeonInfo.cpp", + "port_file": "src/python_dungeon_info.cpp", + "windows_methods": 12, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "effect", "windows_file": "upstream/ava2-client/UserInterface/PythonEffectModule.cpp", @@ -361,6 +252,15 @@ "extra": [], "placeholder": [] }, + { + "module": "event", + "windows_file": "upstream/ava2-client/UserInterface/PythonEventManagerMoudle.cpp", + "port_file": "src/python_event_manager.cpp", + "windows_methods": 29, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "eventMgr", "windows_file": "upstream/ava2-client/UserInterface/PythonGameEventManagerModule.cpp", @@ -525,6 +425,15 @@ "Update" ] }, + { + "module": "guild", + "windows_file": "upstream/ava2-client/UserInterface/PythonGuild.cpp", + "port_file": "src/python_guild.cpp", + "windows_methods": 34, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "ime", "windows_file": "upstream/ava2-client/UserInterface/PythonIMEModule.cpp", @@ -547,77 +456,50 @@ "IsSealScroll" ], "placeholder": [ - "CanAddToQuickSlotItem", "CreateItem", "DeleteIconInstance", "DeleteItem", - "GetApplyPoint", "GetDropClear", "GetDropInfo", - "GetIBuyItemPrice", - "GetISellItemPrice", "GetIconInstance", "GetItemsByName", "GetRarityMaxValue", "GetRarityPoint", - "GetRefineSet", - "GetSocket", - "GetUseType", "HasDropInfo", - "Is1GoldItem", - "IsAntiFlag", - "IsDetachScroll", - "IsEquipmentVID", - "IsFlag", - "IsKey", - "IsMetin", "IsRarityItem", - "IsRefineScroll", - "IsWearableFlag", - "LoadItemTable", "Pick", "Render", - "SelectItemWiki", - "SetDropSoundFileName", - "SetUseSoundFileName", "Update" ] }, + { + "module": "managerBankLogs", + "windows_file": "upstream/ava2-client/UserInterface/PythonManagerBank.cpp", + "port_file": "src/python_native_modules.cpp", + "windows_methods": 1, + "missing": [], + "extra": [], + "placeholder": [ + "Append" + ] + }, + { + "module": "messenger", + "windows_file": "upstream/ava2-client/UserInterface/PythonMessenger.cpp", + "port_file": "src/python_messenger.cpp", + "windows_methods": 5, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "miniMap", "windows_file": "upstream/ava2-client/UserInterface/PythonMiniMapModule.cpp", - "port_file": "src/python_native_modules.cpp", + "port_file": "src/python_minimap.cpp", "windows_methods": 27, "missing": [], - "extra": [ - "RegisterColor" - ], - "placeholder": [ - "AddWayPoint", - "Create", - "Destroy", - "GetGuildAreaID", - "Hide", - "HideAtlas", - "IsAtlas", - "LoadAtlas", - "RegisterAtlasWindow", - "RemoveWayPoint", - "Render", - "RenderAtlas", - "ScaleDown", - "ScaleUp", - "SetCenterPosition", - "SetMiniMapSize", - "SetScale", - "Show", - "ShowAtlas", - "UnregisterAtlasWindow", - "Update", - "UpdateAtlas", - "isShow", - "isShowAtlas" - ] + "extra": [], + "placeholder": [] }, { "module": "net", @@ -648,62 +530,22 @@ "ConnectTCP", "ConnectUDP", "DisconnectUploader", - "EnableChatInsultFilter", "ExitApplication", "ExitGame", "GetBettingGuildWarValue", - "GetGuildID", - "GetPreservedServerCommand", "GetServerInfo", - "IsChatInsultIn", - "IsInsultIn", "IsTest", - "LoadInsultList", "LogOutGame", "OpenCatchKing", - "PreserveServerCommand", "RecvGuildSymbol", - "RegisterEmoticonString", "RegisterErrorLog", "Send67AttrClosePacket", "Send67AttrPacket", "SendAddOfflineShopItem", - "SendAddTime", - "SendAnswerMakeGuildPacket", "SendChangeNamePacket", "SendChinaMatrixCardPacket", - "SendDestroyOfflineShop", - "SendElkDropPacket", - "SendEmoticon", - "SendExchangeAcceptPacket", - "SendExchangeElkAddPacket", - "SendExchangeExitPacket", - "SendExchangeItemAddPacket", - "SendExchangeItemDelPacket", - "SendExchangeStartPacket", - "SendGetBackItems", - "SendGoldDropPacketNew", - "SendGuildAddMemberPacket", - "SendGuildChangeGradeAuthorityPacket", - "SendGuildChangeGradeNamePacket", - "SendGuildChangeMemberGeneralPacket", - "SendGuildChangeMemberGradePacket", - "SendGuildChargeGSPPacket", - "SendGuildDeleteCommentPacket", - "SendGuildDepositMoneyPacket", - "SendGuildInviteAnswerPacket", - "SendGuildOfferPacket", - "SendGuildPostCommentPacket", - "SendGuildRefreshCommentsPacket", - "SendGuildRemoveMemberPacket", "SendGuildSymbol", - "SendGuildUseSkillPacket", - "SendGuildWithdrawMoneyPacket", "SendLoginPacket", - "SendMallCheckoutPacket", - "SendMessengerAddByNamePacket", - "SendMessengerAddByVIDPacket", - "SendMessengerRemovePacket", "SendMiniGameCatchKingDeckCardClick", "SendMiniGameCatchKingFieldCardClick", "SendMiniGameCatchKingReward", @@ -711,46 +553,13 @@ "SendMobileMessagePacket", "SendNEWCIBNPasspodAnswerPacket", "SendOfflineShopButton", - "SendOfflineShopBuyPacket", "SendOfflineShopChangeTitle", "SendOfflineShopCheck", - "SendOfflineShopEndPacket", - "SendOfflineShopRemoveLogs", - "SendOpenShopSlot", - "SendOpenWithVID", - "SendPartyExitPacket", - "SendPartyInviteAnswerPacket", - "SendPartyInvitePacket", - "SendPartyParameterPacket", - "SendPartyRemovePacket", - "SendPartyRemovePacketPID", - "SendPartyRemovePacketVID", - "SendPartySetStatePacket", - "SendPartyUseSkillPacket", - "SendPrivateShopSearchInfo", - "SendQuestConfirmPacket", - "SendQuestInputLongStringPacket", - "SendQuestInputStringPacket", - "SendRemoveOfflineShopItem", - "SendRequestRefineInfoPacket", "SendRunupMatrixCardPacket", - "SendSafeboxCheckinPacket", - "SendSafeboxCheckoutPacket", - "SendSafeboxItemMovePacket", - "SendSafeboxSaveMoneyPacket", - "SendSafeboxWithdrawMoneyPacket", "SendSelectEmpirePacket", - "SendSelectItemPacket", - "SendShopBuyPacket", - "SendShopEndPacket", - "SendShopSellPacket", - "SendShopSellPacketNew", "SendTakeOfflineMoney", - "SendTargetInfoLoad", - "SetEmpireLanguageMode", "SetMarkServer", "SetOfflinePhase", - "SetServerCommandParserWindow", "SetServerInfo", "SetSkillGroupFake", "SetTCPRecvBufferSize", @@ -768,32 +577,7 @@ "windows_methods": 24, "missing": [], "extra": [], - "placeholder": [ - "GetEventType", - "GetEventTypeByVID", - "GetGradeByVID", - "GetLevelByVID", - "GetMobGoldMax", - "GetMobGoldMin", - "GetMobRegenCycle", - "GetMobRegenPercent", - "GetMobsByName", - "GetMonsterDX", - "GetMonsterDamage", - "GetMonsterDamageMultiply", - "GetMonsterExp", - "GetMonsterLevel", - "GetMonsterMaxHP", - "GetMonsterName", - "GetMonsterPrice", - "GetMonsterRaceFlag", - "GetMonsterResist", - "GetMonsterST", - "GetRaceNumByVID", - "GetResist", - "IsMonsterStone", - "LoadNonPlayerData" - ] + "placeholder": [] }, { "module": "pack", @@ -804,6 +588,15 @@ "extra": [], "placeholder": [] }, + { + "module": "petskill", + "windows_file": "upstream/ava2-client/UserInterface/PythonSkillPet.cpp", + "port_file": "src/python_pet_skill.cpp", + "windows_methods": 4, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "player", "windows_file": "upstream/ava2-client/UserInterface/PythonPlayerModule.cpp", @@ -819,7 +612,6 @@ "GetItemElementGrade", "GetItemElementType", "GetItemElementValue", - "GetItemRefineInformation", "GetItemSealDate", "GetItemUnSealLeftTime", "GetItemUnbindTime", @@ -828,12 +620,7 @@ ], "placeholder": [ "ActEmotion", - "AffectIndexToSkillIndex", - "CanAttachMetin", "CanAttackInstance", - "CanDetach", - "CanRefine", - "CanUnlock", "ChangeCurrentSkillNumberOnly", "Clear", "ClearSkillDict", @@ -841,66 +628,30 @@ "ComboAttack", "EndKeyWalkingImmediately", "EndMouseWalking", - "ExitParty", "GetAlignmentData", "GetAutoPotionInfo", "GetCharacterDistance", - "GetConquerorEXP", - "GetEXP", "GetEmotionIconImage", "GetEventGame", "GetGem", - "GetGuildID", - "GetGuildName", - "GetISellItemPrice", - "GetItemFlags", "GetItemLink", - "GetItemNewName", "GetItemRandomAttribute", - "GetItemSubTypeBySlot", - "GetItemTypeBySlot", - "GetJob", - "GetKillLOG", "GetMainCharacterPart", "GetMainCharacterShiningPart", "GetMouseFunc", - "GetPKMode", - "GetPartyMemberAffects", - "GetPartyMemberHPPercentage", - "GetPartyMemberState", - "GetPlayTime", - "GetQuickPage", - "GetRace", - "GetSkillCurrentEfficientPercentage", - "GetSkillNextEfficientPercentage", - "GetSkillSlotIndex", "GetTargetVID", - "HasMobilePhoneNumber", "HidePlayer", "IsActingEmotion", - "IsAntiFlagBySlot", "IsAvailableBeltInventoryCell", - "IsCantFightInstance", - "IsChallengeInstance", - "IsDSEquipmentSlot", "IsEquippingBelt", - "IsGameMaster", "IsInSafeArea", "IsMountingHorse", - "IsObserverMode", "IsOpenPrivateShop", "IsPVPInstance", - "IsPartyLeader", - "IsPartyLeaderByPID", - "IsPartyMember", - "IsRevengeInstance", "IsSameEmpire", - "IsSameItemVnum", "IsShiningSlot", "IsSkillActive", - "IsValuableItem", "LoadNewRegen", - "LocalQuickSlotIndexToGlobalQuickSlotIndex", "MoveItem", "OpenCharacterMenu", "PickCloseItem", @@ -908,13 +659,8 @@ "RegisterCacheEffect", "RegisterEffect", "RegisterEmotionIcon", - "RemovePartyMember", - "RemoveQuickSlotByValue", "Render", - "RequestAddToEmptyLocalQuickSlot", - "RequestDeleteGlobalQuickSlot", "RequestFlag", - "RequestMoveGlobalQuickSlotToLocalQuickSlot", "ResetCameraRotation", "SendClickItemPacket", "SendDragonSoulRefine", @@ -922,7 +668,6 @@ "SetAutoCameraRotationSpeed", "SetAutoPotionInfo", "SetEventGame", - "SetGameWindow", "SetItemAttribute", "SetItemCount", "SetItemData", @@ -931,16 +676,12 @@ "SetMouseFunc", "SetMouseMiddleButtonState", "SetMouseState", - "SetPlayTime", "SetQuickCameraMode", - "SetQuickPage", "SetSingleDIKKeyState", "SetTarget", "SetWeaponAttackBonusFlag", "ShowPlayer", - "SlotTypeToInvenType", "StartMouseWalking", - "ToggleCoolTime", "ToggleLevelLimit", "Update", "UseGuildSkill", @@ -958,6 +699,15 @@ "RegisterSkill" ] }, + { + "module": "privateShopSearch", + "windows_file": "upstream/ava2-client/UserInterface/PythonPrivateShopSearch.cpp", + "port_file": "src/python_shop_search.cpp", + "windows_methods": 12, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "profiler", "windows_file": "upstream/ava2-client/UserInterface/PythonProfilerModule.cpp", @@ -970,6 +720,15 @@ "Push" ] }, + { + "module": "quest", + "windows_file": "upstream/ava2-client/UserInterface/PythonQuest.cpp", + "port_file": "src/python_quest.cpp", + "windows_methods": 6, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "renderTarget", "windows_file": "upstream/ava2-client/UserInterface/CPythonRenderTargetModule.cpp", @@ -988,6 +747,59 @@ "SetShining" ] }, + { + "module": "safebox", + "windows_file": "upstream/ava2-client/UserInterface/PythonSafeBox.cpp", + "port_file": "src/python_native_modules.cpp", + "windows_methods": 15, + "missing": [], + "extra": [ + "GetElements", + "GetItemBind", + "GetMallItemBind" + ], + "placeholder": [] + }, + { + "module": "sash", + "windows_file": "upstream/ava2-client/UserInterface/PythonSash.cpp", + "port_file": "src/python_native_modules.cpp", + "windows_methods": 7, + "missing": [], + "extra": [], + "placeholder": [ + "Add", + "GetAttachedItem", + "GetPrice", + "GetResultItem", + "Remove", + "SendCloseRequest", + "SendRefineRequest" + ] + }, + { + "module": "shop", + "windows_file": "upstream/ava2-client/UserInterface/PythonShop.cpp", + "port_file": "src/python_native_modules.cpp", + "windows_methods": 42, + "missing": [], + "extra": [ + "GetItemElements", + "GetOfflineShopItemTransmutation" + ], + "placeholder": [] + }, + { + "module": "skill", + "windows_file": "upstream/ava2-client/UserInterface/PythonSkill.cpp", + "port_file": "src/python_native_modules.cpp", + "windows_methods": 41, + "missing": [], + "extra": [], + "placeholder": [ + "LoadSkillData" + ] + }, { "module": "snd", "windows_file": "upstream/ava2-client/UserInterface/PythonSoundManagerModule.cpp", @@ -997,78 +809,23 @@ "extra": [], "placeholder": [] }, + { + "module": "switchbot", + "windows_file": "upstream/ava2-client/UserInterface/PythonSwitchbot.cpp", + "port_file": "src/python_switchbot.cpp", + "windows_methods": 9, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "systemSetting", "windows_file": "upstream/ava2-client/UserInterface/PythonSystemModule.cpp", "port_file": "src/python_system.cpp", "windows_methods": 73, "missing": [], - "extra": [ - "IsCollectEquipment", - "IsEnabledFastPickup", - "SetCollectEquipment", - "SetFastPickup" - ], - "placeholder": [ - "ApplyConfig", - "DestroyInterfaceHandler", - "GetAffectIcons", - "GetBossTrack", - "GetConfig", - "GetCountryFlag", - "GetCurrentResolution", - "GetDungeonTrack", - "GetEffectLevel", - "GetFOVLevel", - "GetFrequency", - "GetFrequencyCount", - "GetMapObjectDistance", - "GetMountRender", - "GetNightMode", - "GetPetRender", - "GetQuestIconMode", - "GetResolution", - "GetResolutionCount", - "GetShopNameStatus", - "GetShopNamesRange", - "GetStuffMessage", - "GetWindowStatus", - "IsShadow", - "IsShowDamage", - "IsShowMobAIFlag", - "IsShowMobLevel", - "IsShowOutline", - "IsShowSalesText", - "IsSnowTexturesMode", - "IsSoftwareCursor", - "ReserveResource", - "SaveConfig", - "SaveWindowStatus", - "SetAffectIcons", - "SetBossTrack", - "SetConfig", - "SetCountryFlag", - "SetDungeonTrack", - "SetEffectLevel", - "SetFOVLevel", - "SetInterfaceHandler", - "SetMapObjectDistance", - "SetMountRender", - "SetNightMode", - "SetPetRender", - "SetQuestIconMode", - "SetShadow", - "SetShopNameStatus", - "SetShopNamesRange", - "SetShowDamageFlag", - "SetShowMobAIFlag", - "SetShowMobLevel", - "SetShowOutlineFlag", - "SetShowSalesTextFlag", - "SetSnowTexturesMode", - "SetStuffMessage", - "isInterfaceConfig" - ] + "extra": [], + "placeholder": [] }, { "module": "textTail", @@ -1084,6 +841,15 @@ ], "placeholder": [] }, + { + "module": "wiki", + "windows_file": "upstream/ava2-client/UserInterface/PythonWiki.cpp", + "port_file": "src/python_wiki.cpp", + "windows_methods": 22, + "missing": [], + "extra": [], + "placeholder": [] + }, { "module": "wndMgr", "windows_file": "upstream/ava2-client/EterPythonLib/PythonWindowManagerModule.cpp", @@ -1097,5 +863,5 @@ } ], "missing_method_count": 0, - "placeholder_method_count": 749 + "placeholder_method_count": 370 } diff --git a/docs/PORT-PLAN.md b/docs/PORT-PLAN.md index 2caa5de8..d0e55489 100644 --- a/docs/PORT-PLAN.md +++ b/docs/PORT-PLAN.md @@ -308,3 +308,418 @@ Implemented SendOpenShopSlot(sub13)+BYTE position, SendGetBackItems(sub14), Send ### 2026-10-05: offline open by VID Implemented net.SendOpenWithVID with original sub16 and appended DWORD owner after58-byte common header (distinct from purchase's embedded owner). Preserve absence of actor gate and signed Python-to-DWORD conversion; undefined unused original fields zeroed. Regression checks complete62-byte request while actor controlled. macOS/Android arm64 builds and20 nonvisual CTests passed;925 references unchanged. Full offline receive/stock/withdraw/title/UI and broader gameplay alignment remain incomplete. + +### 2026-10-06: net senders and safebox move layout +Fixed safebox item move (11-byte original layout), exchange action gate/default position/ItemDel no-op; implemented exchange, safebox/mall, messenger, party, guild (15 subheaders), quest input/confirm, select item, target info senders with golden-byte tests. Placeholder count 749 → 618. macOS + Android arm64 libmain.so builds passed; 925 references unchanged. Four CTests (python, window_tree, speedtree_forest, mark_manager) fail identically on baseline because asset paths are hardcoded to /Users/shen/... and cwd-relative; see WINDOWS-PARITY.md. Outstanding: configurable asset root, party/guild member state, select-phase empire/name, emoticon, offline-shop stock/withdraw/title, render_3d timeout. + +### 2026-10-06 (pass 2): receive loop, chat/whisper, server commands +- Made the GC receive loop table-driven and generated from the Win32 reference: 138 headers, 119 handlers. + - It now matches Windows for unknown headers (clear and quit), handler failures (clear), loading-only headers in the Game phase (clear), and padding and partial packets. + - The 75 unported GamePhase packets are skipped one packet at a time, so the stream no longer desyncs. +- Ported the chat receive branches, the 31-byte multilanguage whisper, and ServerCommand with SplitToken and the BINARY_ServerCommand_Run/parser window. +- Ported the emoticon registry and send, the "/" command repeat, and the PyCallClassMemberFunc callback semantics. +- Placeholders went from 618 to 609. macOS and Android arm64 builds pass; 925 reference files unchanged; ctest 16/20 with the same 4 environment failures. +- Correction: pass 1's python_test had aborted early. It needs a merged `ymir work` overlay plus `map`/`textureset` symlinks, and it returns rc=0 even on an abort, so check the log for "passed". +- Next: port the 75 GamePhase handlers (motion 36, add/del/update char, item ground, fly, etc.), the chat module, emoticon effects, the insult filter, configurable asset roots, a harness that fails on a Python abort, and the render_3d timeout. + +### 2026-10-06 (pass 3): remaining GamePhase handlers +- Done: 63 of the 75 skipped GamePhase headers are ported, in src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp. This includes: + - handshake/time sync with the Windows stop-frame; + - the unsequenced XTrap ACK; + - party, PVP and duel; + - target and refine; + - quest script/confirm; + - event manager, calendar, sash, kingdoms war, exchange log and catch-king. + - The refresh block now runs in Windows order. Details are in WINDOWS-PARITY.md. +- Still skipped: 47, 74, 75, 81, 93, 114, 156, 171, 217, 220, 221, 230. +- Visual and native-store gaps: minimap/atlas marks, target and specific effects, fly targets, dig/fishing motions, guild land and symbols, hybrid-crypt keys, anticheat blacklist, sash/bank/chest-drop stores, dungeon auto-walk, text-tail refresh, 300 ms refresh throttle. +- Validation: ava2.python passed, with new golden tests. CTest `-E render_3d` 16/20 (same environment failures; render_3d excluded because of its timeout). Android arm64 built. Baseline 925 files unchanged. Packet audit 210/0. + +### 2026-10-06 (pass 4): quest records and task-letter receive path +Ported HEADER_GC_QUEST_INFO (81), the ordered CPythonQuest record store and all six quest Python bindings directly from AVA2 PythonQuest.cpp/.h and RecvQuestInfoPacket. BEGIN replaces/moves an existing wire quest to the end, while quest.Add BEGIN ignores a duplicate; UPDATE creates missing records, preserves empty strings and changes counters/clocks only when flagged; END deletes. Multilanguage `^` titles invoke GetQuestLetterName before RefreshQuest. Signed counters, DWORD Python IDs, array-index getters and unclamped expired countdowns are preserved. GetQuestData uses the existing portable image-handle adapter for the original icon paths. +Added a source-extracted original header/flag compile oracle and an asset-independent native/Python/wire regression. Declared quest payloads shorter than their selected fields are rejected before consuming a following packet; this deliberately bounds an unsafe original trusted-server assumption. Countdown time uses the port's elapsed monotonic application clock; original virtual/frame-timer mode and UI rendering are not verified. +Fixed the ava2.python test harness: process exit 0 alone no longer proves success; both exit status and final completion marker must pass. Confirmed rejection of early exit(0) and nonzero exit even with the marker present. +Validation: macOS and Android arm64 libmain.so builds passed; ava2.quest and ava2.windows_item_oracle passed; existing python_test passed through the completion wrapper in the prepared asset overlay. Both loopback tests passed with permission to bind local fixture ports. Default nonvisual CTests retain four failures: python asset/map assertion, window_tree missing locale resources, mark_manager hardcoded resource path, and speedtree_forest's canopy wind assertion (the last is not an asset lookup failure). render_3d remains unverified. All 925 immutable AVA2 references unchanged; 211 packet constants checked with zero mismatches. +Remaining skipped GamePhase headers:47,74,75,93,114,156,171,217,220,221,230. Static inventories still show hundreds of placeholders; complete gameplay, assets/rendering, real isolated-server and Android-device parity remain unfinished. + +### 2026-10-06 (pass 5): messenger and cube renewal +Ported messenger GC74 and all five original PythonMessenger.cpp bindings. Login/logout/mobile retain friend membership and emit original group0 callbacks; LIST uses connected bit0/bit1 and emits online state before mobile. LOGIN alone refreshes the target board by name. Added the original sorted guild member list/callback operations and RefreshGuildMember (its Guild GC75 producers remain unported). Destroy clears lists while retaining the handler; runtime teardown releases owned references. Invalid Python arguments return None as the original no-message Py_BuildException does. Oversized/truncated wire names are bounded instead of reproducing original stack overwrite/cross-packet reads; INVITE/unknown subheaders preserve the Windows no-op and unconsumed payload behavior. +Ported cube GC221, ordered recipe records and all five PythonCubeRenewal.cpp bindings. Receive appends even duplicate recipe IDs; OPEN goes to the game window, LOADING to the registered cube handler, CLEAR retains the handler. GetDates preserves its16-field tuple, signed values, array indexing and original missing-entry tuple. Craft/close use original CG21610-byte wire layouts and main-actor CanAct guard, with zeroed undefined close fields. Recipe category reads are bounded; wire bool is stored as BYTE and normalized on query rather than reading an invalid C++ bool representation. +Added dedicated messenger/cube native+Python+fragmented-wire tests and source-extracted structure/enum/offset compile checks. macOS and Android arm64 libmain.so builds passed; four targeted CTests (messenger,cube,quest,Windows declaration oracle) passed. Complete nonvisual CTest19/23: same python/window_tree/mark_manager resource failures and speedtree canopy sway failure. The existing comprehensive python_test passes through its completion wrapper in the prepared asset overlay. Packet constants214/0;925 immutable references unchanged; static placeholders789→780 (active *Module.cpp-only interface count remains597, because these original modules live in PythonMessenger.cpp/PythonCubeRenewal.cpp). +Remaining skipped GamePhase headers:47,75,93,114,156,171,217,220,230. Guild receive/store integration, offline/item shop, switchbot, dungeon/drop/battlepass and wider gameplay/rendering/asset/server/device parity remain unfinished. No reference files or existing server changed. + +### 2026-10-06 (pass 6): private shop search and complete extension discovery +Ported GC156 result receive and the12 active PythonPrivateShopSearch.cpp bindings, plus net.SendPrivateShopSearchInfo/CG143. Preserve append order/duplicates until explicit ClearSearchItems; retain original signed DWORD/int results,64-bit prices,8 sockets/15 attributes, seller/position and literal new-name"^" behavior. Removed two exports absent from the active AVA2 feature profile (transmutation/perma). Receive schedules one RefreshShopSearch after a batch, including an empty result packet. Search request serializes89 Win32 bytes in original field order, wraps BYTE parameters and deliberately does not SendSequence; original main actor CanAct guard retained. Zero-fill original undefined text padding; reject text longer than49 bytes and invalid result/socket accesses instead of reproducing original memory faults. +Added an independent literal-wire/native/Python search test and original-source structure/offset compile comparisons. Both platform builds pass; targeted search/cube/messenger/quest/oracle tests5/5 pass. Nonvisual CTest20/24 with the same four python/window_tree/mark_manager asset failures and speedtree sway assertion. Comprehensive python_test passes in the prepared resource overlay via the completion wrapper. Packet constants216/0;925 immutable reference hashes unchanged; static placeholders780→765. +Corrected the interface audit to discover every original .cpp registering Py_InitModule rather than only *Module.cpp. It now covers47 modules,726 overlapping placeholder methods and7 missing guild_ranking methods (Close,CountDate,GetPageCount,GetPageView,InfoDate,Open,SetPageCount). The count increase reflects expanded audit coverage, not newly introduced placeholders. quest/messenger/cube/search now all appear with no missing/extra/placeholder methods. Method-name coverage still does not prove full behavior. +Remaining skipped GamePhase headers47,75,93,114,171,217,220,230. Global refresh timing (including search's500ms delay), original DWORD-size packet/WORD-framing edge cases above65535 bytes, real server/device and full UI rendering remain unverified; broader gameplay/store/asset gaps persist. + +### 2026-10-06 (pass 7): guild state and GC75 +Ported all34 active PythonGuild.cpp methods, replacing31 guild placeholders while retaining the mark manager. GC75 now handles the original login/logout, list/remove, grade/name/authority, info, comments, EXP, skill/general, invitation, name cache, war/point/list and money subheaders. Preserve member grade sorting only on registration, existing name/job retention on updates, integer average, DWORD sums and signed Python results, no aggregate recomputation on removal, insert-first guild names/skill slots, six enemy slots without compaction and callbacks before war-slot changes. Native Destroy intentionally retains board comments, offer sum and skill-slot map; Python Destroy also clears the slot map. A new embedded runtime clears all state. Invalid indices/wire lengths are bounded instead of reproducing Windows memory faults. +Guild list/login/logout/remove now produce the original messenger group1 callbacks and target refreshes. Page refreshes coalesce in Windows order after packet dispatch. Main actor append/update synchronizes net.GetGuildID and the matching account roster; main-member removal clears these. net.SendGuildRemoveMemberPacket now resolves an exact member name to PID and emits the original CG80 removal, retaining the no-send path for unknown names. GVG keys are stored and removed symmetrically; ChangeGVG/RefreshTextTail name-colour effects remain unported and are not claimed as complete guild-war rendering parity. +Corrected interface discovery to use ClCompile entries from the actual AVA2 Windows vcxproj files. guild_ranking is orphan source, absent from that build and without corresponding protocol declarations: the previous missing-interface report was false. Current audit covers46 compiled modules,0 missing names and694 overlapping placeholders; guild has no missing/extra/placeholder names. Static placeholders765→733. Also corrected the prior refresh-throttle gap: AVA2's s_nextRefreshTime guard is commented out, so its300/500ms assignments impose no active delay. Do not introduce an artificial throttle. +Validation: macOS Debug and Android arm64 builds passed; guild/search/cube/messenger/quest/Windows declaration oracle tests6/6 passed. The new guild test checks independent literal packet bytes, fragmented/coalesced packets, malformed-frame boundaries, all receive subheader families, original tuple defaults and state quirks, remove-member sending, account roster synchronization and runtime reset. Source-extracted guild structs/enums/offsets compile against the port. Full nonvisual CTest21/25, with the same four existing failures (python asset/map assertion, window_tree locale resources, mark_manager legacy resource path, speedtree canopy sway). Comprehensive python_test passes through the completion wrapper in the prepared asset overlay after updating its old skipped-GC75 fixture to still-unported GC47; shutdown emits the pre-existing Python __del__ warnings. Packet constants217/0;925 immutable references unchanged. +Remaining skipped GamePhase headers:47,93,114,171,217,220,230. GVG/PK name colours, DWORD-size packet/WORD-framing edge cases above65535 bytes, wider native stores, real-server/device and full asset/rendering parity remain unfinished. No reference files or existing server changed. + +### 2026-10-06 (pass 8): battle pass +Ported all8 active PythonBattlePass.cpp bindings and GC230/CG230 from PythonNetworkStreamPhaseGame.cpp. Keep separate ordered info/progress vectors; INFO and UPDATE append duplicates without replacing by mission ID. CLEAR removes info and resets time but preserves progress; UPDATE_CLEAR removes progress while preserving info/time. INFO_EXTRA sets signed time; LOADING/UPDATE_LOADING forward their original subheader to the registered handler. OPEN/MP call the game window immediately. Unknown subheaders consume the complete58-byte fixed packet with no state change. +Queries preserve original defaults and tuple shapes, including scalar0 for GetDatesItems on a missing record versus pair(0,0) for an invalid reward slot, four reward entries, signed DWORD/Python-int conversions and independent progress indexing. Negative reward slots are safely rejected instead of reproducing original out-of-bounds memory access. Handler references are retained/released across replacement and runtime teardown; list clears keep the handler. Open/reward requests serialize6 little-endian Win32 bytes, use the original main-actor CanAct gate and SendSequence. OPEN's undefined index field is deterministically zeroed; REWARD preserves signed32-bit wrapping. +Validation: macOS Debug and Android arm64 builds passed. Seven targeted battlepass/guild/search/cube/messenger/quest/Windows declaration oracle CTests passed. New battlepass test uses literal wire records and fragmented/coalesced frames, both lists/clear modes, query defaults/signed values, handler lifetime/callback failure, unknown subheaders, exact request bytes/sequence and action guards. Battlepass structs/enums/offsets are compiled against declarations extracted directly from the immutable original. Full nonvisual CTest22/26 with the same four existing failures (python map/assets, window_tree locale assets, mark_manager resource path, speedtree canopy sway); comprehensive Python regression passes in the prepared resource overlay through the completion wrapper. Static placeholders733→725; compiled-interface placeholders694→686, no missing/extra/placeholder names for battlepass. Packet constants219/0;925 immutable reference hashes unchanged. +Remaining skipped GamePhase headers47,93,114,171,217,220. Offline/item shop, switchbot, dungeon info/drop item state, GVG/PK name colours, other native/UI/resource/rendering gaps and real-server/device parity remain unfinished. render_3d is still excluded for its unresolved timeout. No reference files or existing server changed. + +### 2026-10-06 (pass 9): drop item search +Ported all8 PythonDropItem.cpp bindings, GC220 receive and CG215 open/search from AVA2 PythonNetworkStreamPhaseGame.cpp. Replaced7 dummy handlers plus the hidden GetDates no-op (always returned empty data). Preserve ordered append/duplicates, signed DWORD query results, missing-record tuple("None",0,0,0), GetPageView=5, unconstrained signed page selection and ClearList resetting page to1. Server OPEN calls the game window; LOADING calls the registered handler; CLEAR retains that handler. Unknown subheaders consume the full114-byte fixed packet without state changes. Bound100-byte mob names instead of reading past unterminated wire fields. +Open/search requests encode6 little-endian Win32 bytes, preserve integer wrapping, use the original main-actor CanAct gate and SendSequence. The original OPEN vnum is undefined; its four bytes are deterministically zeroed. Python handler references are owned during registration, released on replacement/teardown, and retained across list clears. +Validation: macOS Debug and Android arm64 builds passed. Eight targeted drop/battlepass/guild/search/cube/messenger/quest/Windows declaration oracle CTests passed. New drop test checks literal fragmented/coalesced wire bytes, duplicate records, full-width names, signed values/argument defaults, page/reset semantics, handler lifetime/callback exceptions, unknown subheaders, exact send packets/sequencing/action guards and fresh-runtime reset. Source-extracted drop structs/enums/offsets compile against the port. Full nonvisual CTest23/27, same existing python/map-assets, window_tree/locale, mark_manager/resource-path and speedtree/canopy-sway failures; comprehensive Python regression passes in the prepared asset overlay through the completion wrapper. Static placeholders725→718; compiled-interface placeholders686→679 with no drop_item missing/extra/placeholder names. Packet constants221/0;925 immutable references unchanged. +Remaining skipped GamePhase headers47,93,114,171,217. Offline/item shop, switchbot, dungeon info, GVG/PK name colours, other native/UI/resource/rendering behavior and real-server/device parity remain incomplete. render_3d remains excluded for its unresolved timeout. No reference files or existing server changed. + +### 2026-10-06 (pass 10): dungeon information +Replaced all12 PythonDungeonInfo.cpp implementations, including8 dummy bindings and4 apparently implemented but fabricated functions. Removed the six hardcoded dungeon entries and incompatible11-field query tuple. Dungeon data now comes exclusively from GC217: independent ordered info, mission and ranking vectors; duplicate entries append in wire order. InfoDate reproduces the original21-field tuple and defaults, InfoDateMision its4-int tuple and InfoDateRanking its4-field tuple; fixed100/24-byte strings are bounded. Preserve signed DWORD results, GetPageView=13 and unconstrained signed page count. +Ported all original GC217 branches, game-window OPEN/RANKING_LOAD/MISION_LOAD callbacks and the original mission-send fallthrough that clears ranking. DATES_CLEAR resets page/info/missions but retains rankings; MISION_CLEAR and RANKING_CLEAR affect only their respective vectors. Unknown subheaders consume the complete618-byte fixed packet without changes. Fresh runtime resets all lists. CG213 open/teleport/mission/ranking requests encode6 little-endian Win32 bytes and use the original CanAct gate/SendSequence; OPEN's undefined index bytes are zeroed. +Validation: macOS Debug and Android arm64 builds passed. Nine targeted dungeon/drop/battlepass/guild/search/cube/messenger/quest/Windows declaration oracle CTests passed. New dungeon test uses literal fragmented/coalesced wire fixtures and verifies all receive branches, all21 query fields, clear/fallthrough independence, duplicates, signed/default/page behavior, full-width unterminated strings, callbacks/failures, exact four send packets and action/sequence guards. Source-extracted structures/enums/offsets compile against the port. Full nonvisual CTest24/28 with the same existing python/map-assets, window_tree/locale, mark_manager/resource-path and speedtree/canopy-sway failures; comprehensive Python regression passes in the prepared asset overlay via completion wrapper. Static placeholders718→710; compiled-interface placeholders679→671; dungeon_info has no missing/extra/placeholder names. Packet constants223/0;925 reference hashes unchanged. +Remaining skipped GamePhase headers47,93,114,171. Offline/item shop and switchbot, GVG/PK name colours, other native/UI/resource/rendering gaps and real-server/device parity remain incomplete. render_3d still excluded for unresolved timeout. No reference files or existing server changed. + +### 2026-10-06 (pass 11): switchbot behavior +Replaced all9 previously non-placeholder switchbot implementations with the original PythonSwitchbot.cpp data flow. Removed fabricated common-attribute/max-value tables and client-side Start/Stop state changes. GC171 now updates the complete220-byte table, applies84-byte item updates and builds the ordered server attribute-set map. Keep six native slots and two alternatives/five normal attributes while exposing SLOT_COUNT=5. Server UPDATE alone determines active/finished; wire bool fields are BYTE and normalized on query. ClearSlot clears active/items/alternatives while retaining finished and player item data, as Windows does. +Attribute-set selection comes from the actual SWITCHBOT(window11) player item and item-proto type/subtype, including arrows/unsupported armor rejection, rings, pendant and original costume-to-armor-subtype mapping. Duplicate map entries overwrite after BYTE narrowing of apply_num. Attribute-list values truncate to signed16-bit, while GetAttributeMaxValue retains signed32-bit values. Python slot/alternative/index/type arguments wrap to BYTE, attribute values to signed16-bit. Bound invalid attribute indices and return deterministic-1 when item lookup fails instead of original uninitialized memory behavior. +Item updates retain the existing vnum/flags and all other fields; the packet vnum is ignored as in AVA2. SetItemCount calls the registered player's RefreshInventory immediately before socket/attribute updates; phase-window RefreshSwitchbotItem follows. Preserve all8 sockets/15 attributes. Server callbacks are immediate. Attribute-map receive clears the prior map, consumes9-byte records, and leaves short tails/unknown-subheader payload for the original dispatcher. +CG171 Start/Stop are explicit37/7-byte Win32 packets with SendSequence and no invented action guard; requests do not alter local state. Preserve the original wrapper's >6 boundary: Start(6) sends only a7-byte header declaring37 bytes because native alternatives lookup returns empty; Stop(6) sends7 bytes; larger wrapped slots send nothing. This source quirk is covered, not treated as an invented protocol improvement. +Validation: macOS Debug and Android arm64 builds passed. Ten targeted switchbot/dungeon/drop/battlepass/guild/search/cube/messenger/quest/Windows declaration oracle CTests passed. New switchbot test covers independent literal fragmented/coalesced records, full table/item updates, callback ordering, bool normalization, BYTE/short conversion, clear semantics, sorted map/overwrite/max-value behavior and all supported/rejected item classifications through generated172-byte item-proto fixtures in a temporary isolated pack root. It also checks exact send/sequence/no-actor/state/boundary behavior, malformed table boundaries, unknown/tail dispatch and runtime reset. Original-source structures/enums/offsets compile against the port. Full nonvisual CTest25/29 with the same four existing python/map-assets, window_tree/locale, mark_manager/resource-path and speedtree/canopy-sway failures; comprehensive Python regression passes in the prepared asset overlay.225 packet constants match;925 immutable references unchanged. Static710 and compiled-interface671 placeholders remain unchanged because all old switchbot methods already had non-dummy function bodies; this milestone demonstrates why name/placeholder audits alone cannot prove parity. +Remaining skipped GamePhase headers47,93,114. Offline/item shop, GVG/PK name colours, wider native/UI/resource/rendering gaps and real-server/device parity remain incomplete. DWORD-sized packet framing above65535 bytes and render_3d timeout remain unverified. No reference files or existing server changed. + +### 2026-10-06 (pass 12): item shop GC93 +Ported RecvItemShop from AVA2 PythonNetworkStreamPhaseGame.cpp. GC93 now forwards dragon coins, optional purchase log, complete purchase-history arrays, single-item updates and nested category/subcategory catalogs to the original game-window callbacks. Keep signed32-bit DWORD callback conversion, signed64-bit prices/coins/sales, BYTE discounts, original callback tuple order and original omission of week/month limits from callback arguments. Log arrays are fully read before append callbacks, while HideLoading/LogClear occur before that read. DRAGONCOIN appends its optional log before setting coins. LOAD opens the main page once after each outer category; zero categories do not open it, and sentinel9999 opens it once and returns. Duplicates and empty subcategories are forwarded without an invented native store. +Preserve original BUY/RELOAD/LOG_ADD/unknown-subheader unconsumed payload behavior. Bounds reject negative/oversized counts and truncated fields rather than reproducing large allocations or cross-frame reads; fixed25/21/16-byte log strings are bounded. Wire bool is read as BYTE and normalized. Existing chat-based requests and original Python UI are unchanged; this milestone covers the receive bridge, not full rendered item-shop interaction parity. +Validation: macOS Debug and Android arm64 builds passed. Eleven targeted itemshop/switchbot/dungeon/drop/battlepass/guild/search/cube/messenger/quest/Windows declaration oracle CTests passed. New literal-wire test checks fragmentation/coalescing, every actual receive branch, signed values/64-bit fields, nested duplicate/empty categories, sentinel/zero counts, callback order/failure, full-width strings, unknown payload dispatch and bounded malformed count/record reads. Source-extracted item/log/header structures, field offsets and enums compile against the port. Full nonvisual CTest26/30 with the same four existing python/map-assets, window_tree/locale, mark_manager/resource-path and speedtree/canopy-sway failures; comprehensive Python regression passes in the prepared resource overlay via completion wrapper.226 packet constants match;925 immutable reference hashes unchanged. Static710 and compiled-interface671 placeholder counts unchanged: there is no dedicated native Python itemshop extension in AVA2. +Remaining skipped GamePhase headers47,114: offline shop and special effects. Other consumed-but-incomplete native/UI/rendering/store logic, GVG/PK name colours, resource roots, real-server/device parity, DWORD-size framing above65535 and render_3d timeout remain outstanding. No reference files or existing server changed. + +### 2026-10-06 (pass 13): offline shop +Ported GC47 and 27 original active PythonShop.cpp offline bindings, replacing fixed-value/no-op methods. Original three-tab/80-slot item indexing, vnum-gated lookup, signed DWORD/int returns, 64-bit prices/flags,8 sockets/15 attributes, missing buyer string "None", initial title "NONE" and Clear() resetting offline metadata and stock are retained. START updates state before callbacks, reverses80 log entries and skips zero-price logs; UPDATE appends nonzero logs first then refreshes. Six scalar branches retain direct-read/trailing-payload behavior; CHECK_RESULT accepts only byte1. IsOfflineShop remains0 because AVA2 never sets the flag. END clears ordinary and offline shop state before the original callbacks. Active zodiac lucky-error callback and unknown/error full-payload consumption are preserved. +Implemented stock replace/delete/clear/query, sorting by display position, CG58 build and CG57 decoration. Explicit little-endian53-byte build header/20-byte stock entries and58+52-byte decoration match the source Win32 layouts; no main-actor gate is invented, and existing SendSequence transport behavior is retained. BYTE/WORD conversions and empty-stock requests match AVA2. Undefined original padding/owner_id is zeroed; decoration text is copied literally rather than reproducing the original format-string vulnerability. Fixed text is bounded and malformed/truncated records reject instead of reproducing out-of-bounds reads. +Added independent literal fragmented/coalesced wire/state/Python fixtures and source-extracted Win32 structure/enum/offset assertions. Interface auditor now merges multiple method tables for one module, so extending shop in a separate translation unit does not erase ordinary shop interfaces from the report. The comprehensive Python framing regression now uses the remaining unported GC114 instead of expecting GC47 to be skipped. +Validation: macOS Debug and Android arm64 builds pass;12 targeted regressions pass. Full nonvisual CTest27/31 retains the four previously documented python/map-assets,window_tree/locale,mark_manager/resource-path and speedtree/canopy-sway failures.228 packet constants match;925 immutable reference hashes unchanged. Static placeholders710→683; compiled-interface placeholders671→644;46 original compiled modules compared,0 missing method names. Comprehensive Python regression passes in the prepared resource overlay through the exit-status/completion-marker wrapper. +Remaining skipped GamePhase header114 (special effects); other consumed-but-incomplete handlers/native/UI/rendering/store logic, shop sign rendering, GVG/PK colours, resource roots, isolated-server/device equivalence, DWORD framing above65535 and render_3d timeout remain outstanding. Offline rendered UI/server interaction parity is unverified. No reference files or existing server changed. + +### 2026-10-06 (pass 14): original item sound dependency and equipment request restrictions +Replaced item.SetUseSoundFileName/SetDropSoundFileName no-ops with the original bounded8-use/5-drop category registries. Native selection follows PythonItem.cpp: bow versus arrow/quiver/default weapon, body versus neck/ear/default armor, ability-up potion sound, talisman portal sound; USE_POTION itself has no client-use sound, leaving server-triggered potion playback separate. Missing item definitions stay silent; empty configured strings are retained. Sound lookup does not change ItemManager's selected item. Added PlayUsePotionSound as a native dependency for GC114; GC114 itself remains skipped until full registered character/bone effects are ported. +Restored original pre-send drop sounds for safebox checkin/checkout/move and mall checkout using actual inventory/storage item definitions. Also restored inventory use/move sounds and their missing equipment restrictions: only an equipment item in a source equipment cell triggers exchange/shop notification or attacking rejection, after CanAct and before sound/send. A destination-only move from a normal inventory cell is permitted as the original does. Equipment range is180..215 for INVENTORY/EQUIPMENT; original selection-without-fallback behavior is retained. No sounds were invented for item drop/pickup/use-to-item. Original packet layouts and transport sequence behavior remain unchanged. +Added isolated literal item-proto fixtures covering24 type/subtype combinations, generated PCM WAV fixtures to prove actual SoundManager dispatch/cache population, original Python bad-argument/category bounds and selection-retention tests, storage-invalid-slot suppression, equipment/source-cell boundaries, exchange/shop notifications and CanAct suppression. Original sound enums are extracted into the Win32 compile oracle. No real device/audio-output/attack-animation equivalence is claimed; the attack gate's runtime animation state and shared audio resource resolver remain pending. +Validation: macOS Debug and Android arm64 builds pass;13 targeted regressions pass. Nonvisual CTest28/32 retains the same four prior python/map-assets,window_tree/locale,mark_manager/resource-path and speedtree/canopy-sway failures. Comprehensive Python regression passes in the prepared resource overlay via exit-status/completion-marker wrapper.228 matching protocol constants,925 unchanged references,46 compiled Windows modules/0 missing methods; static683→681 and compiled-interface644→642 placeholder bindings. +Remaining: GC114 and specific/levelup/skillup character effects need registered effect tables, lifetime/attachment/bone transforms and original rendering/invisibility behavior; wider native/gameplay/rendering/resource/server/device parity remains incomplete. Item-proto preset seeds, audio hardcoded resource paths, DWORD framing above65535 and render_3d timeout remain unverified/unresolved. No reference files or existing server changed. + +### 2026-10-07 (pass 15): remove fabricated item database and port resource data loading +Removed seven preset item records, invented names/descriptions/values, lazy hardcoded locale/en item_names/item_list loading, inferred type from item_list's ignored second column and three hardcoded weapon-model fallbacks. An unloaded database is now empty; data arrives through explicit AVA2 item-list/table/description loaders. item.LoadItemTable retains its original None return even on native failure. Selection success is tracked separately from vnum0, so creating a zero-vnum record does not implicitly select it; failed selection retains the previous record/fallback behavior. Native item-data-pointer helpers reject vnum0 as AVA2 does. +Ported active non-Vietnam LoadItemList/LoadItemDesc and prototype icon selection: original tab splitting/quoted tokens/column counts and atoi IDs, list overwrite/model reset/description/socket clearing, description-only updates of existing IDs and quoted string stripping. Prototype load preserves source record order for same-internal-name icon fallback, then decimal-base icon and bowl27995; existing list definitions preserve model/icon/description. ItemProto now retains recent ordered rows, including duplicate IDs, for these source-order semantics. Failed/truncated loads retain prior state; explicit reset safely clears selected/range references rather than reproducing Windows Destroy dangling pointers. +Corrected GetItemSize to(1,proto size), including size0 for list-only records; icon pixels no longer rewrite prototype dimensions. Selected-pointer getters now raise on missing selection; GetIconImageFileName returns the resolved image filename or original "Noname" when no image is available. Image/subimage candidate resolution now includes the configured decoded resource root, and physical loading preserves the logical resource filename; file-existence checks use both mounted and original local-file candidates. The broader pack/encryption/case/encoding/render lifecycle is still incomplete. +Added isolated list/description/literal-proto/TGA fixtures covering an empty database, removal of preset/lazy data, ignored type/name columns, malformed lines, quoted text, missing records/files, original prototype order/icon fallback, description/model/socket retention/reset, selected-state reload and icon-independent sizes. Updated comprehensive Python harness to explicitly execute the original item-list stage before table loading and to expect Noname in its intentional no-icon working-directory case. app.LoadLocaleData itself remains a no-op: integrating the full locale coordinator (item/NPC/skill/pet/insult/scale/wiki lifecycle) is the next required resource step; these native loaders do not establish complete original startup behavior. +Validation: macOS Debug and Android arm64 builds pass;15 targeted regressions pass. Comprehensive Python regression passes in the prepared resource overlay via completion wrapper. Final nonvisual CTest29/33 retains the same four prior python/map-assets,window_tree/locale,mark_manager/resource-path and speedtree/canopy-sway failures.228 matching packet constants.925 immutable reference hashes unchanged;681 static and642 compiled-interface placeholder bindings remain (these repairs fixed hidden mismatches);46 compiled original modules/0 missing method names. No reference files or existing server changed. +Remaining: full locale startup and renderer/resource lookup/lifetimes, GC114/specific/levelup/skillup effects and bone attachments, GVG/PK colours, other native/consumed-handler stores, audio resource paths, isolated-server/device equivalence, DWORD framing above65535 and render_3d timeout. Full client parity remains incomplete. + +### 2026-10-07 (pass 16): app.LoadLocaleData coordinator, insult filter, pet skill/mob/item scale +Replaced the app.LoadLocaleData no-op with the original ::LoadLocaleData (PythonApplication.cpp) sequence and return value (Py_BuildValue "i"): Destroy of NPC/item/skill/pet-skill stores, then item_list (TraceError, continue), item_proto (fail -> 0), itemdesc (continue), mob_proto (fail -> 0), SkillDesc/SkillTable (fail -> 0; original messages print the mob_proto path), pet_skill (fail -> 0), insult.txt (continue), locale/common/npc_wear.txt (continue), mob_scale.txt (fail -> 0) and item_scale.txt (continue). Python callers (localeInfo.LoadLocaleData) ignore the result as on Windows. +Ported CPythonSkillPet (petskill module: SetSkillSlot/GetIconImage/GetSkillbySlot/GetEmptySkill and RegisterSkillPet, including the excluded final line, 6-column rejection, icon path truncation and unknown-type retention; slot index is bounds-checked instead of writing out of range). Ported CInsultChecker + net.LoadInsultList/IsInsultIn/IsChatInsultIn (original inverted enabled check kept) and applied the original '*' filter to received talking/party/guild/shout/whisper text of non-NPC/non-enemy chatters and to VID-less shout text from the colon, so filtered text also reaches the chat log. Ported LoadMobScale (insert-only, kept across Destroy), LoadNPCWear (15-column rows, race<=7, map-name then "all" lookup) and LoadItemScale (job/sex slot, /100 scale, *100 position, MakeItemData for vnum+0..4; JOB_WOLFMAN skipped because ENABLE_WOLFMAN_CHARACTER is off, other unknown jobs skipped where Windows reads an uninitialised slot). +Comprehensive Python harness now starts locale data through app.LoadLocaleData('locale/en') and asserts pet skill/mob scale/item scale/insult results, '*' masking and that a missing locale returns 0 after Destroy; the later redundant direct SkillDesc/SkillTable registration was removed because a second RegisterSkillDesc without Destroy appends duplicate affect rows on Windows too. +Validation: macOS Debug and Android arm64 builds pass. Comprehensive Python regression passes in the prepared resource overlay (completion marker). Nonvisual CTest (`-E render_3d`, render_3d still times out) 29/33 with the same four python/map-assets, window_tree/locale, mark_manager/resource-path and speedtree/canopy-sway failures. 228 packet constants match; 925 immutable reference hashes unchanged; compiled-interface placeholders 642 -> 634; 46 modules/0 missing methods. No reference files or server changed. +Remaining: renderer consumers of NPC wear (InstanceBase NPC equipment/mount/shining) and sash item scale (InstanceBase::SetSash), CPythonWiki::ReadData (refine_table/special_item_group/mob_drop_item), YMIR lang%d.cvt (not used by EUROPE), GC114 special effects, emoticon actor effects, plus the pass-15 list (renderer/resource lifetimes, GVG/PK colours, audio paths, device equivalence, DWORD framing above 65535, render_3d timeout). + +### 2026-10-07 (pass 17): GC114/emoticons, name colours, NPC wear/sash, CPythonWiki, receive back-pressure +GC114 (HEADER_GC_SEPCIAL_EFFECT) is now dispatched with RecvSpecialEffect/RecvSpecificEffect. The CInstanceBase effect table (InstanceBaseEffect.cpp indices under the AVA2 Locale_inc.h set), AttachSpecialEffect/CreateSpecialEffect, actor-root/bone attached effects and the emoticon path (1000 ms m_dwEmoticonTime gate) are ported. A new player_settings table reproduces CPythonPlayerSettingsModule::Load (236 effects, 12 emoticons with CP949 bytes kept, use/drop sounds); it is registered from app.Create. chrmgr.RegisterEffect/RegisterCacheEffect/SetEmoticon/IsPossibleEmoticon are now real. +Name colours: chrmgr.RegisterNameColor/RegisterTitleColor/SetEmpireNameMode are bound. GetNameColorIndex follows PVP/DUEL/GVG keys, party and empire mode. Text tails refresh on PVP, duel, GVG and party events. +NPC wear (LoadNPCWear) is now consumed in AppendActor. The map name comes only from Warp, as on Windows (GetWarpMapName). Non-PC races do not get weapon/hair/sash. SetSash stores m_dwSashEffect (refine effect 251, acc_01.mse) and the item_scale.txt row (scale and scale-position). chr.RaceToJob/RaceToSex replace their dummies. +app.OpenTextFile/GetTextFileLineCount/GetTextFileLine now follow CTextLineLoader, which the introLoading guild-building list needs. +EffectData script parsing now uses atof/atoi semantics instead of the throwing std::stof/stoi, and it reads the 3 extra control-point values of MOVING_TYPE_BEZIER_CURVE. This was found when the Python harness aborted after app.Create. +Added a CPythonWiki port (src/python_wiki.cpp) with a CTextFileLoader/SplitLine2 port (src/ava2_text_file_loader.h) that replaces the fake wiki module: +- Static chest, boss, costume and blacklist tables. +- ReadData: refine_table, item_proto (MIPX v1 stride 176), special_item_group and mob_drop_item, called from LoadLocaleData. +- LoadMonster per mob_proto record, then ListReverse. +- All 22 Python methods, with ScriptLib argument/exception semantics. The Windows IsBlackList argument-order bug is kept. +- A scratch run against the real AVA2 locale/common files matches Windows, including the 255-row group cap. +Game receive buffer: Windows networkmodule.py sets SetTCPRecvBufferSize(128*1024), and CNetworkStream skips recv() while the buffer is full. The port used to fail or throw past 128 KB. Now LoginClient reads only the free space, and PythonNetworkStream takes only RecvBufferSpace() bytes per frame, leaving the rest in the session. That gives TCP back-pressure, as on Windows. +DWORD-size packets (CHESTDROP, EVENT_MANAGER, EXCHANGE_LOG, ITEMSHOP, SHOPSEARCH_SET) are framed by the low WORD in both clients. Their handlers then read the full size and clear the buffer on failure (RecvErrorPacket). The port adds p.size bounds checks where Windows would over-read. +Validation: +- macOS Debug and Android arm64 builds pass. +- The comprehensive Python regression passes, with new GC114, emoticon, name colour, NPC wear, sash, text-file and wiki assertions. +- The login oracle covers partial take_game_input. +- Nonvisual CTest (`-E render_3d`, since render_3d still times out) is 29/33, with the same four environment failures. +- 229 packet constants match (114 added). The 925 reference hashes are unchanged. +- Compiled-interface placeholders went from 634 to 618, with 46 modules and 0 missing methods. +- No reference files or server were changed. +Remaining: +- The full InstanceBase renderer: sash and NPC-wear models are not attached as meshes yet, and item_scale is data only. +- Fly indexed data and the race/motion part of player settings. +- HAIR_COLOR_ENABLE. +- Wiki differences: MIPT item_proto is unsupported; itemDropFrom iterates an unordered_map, so its order differs from MSVC; out-of-range indices return 0 where Windows has UB; a malformed number stops the drop file where Windows would terminate. +- Resource/renderer lifetimes, audio resource paths, isolated-server/device equivalence and the render_3d timeout. + +### 2026-10-07 (pass 18): CRaceManager/.msm race, shape, hair, weapon and sash mounting +Network actors now take their models from the AVA2 race chain instead of the hardcoded `ResolveModelPath`/`GetRaceModelPath`/`GetWeaponModelPath`/`GetHairModelPath` helpers, which were deleted: +- `src/eter_render/RaceData.{h,cpp}` ports CRaceData (RaceDataFile.cpp LoadRaceData: ShapeData/HairData models and SourceSkin/TargetSkin, attaching bones, motion list) and CRaceManager (npclist.txt registry, race resource path search, motlist.txt GENERAL motions). `app.Create` loads `npclist.txt` and the eight player .msm races (with the per-class weapon bones and the sash bone `Bip01 Spine2`). +- ActorInstance gained the CActorInstance part API: SetRace (clears every part; races > 8 register their GENERAL motions), SetShape (shape model or the base model, plus skins), SetHair (PART_HAIR skinned to PART_MAIN, plus skins), AttachWeapon (right/left hand for dagger, bow and fan-while-mounted; a slot that is not re-attached keeps its old model, as on Windows), AttachSash (`Bip01 Spine2`, plays the sash's own motion 0) and the ENABLE_OBJ_SCALLING sash-only scale. Gr2ModelInstance gained skin replacement, detach, animated attachments and per-attachment scale. +- NetworkActorManager follows CInstanceBase::Create: the NPC-wear path does SetArmor → SetWeapon → SetHair → SetSash; otherwise SetArmor, then for PCs SetHair → SetSash → SetWeapon(weapon, arrow). UpdateActor now runs ChangeArmor (rebuilds the race and re-applies the saved hair/sash/weapon), ChangeWeapon, ChangeHair and ChangeSash. Also ported: __ArmorVnumToShape (USE_ARMOR_SPECULAR), the animal-wear and wedding-dress weapon gates, costume GetWeaponType, and `m_awPart`. A sash vnum with no item keeps the previous sash and scale, and a missing item_scale row gives a zero scale (GetItemScale always returns true). +- `app.SetHairColorEnable`/`SetArmorSpecularEnable` now drive HAIR_COLOR_ENABLE/USE_ARMOR_SPECULAR. A new item query (`SetItemDataQuery`) resolves vnum ranges like GetItemDataPointer and supplies the model, type, sub-type, values and bSpecular. +- Weapon-bone effects (PART_WEAPON/PART_WEAPON_LEFT) take the bone name from the race data instead of a hardcoded `equip_right_hand`/`equip_left_hand`. +Validation: +- macOS Debug and Android arm64 builds pass. +- The comprehensive Python regression passes. New pass-18 assertions run against the real root .msm/npclist and the pack trees: + - A warrior with shape 1, hair 1, weapon 10 and sash 1. + - ChangeWeapon(0) and ChangeArmor re-applying the parts. + - An unknown sash keeps the old one. + - A npc_wear row mounting race 0 parts. + - The stray_dog (101) npclist race. + These checks are skipped when warrior_m.msm is absent. +- Nonvisual CTest (`-E render_3d`, since render_3d still times out) is 29/33, with the same four environment failures. +- 229 packet constants match, and the 925 reference hashes are unchanged. Interfaces are 618/46/0 missing. +- No reference files or server were changed. +Deviations and remaining work: +- **BitKnit gr2 blocks real AVA2 meshes.** About 90% of AVA2 pc/item gr2 files use section compression 4 (BitKnit; for example 315 of 349 files in pc/warrior and 282 of 336 in item/weapon). libgr2 cannot decode BitKnit, so the parts are requested correctly but most AVA2 models do not load or draw. The mesh-level skin match (msm SourceSkin against the gr2 texture name) is therefore unverified. A BitKnit decoder, or an offline conversion to uncompressed gr2, is the next renderer blocker. +- A failed SetRace keeps the model-less instance (Windows fails Create), so the name tail and movement keep working. +- Not ported: + - Specular/sphere maps and LOD things. + - Weapon trace and the armor/weapon refine and shining effects. + - The bow motion mode and the percent-random motion pick. + - PC motions (chrmgr.RegisterMotion* is still a dummy). + - __ClearAffects re-attach in ChangeArmor. + - SpeedTree (tree) races and AttachingData collision/effects. +- The chr-module preview (`chr.SelectInstance`/GetRaceModelPath in python_gameplay_modules.cpp) still uses its own path table. + +### 2026-10-07 (pass 19): BitKnit2 gr2 section decompression +Real AVA2 pc/item gr2 now load. The pass-18 blocker ("compression 4 = BitKnit") was mislabeled: AVA2 ships Granny 2.11.8.0, where `granny_compression_type` is 0 None, 1 Oodle0, 2 Oodle1, 3 BitKnit, 4 **BitKnit2** (`AVA2/TEST/3. Source BIN/Extern/include/granny.h`). +- `shared/gr2/src/bitknit2.{h,cpp}` is a new bounds-checked BitKnit2 decoder (fixed-width types, no platform types). Provenance: it re-implements the MIT-licensed BG3ModStudio `LibLS/Bitknit2Decompressor.cpp` (© 2025 Thomas A. Rieck, https://github.com/trieck/BG3ModStudio) and was cross-checked against the BitKnit core of powzix/ooz `bitknit.cpp`. Framing: u16 magic 0x75B1, then 64 KB quanta (u16 0 = stored). Each rANS quantum must end with both states at 0x10000. +- `decompress_section` case 4 decodes into the expanded buffer. Case 3 (BitKnit v1) is reported as not implemented, since it does not appear in the AVA2 corpus. +- BitKnit2 also compresses the fixup metadata (Granny changelog; BG3ModStudio GR2Reader does the same). For Format 4 sections, `build_fixups` reads the u32 compressed size at PointerFixupArrayOffset, decodes `count*12` bytes and indexes those. It now fails the load with stage `fixup` instead of silently ignoring a bad table. Mixed-marshalling fixups are not used by libgr2 and are left undecoded. +Validation: +- Every `*.gr2` under `AVA2/TEST/1. Client DEV/pack_maker` was scanned (scratch tool, not committed): 16725 files, 16569 load. All 6406 BitKnit2 files load, and their 10833 meshes all have in-range indices and finite positions. The 10163 Oodle1 files are unaffected. The 156 failures are the existing "only 32-bit little-endian" header rejection (plechi_* zones/bosses, some pack_2019/patch weapons), not BitKnit. +- `libgr2.loader_errors` gained cases for BitKnit v1, an empty BitKnit2 stream, a stored quantum that decodes, a truncated stored quantum and a compressed fixup table past EOF. +- The pass-18 python_test block now asserts that warrior_novice.gr2 loads with meshes. It also asserts that shape + hair + weapon + sash all draw textured, with the .msm skins applied (`warrior_novice_blue`, `warrior_hair_01_white`, `weapon_chogeup_01`, `Acce_85_001-008`). This closes the pass-18 "skin match unverified" gap. +- macOS Debug and Android arm64 builds pass, and the comprehensive Python regression passes. +- Nonvisual CTest (`-E render_3d`, since render_3d still times out) is 29/33, with the same four environment failures. +- 229 packet constants match, and the 925 reference hashes are unchanged. Interfaces are 618/46/0 missing. +- No reference files or server were changed. +Remaining: +- 64-bit or big-endian Granny files (156 in the pack tree) are still rejected. +- Oodle0 and BitKnit v1 are still unimplemented, with no AVA2 samples. +- render_3d still times out, so there is no on-screen visual check of the BitKnit2 meshes in this pass. + +### 2026-10-07 (pass 20): 64-bit gr2 loading + curve2 animation decoding +All 16725 gr2 in the AVA2 pack tree now load. Compressed Granny 2.11 animation curves now play instead of leaving bones at bind. +- **64-bit Granny.** `File::load` accepts the 64-bit little-endian magic; only big-endian is still rejected (stage `header`, 0 AVA2 samples). Layout follows BG3ModStudio `GR2Reader` (MIT, read only): the header, section table and 12-byte fixups are identical to 32-bit, and only pointer slots inside section data widen to 8 bytes. `File::Impl::ptr` (4/8) drives `type_def_entry_size` (32 → 44 B), the member sizes in `kPtrSlots` (Reference / String / EmptyRef = ptr, RefToArray / ArrayOfRefs = 4+ptr, VariantRef = 2·ptr, RefToVariantArray = 2·ptr+4), the ArrayOfRefs element stride, and the in-member offsets for vertex variant arrays and `extended_i32`. Pointers stay lazily resolved through the fixup map, so nothing is materialised. +- **curve2.** libgr2 used to classify Granny 2.6+ `curve2{VariantRef CurveData}` tracks but decode only Granny 2.4 `OldCurveType`. AVA2 has 3111 32-bit and all 59 64-bit animation files using curve2, about 605k curves in total. `read_curve2` (`shared/gr2/src/gr2_anim.cpp`) decodes 19 `CurveData*` variants into the existing `Curve` (knots plus float controls), covering all 17 that appear in the corpus. Members are looked up by name from the file's own type tree: + - constants: `Da/D3/D4Constant32f` + - float splines and keyframes: `DaK32fC32f`, `DaKeyframes32f` (knot i = i·TimeStep; all 19045 satisfy N−1 = Duration/TimeStep) + - quantised `D3K16u/K8u`, `D3I1*`, `D9I1/I3*`, `DaK16u/K8u`, where knot = k / OneOverKnotScale (the Trunc field holds the high 16 bits of an f32) and control = c·scale + offset + - `D4nK16uC15u` / `D4nK8uC7u`: three stored components with 2-bit swizzle and sign, the fourth = √(1−Σ²), plus the 16-entry scale/offset tables + - `DaIdentity`, and `DaK32fC32f` with zero knots, decode to identity + The formulas and tables follow the MIT LSLib (Norbyte) GR2 curve implementation, rewritten rather than copied. `Curve::eval` degree 0 with more than one knot is now a step (last knot ≤ t), as Granny's SampleBSpline0 does; it was previously a constant at knot 0. +Validation: +- Scratch scanners (not committed) over `AVA2/TEST/1. Client DEV/pack_maker`: + - 16725/16725 gr2 load: 10264 Oodle1 and 6461 BitKnit2, including the 156 64-bit files. + - The 64-bit models have 0 bad meshes, and their worst bind-pose self-check is 5.2e-4. Their 59 animations sample with no NaN. + - curve2 checks: + - No knot runs past Duration. + - D4n quaternions are all unit length; adjacent controls with |dot| < 0.7 are 0.1% (16u) and 0.3% (8u). + - The angle to the bind pose at t=0 (p25/p50/p75) is 0/8.9/28.6° for D4nK16u, 0.7/11.4/30.3° for D4nK8u and 1.5/15/34.4° for float `DaK32fC32f`. A wrong swizzle or table would sit near the random-rotation median of about 126°. + - Positions with bone-length drift > 5% are mostly effect `*_frag_*` pieces and stretchy Maya rigs (shadow_dragon spine/scapula, 10–26%). +- Tests: + - `libgr2.loader_errors` now checks that a 64-bit magic passes the header stage and big-endian still fails there. + - `libgr2.animation` checks degree-0 step sampling. + - The python_test pass-20 block loads `shadow_dragon.gr2` (64-bit) with `run.gr2`. It asserts all 158 D4n tracks decode and `Spine01_jnt` leaves bind and moves over time. +- Builds and regression: + - macOS Debug and Android arm64 builds pass, and the comprehensive Python regression passes. + - Nonvisual CTest (`-E render_3d`) is 29/33, with the same four environment failures. + - The 229 packet constants match, the 925 reference hashes are unchanged, and interfaces are 618/46/0 missing. + - No reference files or server were changed. +Remaining: +- Big-endian Granny, Oodle0 and BitKnit v1 are still unimplemented (0 AVA2 samples). +- B-spline degree ≥ 3 still falls back to quadratic (0 in corpus). +- Keyframe curves step at TimeStep rather than interpolating; Granny's exact keyframe sampling has not been checked against the SDK. +- render_3d still times out, so there is no on-screen check of the newly animated 64-bit bosses. + +### 2026-10-07 (pass 21): render_3d timeout fixed +Cause: `Gr2SceneRenderer::RenderDraw` (software path) had a stray outer `for (t < num_tris)` loop. It wrapped the rasteriser lambdas and the real triangle loop, so every draw rasterised its whole mesh `num_tris` times, which is O(n²). Each 1024×768 frame took 11–26 s (126 s for the whole test, against the 15 s CTest timeout). Opaque draws hid it behind the depth test, but alpha-blended and additive draws were composited `num_tris` times. Removing the loop gives one pass per triangle. The test now takes about 1.8 s, and the renders look correct (warrior, equipment, water/fog). The GPU path (`RenderSceneGPU`) was not affected. +The test was also tied to the original developer's machine: +- `ava2.render_3d` now runs from a client-root style directory given by `AVA2_TEST_RUNDIR` (default `build/dev/test-rundir`). `tools/make_test_rundir.py` builds it from symlinks: the merged lowercase `ymir work` of every pack_maker pack (PC, ETC, root, then the rest; first wins), plus `bgm`, `sound`, `map` and `textureset`. It is generated, ignored by git, and only ever replaces a directory carrying its own marker file. +- The hardcoded `/Users/shen/.../pack_maker` paths are replaced by `AVA2_PACK_MAKER` (CMake cache `AVA2_PACK_MAKER_DIR`, default `../AVA2/TEST/1. Client DEV/pack_maker`). The textureset fallback was also wrong: it pointed at `Maps/textureset`, but the real location is `textureset/textureset`. +- If the model, building, BGM or UI sound is missing from the run directory, the test exits 77 and CTest reports it as skipped. When the assets are present, every original assert runs unchanged. +Validation: +- With the run directory, render_3d passes under the default 15 s timeout (2.3 s). It now uses the real metin2_map_a1 height/tile/attr/textureset, the minimap, building, water and audio data instead of the procedural fallbacks. +- Without the run directory it exits 77. +- Full CTest (render_3d no longer excluded) is 30/34, with the same four environment failures. +- python_test passes, and the macOS and Android arm64 builds pass. +- The 229 packet constants match, the 925 reference hashes are unchanged, and interfaces are 618/46/0. +Remaining: +- The python, window_tree, speedtree_forest and mark_manager tests still hardcode `/Users/shen` or cwd assets and could use the same run directory. +- render_3d does not yet load a 64-bit animated boss. + +### 2026-10-07 (pass 22): the four environment test failures fixed +The last four CTest failures (python, window_tree, speedtree_forest, mark_manager) were test-environment problems, plus one real argument-helper difference from Windows. +- **Run directory follows the pack manifests.** `tools/make_test_rundir.py` now reads every `pack_maker/*_create.xml` and links each `ArchivedPath` (with `d:/` stripped) to its source, so the run directory is the root the Windows pack manager serves (`icon/...`, `locale//...`, `season2/...`, `uiscript/...`, root `*.msm`). The repository's `upstream/python-root` files are linked first and win. After them, packs go PC, ETC, root, then the rest; the first file wins, and names are compared case-insensitively. The loose client-root folders `mark` and `svside`, plus the `map` alias, are linked as directories. The result is 86538 files, about 7 s to build. +- **All asset tests use it.** `tests/test_rundir.h` provides `EnterTestRunDir()` and `PackMaker()`. ava2.python, ava2.window_tree, ava2.render_3d and ava2.mark_manager chdir into `AVA2_TEST_RUNDIR` and exit 77 (CTest skip) when it is missing. The mark fallback reads `$AVA2_PACK_MAKER/../mark/10_0.tga`. +- **speedtree_forest.** The wind-motion test sampled canopy vertex 0, which is the bottom edge of the lowest leaf cluster, where flex (∝ height²) is close to 0. It now samples the highest canopy vertex. The wind code was unchanged. +- **Stale Python errors (code fix).** `PyTuple_GetPointer` (shared/common/PortPythonPointer.h) failed whenever *any* Python error was pending. ScriptLib's `Py_BuildException("...")` sets an error but returns None, for example when `LoadImage` misses a file. So the next wndMgr call on a valid handle returned None, and NewGoldWindow then failed with `None - int`. AVA2 `ScriptLib PyTuple_GetInteger` never looks at the pending error. The helper now saves and restores it with `PyErr_Fetch`/`PyErr_Restore` and judges only its own conversion. +Validation: +- CTest is 34/34, with no exclusions. +- python_test (from the run directory) passes, and the macOS and Android arm64 builds pass. +- The 229 packet constants match (no mismatches), the 925 reference hashes are unchanged, and interfaces are 618/46/0. +Remaining: +- Without the run directory, the four asset tests are skipped rather than run. +- A stale error raised by a missing asset now surfaces at the next Python check, as in the Windows client, instead of silently turning later calls into None. + +### 2026-10-07 (audit): remaining Windows differences ranked by script use +618 compiled-interface placeholder methods remain (46 modules, 0 missing names); 415 of them are called by upstream/python-root scripts. The most-called and most user-visible gaps: +- **chat module (33/33 placeholders).** chat.AppendChat has 229 call sites. The server chat path still goes through `m_chatCallback` in place of CPythonChat, so the Python chat log and whisper windows stay empty. +- **event module (14).** It drives the quest dialog. QuestButtonClick (33 sites) should call `SendScriptButtonPacket`, which already exists. Skip, UpdateEventSet, RenderEventSet, Get/SetVisibleStartLine and IsWait are also no-ops. +- **Simple lookups:** + - item.GetApplyPoint (65 sites): `ApplyTypeToPointType`. + - player.SlotTypeToInvenType (35 sites). + - app.GetRandom (28 sites). + - nonplayer.GetResist. + - The player getters GetTargetVID, GetGuildID, GetPKMode, GetRace, GetEXP, IsGameMaster... +- **Character/motion registration.** chrmgr (29) covers CreateRace, RegisterMotionData and RegisterComboAttack. chr (56) covers SetLoopMotion, SetVirtualID, SetArmor, Refresh and SetInstanceType. +- **systemSetting (58).** It covers config load/save and the display flags. +- **miniMap/atlas (24)** and **skill (21).** +- **Renderer.** In the game phase, main.cpp draws sky, terrain and actors through its own pipeline: app.RenderGame/UpdateGame and background.* are no-ops. Terrain ambient light is also clamped to at least 0.35/0.38, which Windows does not do. +- **Already listed:** GC114/levelup/skillup effects, GVG/PK colours, NPC wear/sash scale consumers, CPythonWiki::ReadData. + +### 2026-10-07 (pass 23): event module and simple lookups (batch 1) +The event module and the simple lookups at the top of the audit list are now ported from the original code. +- **CPythonEventManager + script::Group.** `src/python_event_manager.{h,cpp}` ports UserInterface/PythonEventManager.cpp and PythonEventManagerMoudle.cpp line by line, and `src/eter_lib/parser.{h,cpp}` ports EterLib/parser.cpp. The parser walks characters through the default code page (CharNextExA/CharPrevExA through mt_codepage). + - All 29 original methods are registered, including AddEvent (ENABLE_MULTILANGUAGE_SYSTEM). GetTotalLineCount is not registered, as in the original. + - The constants now match the original: BUTTON_TYPE_NEXT/DONE/CANCEL = 0/1/2. The old placeholder had CANCEL=0 and NEXT=2, which mapped the quest dialog's buttons wrongly. + - The handler and interface objects are held as weak references (or borrowed pointers), so quest dialog `__del__` timing matches Windows. + - main.cpp passes the frame time in through `SetElapsedMillisecond`. + - `PythonRuntime` calls Destroy and clears the interface before `Py_Finalize`. +- **Original quirks kept:** + - UpdateEventSet subtracts the elapsed time twice. + - The CONFIRM_WAIT remaining time uses DWORD arithmetic, so it shows a negative number after it expires. + - LocaleString_Skip does not advance on a single-byte space. + - A `name|` argument with no value reuses the previous value buffer. +- **Methods that crash on Windows return "no set" instead.** Skip, SetVisibleLineCount, Get/SetVisibleStartLine, GetLineCount and GetLineHeight (on an empty line list) read a NULL slot on Windows. +- **Game-phase script packets.** RecvScriptPacket goes through `RegisterEventSetFromString` → `SetVisibleLineCount(30)` → `OnScriptEventStart` (game phase window `OpenQuestWindow(skin,index)`). SelectAnswer and QuestButtonClick send CG_SCRIPT_ANSWER(29) and CG_SCRIPT_BUTTON(66). +- **Lookups:** + - **item.GetApplyPoint.** Uses `src/game_type.cpp` `ApplyTypeToPointType`. The 150 aApplyInfo entries were generated by compiling the original GameType.cpp table under the Locale_inc.h defines. + - **player.SlotTypeToInvenType.** Uses the 19-entry c_aSlotTypeToInvenType table. + - **app.GetRandom.** Uses `src/eter_base/Random.{h,cpp}`, the EterBase Park–Miller generator. random_range takes an unsigned modulo, and swaps the bounds when from > to. It is seeded once at startup. + - **nonplayer.GetResist.** Uses GetMobResist: the signed cResists value, or 0 when the table is missing or resistNum ≥ 11. resistNum is truncated to a BYTE. + - **player getters:** + - GetGuildID, GetGuildName, GetPKMode and IsGameMaster read the main actor and return 0 or "" when there is none. + - GetRace and GetJob use race % 4 (WOLFMAN is off). + - GetEXP and GetConquerorEXP read POINT_EXP (3) and POINT_CONQUEROR_EXP (212) as DWORDs. + - Get/SetPlayTime store CPythonPlayer::m_dwPlayTime. + - Bad arguments return Py_BadArgument (TypeError) or Py_BuildException (None) as in the original. +- **Tests:** + - New ava2.event (`tests/event_test.cpp`) covers: + - Parser commands, arguments and line counts. + - Handler callbacks in order. + - GetLineCount with iAdjustLine. + - WAIT, Skip and IsWait. + - UpdateEventSet timing, including the double subtraction. + - RUN_CINEMA with a missing file. + - The answer and button packets. + - AddEvent → OpenQuestWindow. + - All of the lookups above. nonplayer uses a Windows TMobTable_r235 fixture. + - python_test: the quest dialog section was written against the old placeholder constants. It is corrected to the original values and to the 3-argument InsertTextInline. +Validation: +- CTest is 35/35. +- python_test (from the run directory) passes, and the macOS and Android arm64 builds pass. +- The 229 packet constants match (no mismatches), and the 925 reference hashes are unchanged. +- Interfaces are 46 modules, 0 missing, 590 placeholders (was 618). The parity inventory has 629 placeholder bindings (was 657). +Remaining: +- **player.GetTargetVID is still a placeholder.** The port has no CPythonPlayer target system (SetTarget/ClearTarget/CanPickInstance/target packet), so it goes into a later targeting batch. +- **Some event commands have no effect yet.** The event camera (SET_CAMERA/BLEND_CAMERA/RESTORE_CAMERA) and the minimap atlas signals (ADDMAPSIGNAL/CLEARMAPSIGNAL/SETCMAPPOS) are not available in the port yet. +- **No real fonts.** Event text lines use the port's CGraphicTextInstance, so GetLineHeight and width-based placement do not yet match Windows pixels. +- **Apply types 176–179.** Windows reads past aApplyInfo[150] for these; the port returns POINT_NONE. +- **Race timing.** player.GetRace reads PythonNetworkStream's main actor race. Windows sets m_dwRace when the main actor is appended, so the two can differ for a short time during phase changes. +- **No caller check.** CPythonStackController::CheckStackReference (SelectAnswer anti-cheat caller check) is not ported. + +### 2026-10-07 (pass 24): chat module (batch 2) +The chat module is now ported from the original code; the 33 placeholder chat methods are gone. +- **CPythonChat + CWhisper.** `src/python_chat.{h,cpp}` ports UserInterface/PythonChat.{h,cpp} and PythonChatModule.cpp line by line, using the Locale_inc.h build: __CHAT_SETTINGS__, ENABLE_MULTILANGUAGE_SYSTEM and ENABLE_DICE_SYSTEM are on, LINK_IN_CHAT is off. + - All 33 original methods are registered, in the original order, with the original constants. + - Lines are stored per chat set, in `m_ChatLineNewDeque`, which is keyed by BYTE. Sets 0 and 1 exist from the start. CreateChatSet copies set 0's lines. DeleteChatSet frees that set's lines. + - Each set keeps its own mode and country-mode filters. Each line has three colour slots, indexed by the set id; set ids of 3 and above share slot 0. + - Each store is capped at 300 lines. Lines containing `#ebvs` are dropped. + - `|Hitem::…|h[name]|h` links are renamed to this client's item name. + - SHOUT `|lang|N|` and `|empire|N|` prefixes are stripped, and the flag images are attached through CResourceManager. + - The board modes VIEW (fade after 5 s), EDIT (alpha ramp) and LOG are ported, as are AppendChatWithDelay, whispers (new-line count, InitWhisper → MakeWhisperButton), the ignore set and GetLinkFromHyperlink. + - The CTimer clock is `SetCurrentMillisecond` (0 = real clock). GetGlobalTime is the same clock in seconds. +- **Server chat path.** RecvChatPacket now calls `CPythonChat::AppendChat` directly, for PC chatter lines and VID-0 SHOUTs, as on Windows. The temporary `SetChatCallback` hook is removed. `PythonRuntime` calls `CPythonChat::Destroy` on teardown. +- **Original quirks kept:** + - chat.IsIgnoreCharacter returns None. + - CreateChatSet(256) finds BYTE 0 and returns 256 without creating a set. + - CreateWhisper on an existing name leaves the old whisper in place. + - ArrangeShowingChat counts country-muted SHOUT lines when sizing the window. + - The first visible slot starts at iHeight 12. + - EDIT mode never advances iLineIndex. + - Update on an unknown set returns before it flushes the delayed lines. + - A shout language above 11, or 0, becomes 1. The empire index is not clamped. A `|lang|N` prefix with no closing bar keeps the rest of the string. + - GetLinkFromHyperlink formats htoi's -1 with `%x`. +- **Guards where Windows has undefined behaviour or crashes:** + - A zero step returns 0 or an empty window instead of dividing by zero. + - An out-of-range chat or country mode skips the write, but the set is still rearranged. + - GetLinkFromHyperlink on a link with no ':' returns "" (Windows reads `results[0]` from an empty vector). An odd attribute count uses 0 for the missing value (Windows reads past the end). + - A whisper position above 1.0 is clamped to the last line (Windows asserts, but the assert is compiled out). + - CWhisper::lineCount starts at 0 (uninitialised on Windows when created through chat.CreateWhisper). +- **Tests:** + - New ava2.chat (`tests/chat_test.cpp`, with an item_proto fixture) covers: + - Constants and colours, including SetChatColor. + - Per-set stores, the `#ebvs` drop and item-link renaming. + - SHOUT prefixes, the language clamp and country-mode filtering. + - Mode filtering and toggling. + - The window size and end position, and a zero step. + - The VIEW fade being per set, EDIT/LOG updates, and Close. + - The 300-line cap. + - The delayed-chat flush. + - Create/DeleteChatSet, including the BYTE key. + - The ignore toggle. + - Whispers: line counts, box size, position, InitWhisper and Clear. + - GetLinkFromHyperlink cases. + - Bad arguments returning None. + - python_test's chat-packet section now checks the CPythonChat line store instead of the removed callback. +Validation: +- CTest is 36/36. +- python_test (from the run directory) passes, and the macOS and Android arm64 builds pass. +- The 229 packet constants match (no mismatches), and the 925 reference hashes are unchanged. +- Interfaces are 46 modules, 0 missing, 557 placeholders (was 590). The parity inventory has 596 placeholder bindings (was 629). +Remaining: +- **No real fonts.** + - DefaultFont_GetResource is not checked, so no line is dropped for a missing font. + - GM lines do not get the italic font. + - CWhisper::Render's clip rectangle is not applied by the text stand-in. +- **Flag images.** The flag paths are looked up through CResourceManager without Windows's IsFileExist check, so a missing flag simply leaves the image empty. +- **Not ported:** + - CPythonStackController::CheckStackReference. + - CPythonApplication::ChangeIcon (the ENABLE_DISCORD_STUFF taskbar icon on a new whisper). + - AppendMonsterList (the PythonNetworkStreamCommand.cpp CHAT_TYPE_INFO monster list) and PythonPlayerSkill's "Find strange game data" notice. Neither feature exists in the port yet. + +### 2026-10-07 (pass 25): systemSetting, skill, miniMap, chr/chrmgr (batch 3) +The five script-facing modules from the audit's batch 3 now follow the original AVA2 code. +- **systemSetting.** `src/python_system.cpp` ports CPythonSystem and PythonSystemModule.cpp: metin2.cfg parsing and the exact SaveConfig text, interface.cfg as raw little-endian int32, display-mode merging, SetConfig/GetConfig and all 58 methods with the original constants. Test: ava2.system_setting. +- **skill.** The 21 PythonSkill.cpp methods in `src/python_native_modules.cpp`: SetPathName/RegisterSkill (per-skill CTextFileLoader files, 949 name wins, no overwrite), skilldesc icon paths per job column (riding 130 uses skill/common/support), the never-filled requirement data, icon images/instances, GetGradeData and TEST. Test: ava2.skill. +- **miniMap.** New `src/python_minimap.{h,cpp}` ports CPythonMiniMap and the 27 module functions (ENABLE_MINIMAP_WHITEMARK_NEW, NAMECOLOR_BOSS_CLIENT, ENABLE_STONEMINIMAP, ENABLE_OFFLINESHOP_SYSTEM on; WJ_COMBAT_ZONE off). LoadAtlas reads setting.txt + atlas.sub and the `_point.txt` marks; Update classifies and clips marks by radius; observers, targets, guild areas, way/signal points, GetInfo/GetAtlasInfo/GetAtlasSize and the atlas window callbacks are ported. WarpBackgroundMap calls LoadAtlas; the event manager and the target packets (123/124/125) feed the map. The extra RegisterColor (not in Windows; only an uncalled uiminimap.py helper uses it) is gone. Test: ava2.minimap. +- **chr / chrmgr.** New `src/python_chr.cpp` ports PythonCharacterModule.cpp (80 methods) and PythonCharacterManagerModule.cpp (37 methods, original order). The stand-in chr instance table (its own model loading and draw list) is deleted; chr now drives NetworkActorManager like CPythonCharacterManager on Windows, and GetAllActiveChrDraws is `NetworkActorManager::BuildDrawCommands`. + - chr argument errors answer `Py_BuildException()` (None); WeaponTraceSetTexture, MoveToDestPosition and testSetRideMan use Py_BadArgument. chrmgr uses Py_BadArgument everywhere, and "RaceData has not selected!" without a selected race. + - Rotation conversions as on Windows: SetRotation `fmod(r+180, 360)`, BlendRotation `fmod(720-r, 360)`, GetRotation `360 - yaw`, SetDirection's 8-entry table (out of range → 0). + - CreateInstance(vid, dict) builds a PC "NONAME" (mov/atk 100, armor 8) and keeps the original bug of writing "y" into the X position; without a dict it is RegisterInstance. Already-existing VIDs log "ALREADY EXIST". + - No-instance answers: GetRotation 0.0, GetRace 0, GetName 0, GetNameByVID "None", GetProjectPosition (-100, -100), GetVirtualNumber/GetInstanceType 6, testGetPKData (0, 4). + - GetProjectPosition projects through the text-tail scene renderer. GetVIDInfo prints the global position (local + map base). SetPathName ignores paths without "d:/ymir". RegisterMotionData caps the weight at 100. SetMotionRandomWeight discards its exception like Windows. SetEmoticon/IsPossibleEmoticon with vid < 0 use the selected instance. + - Supporting changes: ActorInstance::Revive/IsFaint, TextTailManager::GetCurrentSceneRenderer, public NetworkActorManager part setters + IsPartyMember, `m_dwVirtualNumber` (= race on AppendActor), RegisterInstance defaults to TYPE_PC (CActorInstance::__Initialize), and Clear() now detaches text tails (DeleteAllInstances). + - NEW_PET_SYSTEM is off in Locale_inc.h, so chr.RequestPetName does not exist (its only caller, uipetincubatrice.py:83, belongs to the disabled pet incubator). + - Tests: new ava2.chr (`tests/chr_test.cpp`) covers both module surfaces, the no-instance answers, the two error styles, rotations/directions, the CreateInstance dict path and its bug, pixel positions with and without Z, instance types, Hide/Show, GetVIDInfo, SetPathName's guard, SetRaceHeight, testSetRideMan and Destroy. python_test now calls `chr.SetArmor(0)` after SetRace (Windows does not build a model from SetRace alone) and `chr.GetPixelPosition(201)` (the VID argument is required). +Validation: +- CTest is 40/40 (new: ava2.system_setting, ava2.skill, ava2.minimap, ava2.chr). +- python_test passes, and the macOS and Android arm64 builds pass. +- The 229 packet constants match, and the 925 reference hashes are unchanged. +- Interfaces are 46 modules, 0 missing, 370 placeholders (was 557). The parity inventory has 402 placeholder bindings (was 596). +Remaining: +- **systemSetting:** no RefreshShadowLevel, gamma ramp, software cursor or mob-info (AI flag/level) refresh; display modes come from SDL; the config directory differs on Android; some bounds checks added where Windows indexes unchecked; GetConfig emulates the x86 varargs quirk (the float music volume in an "i" slot shifts every later field one place and drops iDistance). +- **skill:** GetSkillRequirementData's `Py_BuildValue("si",0,"None",0)` quirk returns (None, 0); GetGradeData's std::string-through-varargs is emulated (short names give their first 4 bytes, else 0); icons resolve lazily; code page 949 is a constant; icon instances are handles (grpImage is still a placeholder); GetIconImage returns 0 for an unknown skill. +- **miniMap:** nothing is drawn (no D3D minimap/atlas pipeline); observers are unreachable as in the original header map; ENABLE_GRAPHIC_ON_OFF render status is always on; the guild-area overlay, __DownloadSymbol and CreateTargetEffect are not ported; __Update_NotifyGuildAreaEvent is not wired; GetInfo/GetAtlasSize zero-init their outputs; an unknown NPC gives an empty name; setting.txt only supplies MapSize/BasePosition. +- **chr / chrmgr:** + - No pick pass: chr.PickAll is -1 and Pick/GetPickedVID only see OLD_GetPickedInstanceVID. + - No backend for the add/modulate/blend/specular render modes, Select's shop highlight, bounding spheres/GetBoundBoxOnlyXY, weapon trace, combo type, AttachEffect* or the direction line; these only parse. + - Hide/Show toggle `m_isHidden` instead of blending the alpha. + - MountHorse only switches to MODE_HORSE; the horse actor is not created. + - Motion blend times, speed ratios and SetMotionRandomWeight are not ported; PC motions from the closed resource.dll are not registered. + - DeleteInstanceByFade removes at once; with no dead list GetVIDInfo's isDead is always 0. + - SetDirection has a null guard (Windows crashes without a selection). SetRotationAll ignores X/Y. MoveToDestPosition does not recompute the direction. testSetRideMan keys the actor as VID 1 (Windows leaves the graphic VID 0). + - chr.Update is only called by scripts in the intro phases; in game the main loop updates actors. diff --git a/docs/WINDOWS-PARITY-INVENTORY.json b/docs/WINDOWS-PARITY-INVENTORY.json index 0ccbe08e..14e8856d 100644 --- a/docs/WINDOWS-PARITY-INVENTORY.json +++ b/docs/WINDOWS-PARITY-INVENTORY.json @@ -1,6 +1,6 @@ { "scope": "Static Python method-table inventory; excludes hidden no-ops, renderer and packet behavior. Full parity is NOT established.", - "placeholder_count": 994, + "placeholder_count": 402, "placeholders": [ { "file": "src/python_app.cpp", @@ -38,12 +38,6 @@ "handler": "app_dummy_none", "status": "placeholder" }, - { - "file": "src/python_app.cpp", - "api": "SetTwoHandedWeaponAttSpeedDecreaseValue", - "handler": "app_dummy_none", - "status": "placeholder" - }, { "file": "src/python_app.cpp", "api": "SetRideHorseEnable", @@ -242,12 +236,6 @@ "handler": "app_dummy_tuple2", "status": "placeholder" }, - { - "file": "src/python_app.cpp", - "api": "GetRandom", - "handler": "app_dummy_zero", - "status": "placeholder" - }, { "file": "src/python_app.cpp", "api": "RunPythonFile", @@ -416,30 +404,6 @@ "handler": "app_dummy_zero", "status": "placeholder" }, - { - "file": "src/python_app.cpp", - "api": "OpenTextFile", - "handler": "app_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_app.cpp", - "api": "CloseTextFile", - "handler": "app_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_app.cpp", - "api": "GetTextFileLineCount", - "handler": "app_dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_app.cpp", - "api": "GetTextFileLine", - "handler": "app_dummy_str", - "status": "placeholder" - }, { "file": "src/python_app.cpp", "api": "ForceSetLocale", @@ -452,12 +416,6 @@ "handler": "app_dummy_none", "status": "placeholder" }, - { - "file": "src/python_app.cpp", - "api": "LoadLocaleData", - "handler": "app_dummy_none", - "status": "placeholder" - }, { "file": "src/python_app.cpp", "api": "SetCHEONMA", @@ -512,12 +470,6 @@ "handler": "app_dummy_zero", "status": "placeholder" }, - { - "file": "src/python_app.cpp", - "api": "EnableTestServerFlag", - "handler": "app_dummy_none", - "status": "placeholder" - }, { "file": "src/python_app.cpp", "api": "OnLogoUpdate", @@ -584,114 +536,18 @@ "handler": "app_dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetUseSoundFileName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetDropSoundFileName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetIBuyItemPrice", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetISellItemPrice", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsAntiFlag", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsFlag", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsWearableFlag", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Is1GoldItem", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetSocket", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "GetIconInstance", "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetUseType", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "DeleteIconInstance", "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsEquipmentVID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsRefineScroll", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsDetachScroll", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsKey", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsMetin", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "CanAddToQuickSlotItem", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "Update", @@ -722,12 +578,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "LoadItemTable", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "IsSealScroll", @@ -752,12 +602,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetApplyPoint", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "GetItemsByName", @@ -800,18 +644,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SelectItemWiki", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetRefineSet", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "GetAutoPotionInfo", @@ -836,30 +668,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsAntiFlagBySlot", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetItemTypeBySlot", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetItemSubTypeBySlot", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsSameItemVnum", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "PickCloseItemVector", @@ -872,12 +680,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetGameWindow", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "RegisterEffect", @@ -920,18 +722,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetMainCharacterIndex", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsMainCharacterIndex", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "CanAttackInstance", @@ -956,24 +746,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsChallengeInstance", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsRevengeInstance", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsCantFightInstance", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "GetCharacterDistance", @@ -992,12 +764,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsObserverMode", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "ActEmotion", @@ -1076,24 +842,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetSkillSlotIndex", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetSkillCurrentEfficientPercentage", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetSkillNextEfficientPercentage", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "ChangeCurrentSkillNumberOnly", @@ -1106,24 +854,12 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetItemFlags", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "GetItemUnbindTime", "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetISellItemPrice", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "MoveItem", @@ -1136,36 +872,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsGameMaster", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetJob", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetRace", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetPlayTime", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetPlayTime", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "IsSkillActive", @@ -1178,102 +884,18 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "AffectIndexToSkillIndex", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetEXP", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetConquerorEXP", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetGuildID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetGuildName", - "handler": "dummy_str", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "GetAlignmentData", "handler": "dummy_tuple2", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RequestAddToEmptyLocalQuickSlot", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RequestDeleteGlobalQuickSlot", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RequestMoveGlobalQuickSlotToLocalQuickSlot", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "LocalQuickSlotIndexToGlobalQuickSlotIndex", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetQuickPage", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetQuickPage", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RemoveQuickSlotByValue", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "isItem", "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsDSEquipmentSlot", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsValuableItem", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "IsOpenPrivateShop", @@ -1328,30 +950,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "CanRefine", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "CanDetach", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "CanUnlock", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "CanAttachMetin", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "ClearTarget", @@ -1400,66 +998,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsPartyMember", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsPartyLeader", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsPartyLeaderByPID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetPartyMemberHPPercentage", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetPartyMemberState", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetPartyMemberAffects", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RemovePartyMember", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ExitParty", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetPKMode", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "HasMobilePhoneNumber", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "RegisterEmotionIcon", @@ -1478,12 +1016,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ToggleCoolTime", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "ToggleLevelLimit", @@ -1526,12 +1058,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SlotTypeToInvenType", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "SendDragonSoulRefine", @@ -1562,18 +1088,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetItemNewName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetKillLOG", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "GetMainCharacterPart", @@ -1610,786 +1124,6 @@ "handler": "dummy_zero", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetRaceHeight", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetEmpireNameMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetVIDInfo", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetPickedVID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetShapeModel", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "AppendShapeSkin", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetPathName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "LoadRaceData", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "LoadLocalRaceData", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "CreateRace", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SelectRace", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterAttachingBoneName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterMotionMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterMotion", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetMotionRandomWeight", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterNormalAttack", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ReserveComboAttack", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterComboAttack", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ReserveComboAttackNew", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterComboAttackNew", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterMotionData", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterRaceName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterRaceSrcName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterCacheMotionData", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetAffect", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetEmoticon", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsPossibleEmoticon", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterEffect", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterCacheEffect", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterPointEffect", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ShowPointEffect", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ToggleDirectionLine", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetMovingSpeed", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetDustGap", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetHorseDustGap", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterTitleName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterNameColor", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RegisterTitleColor", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "DismountHorse", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "MountHorse", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetSash", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Render", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RenderCollision", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "DeleteInstanceByFade", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsEnemy", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsNPC", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsGameMaster", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsPartyMember", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Select", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetAddRenderMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetBlendRenderMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Unselect", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Pick", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "PickAll", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetArmor", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetVirtualID", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetInstanceType", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RequestPetName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetDirection", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Refresh", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Revive", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Die", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "AttachEffectByID", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "AttachEffectByName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "LookAt", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetMotionMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetLoopMotion", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "BlendLoopMotion", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "PushOnceMotion", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "PushLoopMotion", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "BlendRotation", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetRotation", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetGuildID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetProjectPosition", - "handler": "dummy_tuple3", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetVirtualNumber", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetInstanceType", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetBoundBoxOnlyXY", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RaceToJob", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RaceToSex", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testGetPKData", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "FaintTest", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetMoveSpeed", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetAttackSpeed", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "WeaponTraceSetTexture", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "WeaponTraceUseAlpha", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "WeaponTraceUseTexture", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "MoveToDestPosition", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testSetComboType", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testSetAddRenderMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testSetModulateRenderMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testSetAddRenderModeRGB", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testSetModulateRenderModeRGB", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testSetSpecularRenderMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testSetSpecularRenderMode2", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testRestoreRenderMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "testSetRideMan", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsStone", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetChatColor", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Clear", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Close", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "CreateChatSet", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Update", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "Render", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetBoardState", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetPosition", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetHeight", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetStep", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ToggleChatMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "EnableChatMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "DisableChatMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetEndPos", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetLineCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetVisibleLineCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetLineStep", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "AppendChat", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "AppendChatWithDelay", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ArrangeShowingChat", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IgnoreCharacter", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "IsIgnoreCharacter", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "CreateWhisper", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "AppendWhisper", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "RenderWhisper", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetWhisperBoxSize", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "SetWhisperPosition", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "ClearWhisper", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "InitWhisper", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GetLinkFromHyperlink", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "DeleteChatSet", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "EnableCountryMode", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "DisableCountryMode", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "IsSoftwareTiling", @@ -2414,18 +1148,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GlobalPositionToLocalPosition", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "GlobalPositionToMapInfo", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "GetRenderShadowTime", @@ -2648,12 +1370,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_gameplay_modules.cpp", - "api": "WarpTest", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_gameplay_modules.cpp", "api": "CreatePrivateShopPos", @@ -3194,360 +1910,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_native_modules.cpp", - "api": "GetEventType", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetEventTypeByVID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetLevelByVID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGradeByVID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetRaceNumByVID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterMaxHP", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterRaceFlag", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterLevel", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterDamage", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterExp", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterDamageMultiply", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterST", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterDX", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsMonsterStone", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMobRegenCycle", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMobRegenPercent", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMobGoldMin", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMobGoldMax", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetResist", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "LoadNonPlayerData", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterPrice", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMobsByName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterLevel", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterRaceFlag", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsMonsterStone", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterDamage", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterExp", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterDamageMultiply", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterST", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterDX", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsMonsterStone", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterResist", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMonsterMaxHP", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetScale", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "ScaleUp", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "ScaleDown", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetMiniMapSize", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetCenterPosition", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Destroy", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Create", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Update", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Render", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Show", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Hide", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "isShow", - "handler": "dummy_bool_false", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "LoadAtlas", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "UpdateAtlas", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "RenderAtlas", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "ShowAtlas", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "HideAtlas", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "isShowAtlas", - "handler": "dummy_bool_false", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsAtlas", - "handler": "dummy_bool_false", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "AddWayPoint", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "RemoveWayPoint", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "RegisterAtlasWindow", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "UnregisterAtlasWindow", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildAreaID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "RegisterColor", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_native_modules.cpp", "api": "Push", @@ -3560,348 +1922,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_native_modules.cpp", - "api": "UpdateEventSet", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetVisibleLineCount", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "RenderEventSet", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Skip", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsWait", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "EndEventProcess", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetVisibleStartLine", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetVisibleStartLine", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetInterfaceWindow", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetLeftTimeString", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "QuestButtonClick", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Destroy", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetYPosition", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "AllProcessEventSet", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "AddEvent", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Open", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Close", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Clear", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsOpen", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetItemID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetItemCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetItemPrice", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetItemMetinSocket", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetItemAttribute", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetTabCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetTabName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetTabCoinType", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetVnumBuy", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetCountBuy", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsOfflineShop", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemVnum", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemPrice", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemMetinSocket", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemAttribute", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSign", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "ClearOfflineShopStock", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "AddOfflineShopItemStock", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "DelOfflineShopItemStock", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemPriceReal", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemStatus", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopItemBuyerName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "BuildOfflineShop", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetDisplayedCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetOfflineShopID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetCurrentOfflineShopMoney", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "HasOfflineShop", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetRealWatcherCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "ChangeDecoration", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetShopFlag", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetShopFlag", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetShopType", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetShopType", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetShopTime", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetShopTime", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetItemRandomAttribute", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_native_modules.cpp", "api": "GetOfflineShopItemTransmutation", @@ -3914,324 +1934,12 @@ "handler": "dummy_tuple4", "status": "placeholder" }, - { - "file": "src/python_native_modules.cpp", - "api": "SetPathName", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "RegisterSkill", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_native_modules.cpp", "api": "LoadSkillData", "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_native_modules.cpp", - "api": "ClearSkillData", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillDescription", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillType", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillConditionDescriptionCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillConditionDescription", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillAffectDescriptionCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillAffectDescription", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillCoolTime", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillNeedSP", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillContinuationSP", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillMaxLevel", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillLevelUpPoint", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillLevelLimit", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsSkillRequirement", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillRequirementData", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillRequireStatCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillRequireStatData", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "CanLevelUpSkill", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsLevelUpSkill", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "CheckRequirementSueccess", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetNeedCharacterLevel", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsUseHPSkill", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "CanUseSkill", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetIconName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetIconImage", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetIconInstance", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetIconInstanceNew", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "DeleteIconInstance", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGradeData", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetIconImageNewEx", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetNewAffectDataCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetNewAffectData", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetDuration", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "TEST", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetSkillSlot", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetIconImage", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillbySlot", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetEmptySkill", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetQuestCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetQuestData", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetQuestIndex", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetQuestLastTime", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Clear", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Add", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "RemoveFriend", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsFriendByName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Destroy", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "RefreshGuildMember", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetMessengerHandler", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_native_modules.cpp", "api": "SendCloseRequest", @@ -4310,18 +2018,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_native_modules.cpp", - "api": "IsBlackList", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "ReadData", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_native_modules.cpp", "api": "IsRunning", @@ -4358,282 +2054,6 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_native_modules.cpp", - "api": "Open", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SearchItem", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "CountDates", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetPageView", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetPageSelect", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetPageActual", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetDropItemHandler", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsGuildEnable", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "HasGuildLand", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildMasterName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetEnemyGuildName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildMoney", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildBoardCommentCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildBoardCommentData", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildLevel", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildExperience", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildMemberCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildMemberLevelSummary", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildMemberLevelAverage", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildExperienceSummary", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildSkillPoint", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetDragonPowerPoint", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGuildSkillLevel", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillLevel", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillMaxLevelNew", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetSkillIndex", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSkillIndex", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGradeData", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetGradeName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMemberCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetMemberData", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "MemberIndexToPID", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsMember", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "IsMemberByName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "MainPlayerHasAuthority", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Destroy", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "CountDateRanking", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "InfoDateRanking", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "InfoDateMision", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Open", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Teleport", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Ranking", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Mision", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetPageCount", - "handler": "dummy_none", - "status": "placeholder" - }, { "file": "src/python_native_modules.cpp", "api": "SetMount", @@ -4682,174 +2102,12 @@ "handler": "dummy_none", "status": "placeholder" }, - { - "file": "src/python_native_modules.cpp", - "api": "CountDates", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetCubeRenewalHandler", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "CubeRenewalMakeItem", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "CubeRenewalClose", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "CountDates", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetDates", - "handler": "dummy_tuple2", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetDatesItems", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetDatesCount", - "handler": "dummy_tuple3", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "SetBattlePassHandler", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetTime", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Open", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "Reward", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetItemCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemCount", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemPrice", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemVnum", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemShopVID", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "ClearSearchItems", - "handler": "dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemMetinSocket", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemAttribute", - "handler": "dummy_tuple2", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemTransmutation", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemNewName", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemPerma", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemPos", - "handler": "dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemSeller", - "handler": "dummy_str", - "status": "placeholder" - }, - { - "file": "src/python_native_modules.cpp", - "api": "GetSearchItemID", - "handler": "dummy_zero", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "GetBettingGuildWarValue", "handler": "net_dummy_zero", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "EnableChatInsultFilter", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "SetServerInfo", @@ -4862,18 +2120,6 @@ "handler": "net_dummy_str", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "PreserveServerCommand", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "GetPreservedServerCommand", - "handler": "net_dummy_str", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "IsTest", @@ -4886,24 +2132,6 @@ "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "IsChatInsultIn", - "handler": "net_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "IsInsultIn", - "handler": "net_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "LoadInsultList", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "UploadMark", @@ -4916,30 +2144,12 @@ "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "GetGuildID", - "handler": "net_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendTargetInfoLoad", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "ToggleGameDebugInfo", "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "SetServerCommandParserWindow", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "SetTCPRecvBufferSize", @@ -5024,348 +2234,18 @@ "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "SendElkDropPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGoldDropPacketNew", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "SetOfflinePhase", "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "IsConnect", - "handler": "net_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendEmoticon", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "SendMobileMessagePacket", "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "SendShopEndPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendShopBuyPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendShopSellPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendShopSellPacketNew", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendExchangeStartPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendExchangeItemAddPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendExchangeItemDelPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendExchangeElkAddPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendExchangeAcceptPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendExchangeExitPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "RegisterEmoticonString", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendMessengerAddByVIDPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendMessengerAddByNamePacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendMessengerRemovePacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartyInvitePacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartyInviteAnswerPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartyExitPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartyRemovePacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartyRemovePacketPID", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartyRemovePacketVID", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartySetStatePacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartyUseSkillPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendPartyParameterPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendSafeboxSaveMoneyPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendSafeboxWithdrawMoneyPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendSafeboxCheckinPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendSafeboxCheckoutPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendSafeboxItemMovePacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendMallCheckoutPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendAnswerMakeGuildPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendQuestInputStringPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendQuestInputLongStringPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendQuestConfirmPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildAddMemberPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildRemoveMemberPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildChangeGradeNamePacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildChangeGradeAuthorityPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildOfferPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildPostCommentPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildDeleteCommentPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildRefreshCommentsPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildChangeMemberGradePacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildUseSkillPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildChangeMemberGeneralPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildInviteAnswerPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildChargeGSPPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildDepositMoneyPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGuildWithdrawMoneyPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendRequestRefineInfoPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendSelectItemPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SetEmpireLanguageMode", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "SetSkillGroupFake", @@ -5390,36 +2270,12 @@ "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "SendOfflineShopEndPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendOfflineShopBuyPacket", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "SendAddOfflineShopItem", "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "SendRemoveOfflineShopItem", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendDestroyOfflineShop", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "SendTakeOfflineMoney", @@ -5444,36 +2300,6 @@ "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "SendOfflineShopRemoveLogs", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendOpenShopSlot", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendGetBackItems", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendAddTime", - "handler": "net_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_net.cpp", - "api": "SendOpenWithVID", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "RegisterErrorLog", @@ -5528,12 +2354,6 @@ "handler": "net_dummy_none", "status": "placeholder" }, - { - "file": "src/python_net.cpp", - "api": "SendPrivateShopSearchInfo", - "handler": "net_dummy_none", - "status": "placeholder" - }, { "file": "src/python_net.cpp", "api": "SendMiniGameCatchKingStart", @@ -5593,378 +2413,6 @@ "api": "GetDayActivate", "handler": "net_dummy_zero", "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetShadow", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsShadow", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsShowDamage", - "handler": "sys_dummy_one", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetShowDamageFlag", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsShowSalesText", - "handler": "sys_dummy_one", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetShowSalesTextFlag", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsShowOutline", - "handler": "sys_dummy_one", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetShowOutlineFlag", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsSoftwareCursor", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "isInterfaceConfig", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SaveWindowStatus", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetWindowStatus", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetResolutionCount", - "handler": "sys_dummy_one", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetFrequencyCount", - "handler": "sys_dummy_one", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetCurrentResolution", - "handler": "sys_dummy_tuple3", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetResolution", - "handler": "sys_dummy_tuple3", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetFrequency", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "ApplyConfig", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetConfig", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SaveConfig", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetConfig", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetInterfaceHandler", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "DestroyInterfaceHandler", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "ReserveResource", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetCollectEquipment", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsCollectEquipment", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetFastPickup", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsEnabledFastPickup", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetSnowTexturesMode", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsSnowTexturesMode", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsShowMobAIFlag", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetShowMobAIFlag", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "IsShowMobLevel", - "handler": "sys_dummy_one", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetShowMobLevel", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetShopNamesRange", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetShopNamesRange", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetQuestIconMode", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetQuestIconMode", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetCountryFlag", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetCountryFlag", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetAffectIcons", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetAffectIcons", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetFOVLevel", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetFOVLevel", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetEffectLevel", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetEffectLevel", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetPetRender", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetPetRender", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetMountRender", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetMountRender", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetShopNameStatus", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetShopNameStatus", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetNightMode", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetNightMode", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetStuffMessage", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetStuffMessage", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetDungeonTrack", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetDungeonTrack", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetBossTrack", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetBossTrack", - "handler": "sys_dummy_zero", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "SetMapObjectDistance", - "handler": "sys_dummy_none", - "status": "placeholder" - }, - { - "file": "src/python_system.cpp", - "api": "GetMapObjectDistance", - "handler": "sys_dummy_zero", - "status": "placeholder" } ] } diff --git a/docs/WINDOWS-PARITY.md b/docs/WINDOWS-PARITY.md index c30b2cf5..ae488238 100644 --- a/docs/WINDOWS-PARITY.md +++ b/docs/WINDOWS-PARITY.md @@ -18,7 +18,7 @@ Full 1:1 behavior is NOT implemented. The original AVA2 C++/Python snapshot is t ## Remaining substantial differences -- `docs/WINDOWS-PARITY-INVENTORY.json` contains 994 static placeholder method bindings. This counts bindings, not distinct gameplay features; it also includes configuration/diagnostic APIs. Non-placeholder functions can still have behavioral differences. +- `docs/WINDOWS-PARITY-INVENTORY.json` contains 681 static placeholder method bindings. This counts bindings, not distinct gameplay features; it also includes configuration/diagnostic APIs. Non-placeholder functions can still have behavioral differences. - Native `PythonNetworkStream` queues gameplay bytes separately from `LoginClient`; loading currently pauses login transport. Full loading/game receive dispatch, ciphertext transport, packet sequences and map handoff are not integrated end to end. - Host contains local map/actor/combat/loot demonstrations and phase shortcuts. These do not reproduce authoritative server gameplay. `--phase game`, `--until-game` and screenshots are development previews, not evidence of server entry. - Original UI scripts run over partial native bridges. Event routing, IME/text, layout/font/resource behavior and original window lifecycle need Windows comparison. @@ -301,3 +301,339 @@ Removed extra GetItemRefineInformation export and invented vnum+1/cost/probabili ### 2026-10-05: item equipment classification Replaced item.IsEquipmentVID zero placeholder with original selected-item lookup/fallback and CItemData::IsEquipment predicate (WEAPON/ARMOR only). Costume/rod/other item kinds do not count. Preserve selection side effect; regression samples every distinct real type/subtype and checks selected refined-vnum state. macOS/Android arm64 builds and20 nonvisual CTests passed;925 reference files unchanged. Full locale/item transactions/skill/combat/rendering parity remains incomplete, with render_3d timeout unresolved. + +### 2026-10-06: net exchange/safebox/messenger/party/guild/quest senders +Compared PythonNetworkStreamModule.cpp wrappers and PythonNetworkStreamPhaseGame*.cpp / PythonNetworkStreamPhaseGameItem.cpp senders against src/python_net.cpp and PythonNetworkStream.cpp. +Corrections: safebox item move was a wrong 4-byte struct; it is now the original 11-byte {header 77, TItemPos src, TItemPos dst, DWORD count} layout. Exchange senders gained the original main-actor action gate and default TItemPos {INVENTORY, 0xffff}; exchange ItemDel is a no-op returning true, as on Windows. Replaced about 45 net placeholders with verbatim-style wrappers and senders: exchange, safebox/mall checkout (2/3-arg switches; Mall raises Py_BuildException otherwise), messenger add by VID/name and remove (with target-board refresh), party invite/answer/remove/state/skill/parameter (remove only in Game phase), all 15 guild subheaders (comment refresh 1000 ms throttle; post comment BYTE length incl. NUL), answer make guild, quest input string/long string/confirm, script select item, target info load, refine-info request no-op. Added the CG headers/subheaders/length constants to Packet.h; the packet-constant audit now covers MESSENGER/GUILD CG subheaders (155 checked, 0 mismatches). Python interface audit placeholders 749 → 618. +Tests: ava2.python golden-byte block for every new sender, outside-Game party remove, messenger board callback, guild throttle, argument failures, and exchange gate with a controlled main actor. +Validation: macOS build passed; Android arm64 libmain.so built (SDL3 3.4.16 rebuilt for arm64 in a scratch prefix); 925 reference files unchanged. CTest: 16/20 nonvisual pass. ava2.python, window_tree, speedtree_forest, mark_manager fail identically on the unmodified baseline commit. The cause is the environment, not this change: assets now live at ../AVA2/TEST/1. Client DEV/pack_maker, while sources/tests still hardcode /Users/shen/... and cwd-relative `ymir work`/`locale`/`UIScript`. With a scratch run directory mirroring upstream/python-root plus `ymir work`, python_test (including the new block) passes. +Remaining: SelectEmpire/ChangeName (select-phase LoginClient path), SendEmoticon (needs chat receive parsing), offline-shop AddItem/TakeMoney/ChangeTitle/Check/Button, party/guild member state (PartyExit/RemoveVID/GuildRemoveMember lookups always fail), other modules' placeholders, and configurable asset roots. render_3d remains excluded for its unresolved timeout. + +### 2026-10-06 (pass 2): receive loop, chat/whisper, server commands +Compared CNetworkPacketHeaderMap/CheckPacket, GamePhase()/LoadingPhase() dispatch, RecvChatPacket/RecvWhisperPacket (ENABLE_MULTILANGUAGE_SYSTEM), ServerCommand (PythonNetworkStreamCommand.cpp), SendChatPacket/emoticon handling and PyCallClassMemberFunc semantics against src/eter_net and src/python_net.cpp. +Corrections: +- Receive loop: header sizes now come from `Ava2GcPacketTable.inc`, produced by tools/generate_ava2_gc_packet_table.py. The script evaluates the reference CMainPacketHeaderMap and GamePhase switch with clang i686-pc-windows-msvc, giving 138 mapped headers and 119 GamePhase handlers. + - Zero padding is skipped. A dynamic size is read from the WORD at offset 1, and the loop waits until the whole packet has arrived. + - An unmapped header triggers a trace, clears the buffer and requests quit, standing in for PostQuitMessage. main.cpp stops the loop. + - A handler that returns false triggers a trace and clears the buffer, as RecvErrorPacket does. + - In the Game phase, the loading-only headers 15/113/137/138 reach RecvDefaultPacket, which clears the buffer. + - A GamePhase header with no port yet is skipped as exactly one packet and recorded, so the stream no longer desyncs. +- Python callbacks use `PyCallClassMemberFunc`. A missing method is skipped, and an exception is printed instead of propagating as a C++ throw. +- Chat: + - types ≥ CHAT_TYPE_MAX_NUM (15) are dropped; COMMAND goes to ServerCommand; + - an unknown VID is dropped; + - for chatter types, the text after ": " is checked against ParseEmoticon; + - RegisterChatTail is called except for SHOUT; + - AppendChat runs only for PC actors; + - with VID 0, SHOUT goes to AppendChat and every other type goes to the game window's GetLocaleString(type, text). +- Whisper uses the original 31-byte header with bLanguage/bEmpire, enforced by static_assert: + - CHAT/GM → OnRecvWhisper(type, name, "name : msg", lang, empire); + - SYSTEM/ERROR → OnRecvWhisperSystemMessage; + - anything else → OnRecvWhisperError. +- ServerCommand (new src/eter_net/PythonNetworkStreamCommand.cpp, with a provenance header): + 1. ConsoleEnable returns early. + 2. BINARY_ServerCommand_Run is tried on the game window, or on the parser window when there is no game window. A true result stops processing. + 3. Tokens are split with SplitToken (quotes kept together, case preserved). + 4. The original strcmpi chain then runs. It covers gift, cube, Observer*, OfflineShopSetFlag, cards, Zodiac, mobile_auth, messenger_auth, setblockmode, quit, sms/nosms and combo. + 5. Unknown commands trace "Unknown Server Command". +- New net functions: PreserveServerCommand/GetPreservedServerCommand, SetServerCommandParserWindow, RegisterEmoticonString (max 128) / SendEmoticon, EnableChatInsultFilter and SetEmpireLanguageMode, each with the original constructor-lifetime state. +- player.IsObserverMode and HasMobilePhoneNumber now read the stream state. +- SendChatPacket returns true for empty input or input of 512 bytes or more. A bare "/" repeats the last slash command. +Tests: ava2.python now covers all of the above. That includes the cube/messenger_auth quoted tokens, Run=True short-circuit, the 31-byte whisper cases, a missing or raising callback, the "/" repeat, an unported header-36 skip with a partial wait, unknown header 250 → quit (cleared again by ResetConnection), and header 138 in the Game phase. +Validation: macOS build clean; Android arm64 libmain.so built; 925 reference files unchanged; packet constant audit 155/0; interface audit 609 placeholders, down from 618. CTest `-E render_3d` gives 16/20, with the same four environment failures as before. +Correction to pass 1: that pass reported python_test as passing, but it had actually stopped early. CreateCharacterWindow aborted on the missing ui/pattern texture, and the harness returns rc=0 when Python aborts, because app.Abort is a no-op. The run directory now needs a merged lowercase `ymir work` overlay of every pack_maker `*/ymir work`, with PC first, then ETC, then root, then the rest; it also needs `map` → pack_maker/Maps and `textureset` → Maps/textureset. In that setup the full python_test reaches its final "passed" line. Always check the log for that line, not the exit code. +Remaining: +- 75 Windows GamePhase handlers are still unported; they are now skipped safely: 18, 36, 39, 40, 41, 43, 45, 46, 47, 48, 58, 61, 62, 63, 66, 68, 69, 71, 74, 75, 77–83, 89, 91–93, 95, 99, 110–112, 114, 115, 119, 121, 123–125, 130–132, 134, 141, 152, 153, 156, 171, 204, 205, 208, 209, 213–218, 220, 221, 230, 231, 235, 241, 242, 249, 252, 255. +- Headers 96/97/98 appear in the switch but not in the header map, so they behave as unknown on Windows too. +- The chat module is entirely placeholder (33/33), so AppendChat only reaches the callback. +- Not ported: emoticon effect playback, the insult filter, the empire convert table (YMIR locale only, so a no-op for AVA2), emotions, StoneDetect, stamina, OfflineShop SetShopFlag and the combo skill slot level. +- The Login/Select phases share one dispatcher. +- app.Exit/Abort are no-ops. +- Asset roots are hardcoded. +- render_3d is still excluded because of its timeout. + +### 2026-10-06 (pass 3): remaining GamePhase handlers +Ported 63 of the 75 skipped GamePhase() headers in the new src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp. Each one follows the matching handler in PythonNetworkStreamPhaseGame.cpp, PhaseGameItem.cpp, PhaseGameActor.cpp or PhaseHandShake.cpp, with the AVA2 Locale_inc.h feature set. Wire reads and Python callbacks match the reference one for one. +- Ported headers: 18, 36, 39–41, 43, 45, 46, 48, 58, 61–63, 66, 68, 69, 71, 77–80, 82, 83, 89, 91, 92, 95, 99, 110–112, 115, 119, 121, 123–125, 130–132, 134, 141, 152, 153, 204, 205, 208, 209, 213–216, 218, 231, 235, 241, 242, 249, 252 and 255. +- Handshake and server time: 255 stores the server time sync and sends TIME_SYNC (0xfc) with dwTime+2·lDelta, sequenced. 252 calls SetServerMSec. 255, 252, 152 and 153 return from GamePhase() as on Windows, so the rest of the buffer and the refresh block wait for the next frame. +- Refresh block now runs in Windows order: Character, Inventory, Skill, Status. The new Character flag is set by ChangeSkillGroup. +- XTrap 205 replies with 204 plus 128 bytes without SendSequence. XTRAP_CLIENT_ENABLE is off in the reference, so the reply data is left uninitialised there; the port sends zeros. The send queue now carries a per-packet sequence flag through LoginClient/LoginSession::send_game_packet. +- Packets that fail on Windows still fail here, so RecvErrorPacket clears the buffer: + - HS 204: neither HackShield nor LOCALE_SERVICE_GLOBAL is defined. + - Unk213: the `Recv(sizeof(...)), &pkt` comma bug. +- Refine 95/119 use the ENABLE_MULTI_REFINE_WORLDARD subtype callbacks: 95 → OpenRefineDialog/AppendMaterialToRefineDialog, 119 → BINARY_MULTI_REFINE_ADD_INFO/ADD_MATERIAL. +- Player and actor state now updated: + - party members; + - PVP and duel keys; + - Remember*/ForgetInstance; + - kill log; + - skill group, together with NEW_ClearSkillData; + - walk mode; + - fishing state; + - ownership; + - dungeon destination. +- Target and TargetInfo use CanViewTargetHP, which includes Hydra race 6801, and pass the hide-costume string bounded. +Gaps (consumed exactly, logged here): +- Atlas/minimap marks and target effects: 115, 123–125. +- Guild land areas and the symbol download: 130. +- Fly targets: 69, 71. +- Dig, fishing and emotion motions. +- Specific effect: 208. +- Hybrid-crypt pack keys: 152, 153. +- CheatBlacklist: 249. +- Native stores: sash material, bank log, chest-drop items. +- The dungeon auto-walk. +- RefreshAllPCTextTail after DuelStart. +- The 300 ms refresh throttle. +- Not ported yet (12 headers): 47, 74, 75 (guild), 81, 93, 114, 156, 171, 217, 220, 221, 230. +Tests: ava2.python checks golden wire bytes and callbacks for: +- Handshake TIME_SYNC bytes, sequence flag and stop-frame; +- HandshakeOK server msec; +- the unsequenced XTrap ACK; +- HS/Unk213 buffer clear; +- the HybridCrypt stream skip; +- refine 95/119; +- refresh order; +- PVP key; +- Sash, KingdomsWar, Sungma, lover, 67Attr, guild-name; +- ExchangeLog LOAD/LOAD_ITEM, CatchKing, Calendar/ADM, DS refine; +- exact consumption of Land, NPC list, Dungeon and blacklist. +The unported-skip test now uses header 75. +Validation: +- macOS build clean. +- python_test reaches its "passed" line. +- CTest `-E render_3d` gives 16/20, with the same four environment failures. render_3d is still excluded because of its timeout. +- Android arm64 libmain.so built. +- 925 reference files unchanged. +- Packet constant audit: 210 checked, 0 mismatches. + +### 2026-10-06 (pass 4): quest state, Python getters and completion harness +Reference: upstream/ava2-client/UserInterface/PythonQuest.cpp, PythonQuest.h, Packet.h::packet_quest_info/QUEST_SEND_* and PythonNetworkStreamPhaseGame.cpp::RecvQuestInfoPacket (ENABLE_MULTILANGUAGE_SYSTEM active). +- HEADER_GC_QUEST_INFO81 is no longer skipped. Decode the six-byte packed Win32 header and flag-ordered 1/31/17/4/17/4/25-byte fields; force the original final string bytes to NUL. +- Ordered records distinguish array indices from DWORD quest IDs. Wire BEGIN deletes then appends, UPDATE creates a missing record and updates only nonempty strings/flagged values, END deletes. Reset the countdown start only on BEGIN/create or a flagged clock update. +- `^` titles are delegated to GetQuestLetterName with the original `(type,index,flag,title,clockName,counterName,icon,clockValue,counterValue)` arguments. RefreshQuest follows state changes or the translation callback, including END. +- Replaced all six quest placeholders: GetQuestCount, GetQuestData, GetQuestIndex, GetQuestLastTime, Clear, Add. Add's BEGIN duplicate guard differs from wire BEGIN exactly as the source does; Add's END/unknown types do nothing. Getters use array indices; invalid indices raise RuntimeError. Original tuple/string/signed-value semantics retained, with portable image handles replacing Win32 pointers and the original explicit/default icon paths. +- Header size/offset and all seven flags are extracted directly from the original source by generate_ava2_item_oracle.py and compared in windows_item_oracle_test. +- Malformed flagged payload lengths are bounded before subsequent packet reads. This avoids reproducing the original cross-packet read on corrupt declared sizes. +- Timer uses elapsed monotonic application seconds. Original virtual/frame-timer mode is not ported or verified. Missing icon resources yield handle0 through the existing resource adapter. This is task-list state parity, not full quest script interpreter/UI rendering parity. +- tests/quest_test.cpp verifies wire fragmentation plus following ping, signed counter values, packet BEGIN replacement/reordering, Python BEGIN duplicate retention, UPDATE empty strings/clock flags, negative/expired countdowns, high DWORD Python IDs, invalid array indices, multilingual callback-to-Add flow, END, Clear and malformed state preservation. +- tests/check_completion.py now wraps ava2.python and ava2.quest. Both a zero process status and final success marker are mandatory. Manual harness fixtures verify early exit(0) fails and a nonzero exit containing the marker also fails. +Validation: macOS build and Android arm64 libmain.so passed; quest and source oracle CTests passed. Existing comprehensive python_test passed through the wrapper using the prepared resource overlay, with final success marker present. python_view/login_loopback passed with local socket binding allowed. Nonvisual suite has four outstanding default-environment failures; render_3d still excluded. Correcting the previous description: speedtree_forest fails its canopy sway assertion, not a missing-file assertion; the other three failures involve asset/map/locale lookup. Reference hash verification925/925; packet constant audit211/0. Regenerated inventories: active method-table comparison597 overlapping placeholders (method-name coverage is not implementation parity); wider static inventory789 placeholders. The quest module lives in original PythonQuest.cpp rather than *Module.cpp, so its six replacements are covered by the dedicated regression, not that active method-table count. +Remaining skipped GamePhase headers:47,74,75,93,114,156,171,217,220,221,230. Existing guild/messenger/offline-shop/system stores, quest script interpreter, configurable assets, visual effects/rendering and real server/device verification remain incomplete. No AVA2 reference or existing server changed. + +### 2026-10-06 (pass 5): messenger and cube renewal state parity +Source basis: AVA2 PythonMessenger.cpp/.h, PythonCubeRenewal.cpp/.h, Packet.h declarations/enums and PythonNetworkStreamPhaseGame.cpp::RecvMessenger/RecvCubeRenewalPacket/CubeRenewalMakeItem/CubeRenewalClose. +- Messenger GC74: original LIST, LOGIN, LOGOUT and MOBILE handling. All insert list membership, including offline friends. LIST connected bits select OnLogin/OnLogout then optional OnMobile(group0,name,1); explicit MOBILE preserves BYTE state. LOGIN calls RefreshTargetBoardByName after OnLogin. Case-sensitive set membership retained. INVITE/unknown subheaders have no handler and leave payload bytes for the stream dispatcher as Windows does. +- Five messenger bindings now execute native state. RemoveFriend does not send a network request or callback; Destroy clears both lists without dropping the handler. Original no-message Py_BuildException argument failures return None. Native guild operations implement append-once/default-offline, login/logout, unconditional removal callbacks and sorted replay; GC75 is not yet connected. Replay copies the map to safely handle callback mutation instead of reproducing invalidated C++ iterators. +- Cube GC221: fixed167-byte frame,165-byte original recipe, ordered vector append including duplicate recipe IDs. OPEN goes to the game phase window; LOADING uses the cube handler; CLEAR empties the list and retains that handler. Unknown subheaders consume the fixed frame without state changes. +- Five cube bindings now implement count, original16-element GetDates tuple, handler registration, craft and close. Missing/negative array indices return the original15-zero + "None" tuple; missing argument returns None. Preserve Win32 signed DWORD values in Python getters and DWORD wrapping in requests. CG216 is10 bytes; craft sub4 carries index/count, close sub5 zeroes original undefined trailing fields. Both retain the original CanAct guard and sequence queue behavior. +- Safety adaptations: own/release callback references across replacement/runtime teardown; bound messenger names to24 bytes and declared frame lengths; bound cube category to100 bytes; use a BYTE for the incoming bool representation and normalize it on query. These avoid original raw-pointer/stack-overwrite/out-of-bounds/invalid-bool behavior without inventing normal gameplay semantics. +- Extended source extraction oracle compares original messenger structures/enums, cube structure sizes, every recipe offset and all cube subheaders. Wire fields use explicit Win32 widths; outgoing cube requests are serialized byte by byte. +- tests/messenger_test.cpp covers split LIST+ping, mixed connection bits, signed/mobile255 state, membership during callbacks, login target refresh order, case sensitivity, deletion, sorted guild replay, clearing/handler retention, INVITE behavior, malformed lengths, raising callbacks, handler weakref ownership and a second clean runtime. +- tests/cube_renewal_test.cpp covers literal167-byte fragmented recipe+ping,16-field signed tuples, duplicate append, open/loading/clear callbacks, invalid indices/arguments, exact CG bytes including high DWORD values, missing/controlled main actor gates, handler replacement and runtime reset. +Validation: macOS and Android arm64 library builds pass; messenger/cube/quest/declaration-oracle tests4/4 pass. Nonvisual suite19/23 with the same four outstanding failures; comprehensive python_test passes in the prepared asset overlay with both zero exit and completion marker. render_3d remains excluded/unverified; no live server/device test. Packet audit214/0;925 reference hashes unchanged. Regenerated static inventory780 placeholders; active *Module.cpp-only method inventory remains597 (these two reference modules, like quest, are outside that glob). Remaining skipped GamePhase headers47,75,93,114,156,171,217,220,230. Full client parity remains incomplete. + +### 2026-10-06 (pass 6): shop-search receive, query APIs and outgoing request +Reference: PythonPrivateShopSearch.cpp/.h, Packet.h::packet_offline_shop_item/packet_priv_shop_item_set/command_shop_search, PythonNetworkStreamPhaseGame.cpp::RecvShopSearchSet/SendPrivateShopSearchInfo and PythonNetworkStreamModule.cpp::netSendPrivateShopSearchInfo under AVA2 Windows active feature guards. +- GC156 reads the5-byte header, WORD record count and active128-byte item records. Decode all original Win32 fields including signed64 price, signed32 count/sockets,15 BYTE/signed16 attributes, status, seller and owner. Validate count against declared frame length before reading records; append only after the complete record block is read. Do not clear results on a new reply. Set a pending refresh flag, replayed once after the current receive batch and existing status refresh; zero-result replies also refresh. +- Replaced all12 active privateShopSearch bindings. Preserve signed DWORD Python conversion, literal"^" new-name result, invalid attribute zero tuple and too-large socket None result. ClearSearchItems clears the vector without a callback. Transmutation/perma bindings removed because WJ_CHANGELOOK_SYSTEM/ENABLE_PERMA_ITEM are inactive. Invalid record indices and negative sockets raise RuntimeError rather than allowing vector::at exceptions to escape or out-of-bounds reads; seller strings are bounded to25 bytes. +- net.SendPrivateShopSearchInfo parses the original19 arguments, serializes89 bytes with explicit widths/field order (sex before enchant/alchemy on wire despite different Python argument order), and applies CanAct. SendUnsequenced preserves the original absence of SendSequence. Valid text is copied with deterministic zeroed padding; >49 bytes raises ValueError rather than reproducing strcpy overflow. Prices remain signed64. +- Original-source oracle compares record/header/request sizes and all item/request offsets with the active Windows declarations. tests/shop_search_test.cpp independently builds literal128-byte records and89-byte requests, tests fragmentation+following ping, batch refresh, append/duplicate/empty replies, high DWORD IDs, negative price/count, last socket/attribute, seller/name behavior, active exports, malformed count state preservation, handler-visible results, exact unsequenced send bytes, action gates, text bounds and runtime reset. +- Global refresh throttle is still not ported: Windows sets the next refresh time to+500ms after a search refresh. Existing CheckPacket intentionally retains the reference's WORD dynamic framing even for this DWORD-size header; replies beyond65535 bytes and that reference edge case are not verified. No real-server search or rendered search UI claim. +- Fixed tools/audit_ava2_python_interfaces.py to discover .cpp module registration regardless of filename. Report now covers47 modules (previous29), with726 overlapping placeholder methods and7 missing guild_ranking methods: Close,CountDate,GetPageCount,GetPageView,InfoDate,Open,SetPageCount. This larger count exposes prior omissions. quest/messenger/cube/search have zero missing/extra/placeholder methods in the expanded audit. This is name coverage, not behavior verification. +Validation: macOS build and Android arm64 libmain.so pass. Five targeted CTests pass; full nonvisual20/24 with the same four baseline failures; comprehensive python_test passes through completion verification in the prepared asset overlay. render_3d remains excluded. Packet constants216 checked/0 mismatches;925 reference hashes unchanged; static placeholders765. Remaining skipped GamePhase headers47,75,93,114,171,217,220,230, plus the documented native systems/rendering/asset/server/device gaps. No reference files or existing server changed. + +## 2026-10-06 pass7 — guild receive and Python state +- Added the34 original compiled guild methods and all actual RecvGuild subheader branches;31 guild placeholders and net's guild-ID placeholder replaced. Preserve original cache insertion, tuple/sentinel behavior, member update/sort/statistics quirks, skill slots, authority mask and native/Python Destroy distinction. +- GC75 now supplies messenger guild membership/login/logout/removal, immediate target/invite/war callbacks and deferred page refreshes in the reference order. Main actor guild changes update net.GetGuildID and the matching character-selection roster; name-based remove-member sending uses the real PID. +- Win32 guild structures/enums/offsets are checked against source-extracted declarations. New guild_test validates state, embedded Python and literal fragmented/coalesced wire fixtures, including bounded malformed packets. +- GVG keys are present; ChangeGVG text-tail/name colours remain a documented gap. Guild protocol/API coverage does not imply full combat/UI parity. +- Interface audit now filters original .cpp files by Windows vcxproj compilation entries:46 modules,0 missing methods,694 overlapping placeholders; guild/quest/messenger/cube/search have no missing/extra/placeholder method names. Previous guild_ranking missing names were a false positive from orphan source. +- Corrected the earlier refresh-throttle claim: the reference early-return guard is commented out. Its300/500ms timestamp assignments have no active throttling effect. +- Builds pass on macOS Debug and Android arm64. Targeted tests6/6; full nonvisual CTest21/25 with the same four existing failures. The comprehensive Python test passes in the prepared asset overlay after replacing its outdated skipped-GC75 fixture with GC47. Static inventory733 placeholders;217 packet constants match;925 reference hashes unchanged. Remaining skipped game headers47,93,114,171,217,220,230; render_3d remains excluded/unverified. + +## 2026-10-06 pass8 — battle pass +- Replaced all8 battlepass placeholders. GC230 now dispatches the original two independent append-only lists, time, clear modes and loading/game callbacks. GetDates/GetDatesCount/GetDatesItems preserve original tuple shapes, defaults and signed values; invalid negative reward slots are bounded. +- CG230 OPEN/REWARD encode6 Win32 bytes with the original CanAct and SendSequence behavior; OPEN undefined padding is zeroed. Owned Python handler references survive list clears and release on replacement/runtime teardown. +- Literal fragmented/coalesced packet fixtures and source-extracted structure/enum/offset oracle checks pass. macOS Debug and Android arm64 builds pass; targeted7/7 and full nonvisual22/26 tests, with the four previously documented failures unchanged. Comprehensive Python regression passes in the prepared asset overlay. Static inventory725 placeholders, compiled-interface placeholders686,219 matching packet constants and925 unchanged reference files. Remaining skipped GamePhase headers47,93,114,171,217,220; full gameplay/rendering parity remains incomplete. + +## 2026-10-06 pass9 — drop item search +- Ported all8 drop_item methods, including the former hidden GetDates no-op. GC220 supplies ordered results and original clear/page/game/loading callback behavior; signed values, defaults and100-byte name bounds are verified. +- CG215 OPEN/SEARCH use6 explicit Win32 bytes, original CanAct and SendSequence; undefined OPEN vnum padding is zeroed. Registered Python handlers survive clears and release on replacement/runtime teardown. +- Literal fragmented/coalesced wire/native/Python tests and source-extracted protocol oracle pass. macOS Debug and Android arm64 builds pass; targeted8/8, full nonvisual23/27 with four existing failures unchanged, comprehensive Python regression passes in the prepared resource overlay. Static placeholders718, compiled-interface placeholders679,221 matching packet constants,925 unchanged reference files. Remaining skipped GamePhase headers47,93,114,171,217. Full gameplay/rendering parity is incomplete. + +## 2026-10-06 pass10 — dungeon information +- Replaced all12 dungeon_info methods and removed six fabricated dungeon entries/11-field query data. Original GC217 data drives the21-field info, mission and ranking queries, page behavior and original signed/default values. +- Ported independent list clears, mission-send ranking-clear fallthrough, immediate game callbacks and all four CG213 requests with explicit6-byte Win32 encoding, CanAct and SendSequence. OPEN undefined index padding is zeroed; fixed strings are bounded. +- Literal fragmented/coalesced packet/state/Python tests and source-extracted structure/enum/offset oracle pass. macOS Debug and Android arm64 builds pass; targeted9/9, nonvisual24/28 with four known failures unchanged. Comprehensive Python regression passes in the resource overlay. Static placeholders710, compiled-interface placeholders671,223 matching packet constants,925 unchanged reference files. Remaining skipped game headers47,93,114,171; full gameplay/rendering parity remains incomplete. + +## 2026-10-06 pass11 — switchbot +- Replaced9 existing but behaviorally incorrect switchbot methods: remove local fake run-state transitions and fabricated attribute lists/maxima; use GC171 table/item/server map state and actual player item-proto classification. Preserve internal6/exposed5 slots, BYTE/short conversions, original ClearSlot finished retention, sorted/deduplicated attribute map and32-bit max versus16-bit list values. +- Item updates ignore packet vnum, retain existing item fields and update all8 sockets/15 attrs. Player-window RefreshInventory occurs after count update and before socket/attribute changes; phase-window item refresh follows. CG171 start/stop match original Win32 bytes/sequencing, absence of action guard and slot6 boundary/header-size quirk. +- Original-source struct/enum/offset oracle and literal native/Python wire tests, including isolated generated item-proto classification fixtures, pass. macOS Debug and Android arm64 builds pass; targeted10/10, full nonvisual25/29 with the same four known failures. Comprehensive Python regression passes in the prepared resource overlay.225 matching constants,925 unchanged references. Static710/compiled671 placeholder counts are unchanged because the old functions were not named dummy; behavior still differed substantially. Remaining skipped game headers47,93,114; full parity remains incomplete. + +## 2026-10-06 pass12 — item shop +- GC93 now executes the original dragon-coin/log/item/catalog receive branches and game-window callbacks. Preserve64-bit prices/sales, signed DWORD values, original callback order, duplicate entries and per-category main-page opening/sentinel/zero-category behavior. No invented native item-shop store or extension API. +- BUY/RELOAD/LOG_ADD/unknown payload remains for the dispatcher as Windows does; malformed lengths/counts and unterminated strings are bounded. Original Python UI/chat-based requests remain unchanged, so full rendered store interaction parity is still unverified. +- Literal fragmented/coalesced callback tests and source-extracted Win32 structure/enum/offset oracle pass. macOS Debug and Android arm64 builds pass; targeted11/11, nonvisual26/30 with the same four known failures. Comprehensive Python regression passes in the resource overlay.226 matching constants,925 unchanged reference files; static710/compiled671 placeholder counts unchanged. Remaining skipped headers47,114; full client parity remains incomplete. + +## 2026-10-06 pass13 — offline shop +- GC47 now drives original shop item/metadata state and START/END/UPDATE/scalar/error callbacks. Replaced27 active PythonShop.cpp offline placeholders; preserve reversed logs, vnum-gated lookup, missing strings, Clear behavior, signed values and64-bit money/flags. Original IsOfflineShop is never set and remains0; CHECK_RESULT alone updates HasOfflineShop. +- Stock replacement/deletion/price query and display sorting feed explicit Win32 CG58 build requests; CG57 decoration uses the original58+52-byte layout. No action gate or local server-success state is invented. Uninitialized bytes are zeroed, strings bounded, decoration text copied literally and malformed records rejected safely. +- Original-source struct/enum/offset oracle and independent fragmented/coalesced wire/state/Python fixtures pass, including second-tab updates and zero-price logs. macOS Debug and Android arm64 builds pass;12 targeted tests pass, nonvisual27/31 with four existing failures.228 matching constants,925 unchanged references;683 static/644 overlapping compiled-interface placeholders remain,0 missing names across46 compiled original modules. Comprehensive Python regression passes in the prepared resource overlay. Remaining skipped header114; full client parity is incomplete. + +## 2026-10-06 pass14 — item sound and equipment request guards +- Ported original use/drop filename category state and selection, replacing2 item extension no-ops. Retain silent USE_POTION client use, separate native server-potion helper, bow/arrow/quiver, body/neck/ear, ability-up/talisman rules, missing-item suppression and selected-item retention. +- Inventory use/move and safebox/mall requests now call original sound paths before send. Equipment requests retain exchange/shop/attacking restrictions and original source-cell-only rule; CanAct suppresses sound/send. No new drop/pickup/use-to-item sounds. +- Independent24-category item-proto fixtures, generated WAV playback/cache evidence, source enum oracle and guarded packet/notification tests pass. macOS Debug and Android arm64 builds pass;13 targeted tests and comprehensive Python overlay regression pass. Nonvisual28/32 with four previous failures;681 static/642 compiled-interface placeholders remain.228 matching constants,925 unchanged references. GC114 remains skipped; full bone/effect/audio/device equivalence and full client parity remain incomplete. + +## 2026-10-07 pass15 — item database and resource data +- Removed7 fabricated item records, automatic item_names/list reads, inferred list-column types and hardcoded model fallbacks. Ported native original item-list/description loaders and ordered prototype icon fallback; selected/unloaded state, text/model/description/socket overwrites, failure retention and prototype sizes now follow AVA2. +- Icon pixels no longer determine item grid size. Missing selected data raises; missing image returns Noname. Configured decoded-root image lookup and logical resource filenames now agree with the item loader instead of relying solely on process cwd. +- Independent literal proto/TGA/list/description fixtures and related15 targeted tests pass. macOS Debug/Android arm64 builds and comprehensive Python overlay regression pass.925 immutable references unchanged;681 static/642 compiled-interface placeholders remain. Final nonvisual29/33 has the same four previously documented failures.228 protocol constants match. Full app.LoadLocaleData integration, complete resource/render lifecycle and full client parity remain pending. + +## 2026-10-07 pass16 — locale data coordinator +- app.LoadLocaleData now follows the original LoadLocaleData order, Destroy calls, fatal/non-fatal steps and integer result (item list/proto/desc, mob_proto, SkillDesc/SkillTable, pet_skill, insult, npc_wear, mob_scale, item_scale). Previously it was a no-op, so in-game item/mob/skill/pet data never loaded through the original path. +- petskill module + RegisterSkillPet, CInsultChecker with net.LoadInsultList/IsInsultIn/IsChatInsultIn and the received-chat '*' filter, LoadMobScale, LoadNPCWear and LoadItemScale ported as data stores. +- Not yet consumed: NPC wear/item scale renderer paths, CPythonWiki::ReadData; YMIR cvt tables intentionally skipped (EUROPE). +- macOS Debug/Android arm64 builds and comprehensive Python overlay regression pass. Nonvisual 29/33 (render_3d excluded: timeout) with the four existing failures; 228 constants, 925 references unchanged, compiled-interface placeholders 642 -> 634. + +## 2026-10-07 pass17 — GC114 effects, name colours, NPC wear, wiki, receive buffer +- GC114 special/specific effects, the CInstanceBase effect table, bone/root attached effects and emoticons (1000 ms gate) are ported. The player-settings effect/emoticon/sound tables (236/12) are registered at app.Create, and the chrmgr effect/emoticon/name-colour bindings are no longer stubs. Name colours follow PVP/DUEL/GVG/party/empire mode, and text tails refresh on those events. +- NPC wear is applied in AppendActor, using the Warp map name only, with no weapon/hair/sash for non-PCs. The sash keeps its refine effect (251) and item_scale row. chr.RaceToJob/RaceToSex, app text-file line APIs and the atof-style EffectData parser (Bezier control points) now match Windows. +- CPythonWiki + CTextFileLoader are ported: ReadData (refine/item_proto/special_item_group/mob_drop_item), LoadMonster/ListReverse and all 22 methods, including the Windows IsBlackList argument bug. The output matches the real locale/common data. +- The 128 KB game receive buffer now applies back-pressure, as Windows CNetworkStream does, instead of failing. DWORD-size packets frame by WORD in both clients. +- Results: + - macOS/Android builds pass, and the comprehensive Python overlay regression passes. + - Nonvisual CTest is 29/33 (render_3d excluded: timeout). + - 229 constants match, and the 925 references are unchanged. + - Compiled-interface placeholders went from 634 to 618. +- Remaining: + - Sash/NPC-wear mesh attachment and the item-scale renderer. + - Fly/race-motion settings and HAIR_COLOR_ENABLE. + - Wiki: MIPT/unordered order/OOB differences. + - Resource/audio lifetimes, device/server equivalence and render_3d. + +## 2026-10-07 pass18 — race/shape/hair/weapon/sash model mounting +- The fake race/weapon/hair path helpers are gone. CRaceData/CRaceManager (.msm shape/hair/skins, bones, npclist, motlist) are ported, and app.Create loads npclist plus the eight player races. +- CInstanceBase::Create/ChangeArmor/ChangeWeapon/ChangeHair/SetSash order and gates now match Windows: the NPC-wear path, the PC-only parts, `!IsPC && race > 8`, animal-wear/wedding-dress weapons, ArmorVnumToShape and m_awPart. CActorInstance AttachWeapon follows the hand rules (dagger/bow/fan) and keeps stale slots, as Windows does. AttachSash uses `Bip01 Spine2` with its own motion and the sash-only item_scale. app.SetHairColorEnable/SetArmorSpecularEnable are wired, and weapon effects use the race bones. +- Results: + - macOS/Android builds pass, and the Python regression passes with real-asset mount assertions. + - CTest is 29/33 (render_3d excluded: timeout). + - The 229 constants and 925 references are unchanged, and interfaces are 618/46/0. +- Remaining: + - Most AVA2 gr2 are BitKnit-compressed, which libgr2 cannot decode, so the meshes do not draw yet. + - Specular/LOD/trace/refine/shining are not ported. + - The bow motion mode, PC motion registration, tree races and the chr preview path table. + +## 2026-10-07 pass19 — BitKnit2 gr2 decompression +- Granny 2.11 format 4 is BitKnit2, not BitKnit. libgr2 now decodes it (`shared/gr2/src/bitknit2.cpp`, MIT provenance BG3ModStudio, cross-checked against ooz), including the compressed pointer-fixup tables. +- Results: + - All 6406 BitKnit2 gr2 in the AVA2 pack tree load, with 10833 sane meshes. + - The warrior shape/hair/weapon/sash now draw with the .msm skins applied (python_test asserts this). + - macOS/Android builds pass. + - CTest is 29/33 (render_3d excluded: timeout). + - The 229 constants and 925 references are unchanged, and interfaces are 618/46/0. +- Remaining: + - 156 64-bit/big-endian gr2 are still rejected. + - Oodle0 and BitKnit v1 are unimplemented (no AVA2 samples). + +## 2026-10-07 pass20 — 64-bit gr2 + curve2 animation curves +- **64-bit gr2.** libgr2 now loads 64-bit little-endian Granny files. Only pointer slots inside section data are 8 bytes, which changes the type-def entry size, member sizes and in-member offsets. All 156 previously rejected AVA2 files load (plechi_* zones/bosses, shadow_dragon, some weapons). +- **curve2 animation.** Granny 2.11 `curve2` animation curves are decoded: constants, float and keyframe splines, K16u/K8u quantised curves, and D4n compressed quaternions (19 variants, all 17 used by AVA2). They cover 3111 32-bit and all 59 64-bit animation files, which previously left the compressed bones at bind pose. +- **Results:** + - 16725/16725 gr2 load. + - Decoded quaternions are unit length and their bind-angle distribution matches the float curves. + - python_test asserts that shadow_dragon run animates. + - macOS/Android builds pass. + - CTest is 29/33 (render_3d excluded: timeout). + - The 229 constants and 925 references are unchanged, and interfaces are 618/46/0. +- **Remaining:** + - Big-endian, Oodle0 and BitKnit v1 (0 samples). + - Keyframe curves step per TimeStep. + - No render_3d visual check. + +## 2026-10-07 pass21 — render_3d timeout +- **Cause.** The software renderer `Gr2SceneRenderer::RenderDraw` had a leftover outer per-triangle loop, so each mesh was rasterised `num_tris` times (O(n²)). This took about 11–26 s per frame and 126 s per test run. It also over-composited blended and additive draws. That loop has been removed. The Windows client draws through D3D, so the GPU path was never affected. +- **Environment.** `tools/make_test_rundir.py` builds a merged client-root run directory. `AVA2_TEST_RUNDIR` and `AVA2_PACK_MAKER` replace the `/Users/shen` paths. When the assets are missing, the test is skipped (exit 77). +- **Results:** + - render_3d takes 2.3 s under CTest's 15 s timeout. + - Full CTest is 30/34, with the same four environment failures. + - python_test passes, and the macOS/Android builds pass. + - The 229 constants and 925 references are unchanged, and interfaces are 618/46/0. + +## 2026-10-07 pass22 — the four environment test failures +- **Parity fix.** `PyTuple_GetPointer` used to fail on any pending Python error. ScriptLib `Py_BuildException("msg")` leaves an error set while returning None, so after a missing image every later wndMgr handle lookup returned None (NewGoldWindow `board.GetWidth()` → None). Windows `PyTuple_GetInteger` ignores pending errors. The helper now preserves the earlier error and checks only its own conversion. +- **Environment.** `tools/make_test_rundir.py` now builds the client root from the `*_create.xml` ArchivedPath manifests (python-root first; then PC, ETC, root and the rest; first wins), plus `map`, `mark` and `svside`. ava2.python, window_tree, render_3d and mark_manager all run from `AVA2_TEST_RUNDIR` and skip (77) without it. The speedtree_forest wind test now samples the highest canopy vertex instead of the bottom one. +- **Results:** + - CTest is 34/34. + - python_test passes, and the macOS/Android builds pass. + - The 229 constants and 925 references are unchanged, and interfaces are 618/46/0. + +## 2026-10-07 pass23 — event module and simple lookups +- **event.** This is a line-by-line port of CPythonEventManager plus script::Group (`src/python_event_manager.cpp`, `src/eter_lib/parser.cpp`). + - All original methods are registered, including AddEvent; GetTotalLineCount is not, as in the original. + - The button constants are fixed to NEXT/DONE/CANCEL = 0/1/2. The old placeholder had CANCEL=0 and NEXT=2. + - The script packet now runs the real event set and opens the quest window through `OpenQuestWindow`. + - SelectAnswer and QuestButtonClick send CG 29 and CG 66. + - The quirks are kept: the elapsed time is subtracted twice, and the DWORD confirm-wait time goes negative after it expires. +- **Lookups:** + - item.GetApplyPoint uses aApplyInfo, generated from the original. + - player.SlotTypeToInvenType. + - app.GetRandom uses the EterBase Park–Miller generator. + - nonplayer.GetResist. + - player GetGuildID/GetGuildName/GetPKMode/IsGameMaster/GetRace/GetJob/GetEXP/GetConquerorEXP/Get/SetPlayTime. +- **Still different:** + - GetTargetVID: there is no target system yet. + - Event camera and minimap atlas signals have no effect. + - There are no real font metrics. + - Apply types 176–179 return 0 (Windows reads out of bounds). + - CheckStackReference is not ported. +- **Results:** + - CTest is 35/35, including the new ava2.event. + - python_test passes, and the macOS/Android builds pass. + - The 229 constants and 925 references are unchanged. + - Interfaces are 590/46/0 (was 618), and the inventory has 629 placeholder bindings (was 657). + +## 2026-10-07 pass24 — chat module +- **chat.** This is a line-by-line port of CPythonChat and CWhisper (`src/python_chat.cpp`), using the __CHAT_SETTINGS__ and ENABLE_MULTILANGUAGE_SYSTEM build. + - All 33 original methods replace the placeholders. + - It has per-set line stores keyed by BYTE, and per-set mode and country filters. + - It ports the 300-line cap, the `#ebvs` drop, item-link renaming, the SHOUT lang/empire prefixes with flag images, and the VIEW/EDIT/LOG board updates. + - It also ports delayed chat, whispers, the ignore set and GetLinkFromHyperlink. +- **Server path.** RecvChatPacket now calls `CPythonChat::AppendChat`, as on Windows. The temporary chat callback is removed. +- **Quirks kept:** + - IsIgnoreCharacter returns None. + - CreateChatSet(256) aliases set 0's store. + - Country-muted shouts still count toward the window size. + - Update on an unknown set skips the delayed flush. +- **Guards where Windows has undefined behaviour:** + - A zero step. + - Out-of-range mode indexes. + - A hyperlink with no ':' or an odd attribute count. + - A whisper position above 1.0. + - The uninitialised whisper lineCount. +- **Still different:** + - There are no real fonts: no missing-font drop, no GM italic font, and no whisper clip rectangle. + - Flag images are looked up without IsFileExist. + - CheckStackReference, ChangeIcon and AppendMonsterList are not ported. +- **Results:** + - CTest is 36/36, including the new ava2.chat. + - python_test passes, and the macOS/Android builds pass. + - The 229 constants and 925 references are unchanged. + - Interfaces are 557/46/0 (was 590), and the inventory has 596 placeholder bindings (was 629). +## 2026-10-07 pass25 — systemSetting, skill, miniMap, chr/chrmgr +- **systemSetting.** CPythonSystem + all 58 module methods: metin2.cfg/interface.cfg formats, display modes, SetConfig/GetConfig. +- **skill.** The 21 PythonSkill.cpp methods: RegisterSkill files, skilldesc icon paths, requirement data, icon images/instances, GetGradeData, TEST. +- **miniMap.** CPythonMiniMap (`src/python_minimap.cpp`) + the 27 module functions; LoadAtlas, point marks, Update, observers, targets, guild areas, way/signal points, GetInfo/GetAtlasInfo. RegisterColor (not in Windows) removed. +- **chr / chrmgr.** `src/python_chr.cpp` ports all 80 chr and 37 chrmgr methods onto NetworkActorManager/RaceManager; the stand-in instance table is gone. Original error styles, rotation conversions, CreateInstance's "y" bug, no-instance answers, GetVIDInfo format and SetPathName guard are kept. chr.RequestPetName is absent (NEW_PET_SYSTEM off). +- **Still different:** + - systemSetting: no shadow/gamma/cursor/mob-info refresh; SDL display modes; Android config path. + - skill: (None, 0) requirement quirk; emulated GetGradeData varargs; lazy icons; grpImage placeholder. + - miniMap: no rendering; no guild-area overlay, symbol download or target effect. + - chr: no pick pass, render modes, bounding spheres, weapon trace, horse actor, motion blending, fade-out or dead list; Hide/Show use a flag; SetDirection null guard; testSetRideMan VID 1. +- **Results:** + - CTest is 40/40 (new ava2.system_setting, ava2.skill, ava2.minimap, ava2.chr). + - python_test passes, and the macOS/Android builds pass. + - The 229 constants and 925 references are unchanged. + - Interfaces are 370/46/0 (was 557), and the inventory has 402 placeholder bindings (was 596). diff --git a/shared/common/PortPythonPointer.h b/shared/common/PortPythonPointer.h index 8368e6e5..5fd0bb10 100644 --- a/shared/common/PortPythonPointer.h +++ b/shared/common/PortPythonPointer.h @@ -18,8 +18,17 @@ bool PyTuple_GetPointer(PyObject* args, int position, T** out) PyObject* value = PyTuple_GetItem(args, position); if (!value) return false; + // A ScriptLib call may leave an error set while returning None (Py_BuildException with a + // message, e.g. a missing image). AVA2 ScriptLib PyTuple_GetInteger ignores that stale error, so + // only judge this conversion and leave the earlier error as it was. + PyObject *type, *error, *traceback; + PyErr_Fetch(&type, &error, &traceback); void* pointer = PyLong_AsVoidPtr(value); - if (PyErr_Occurred()) + const bool failed = PyErr_Occurred() != nullptr; + if (failed) + PyErr_Clear(); + PyErr_Restore(type, error, traceback); + if (failed) return false; *out = static_cast(pointer); return true; diff --git a/shared/gr2/CMakeLists.txt b/shared/gr2/CMakeLists.txt index a0a0d7da..41565803 100644 --- a/shared/gr2/CMakeLists.txt +++ b/shared/gr2/CMakeLists.txt @@ -3,6 +3,7 @@ add_library(libgr2 STATIC src/gr2_file.cpp # T1 header + section table + fixup src/gr2_decompress.cpp # T2 section 解压分派 src/oodle1.c # T2 Granny Oodle1 解码(端口自泄露 SDK) + src/bitknit2.cpp # T2 Granny BitKnit2 解码(MIT,BG3ModStudio) src/gr2_typetree.cpp # T3 自描述类型树遍历 src/gr2_fileinfo.cpp # T4 FileInfo 汇总 src/gr2_skeleton.cpp # T5 骨架 + bind pose 自洽检查 diff --git a/shared/gr2/README.md b/shared/gr2/README.md index 284aaf78..ecdc4a4a 100644 --- a/shared/gr2/README.md +++ b/shared/gr2/README.md @@ -5,7 +5,9 @@ ## 能做什么 - 容器:magic / header / section / pointer-fixup(懒解引用,不物化 32 位指针) -- section 解压:Oodle1(`oodle1.c`) +- section 解压:Oodle1(`oodle1.c`)、BitKnit2(`bitknit2.cpp`,Granny 2.11 `Format==4`,含压缩的 fixup 表) +- 32 / 64 位 little-endian(64 位只是 section 数据里的指针宽 8 字节;header / section 表 / fixup 同 32 位) +- 动画曲线:老式 `OldCurveType`(Granny 2.4)+ Granny 2.6+ `curve2` 的 19 种 `CurveData*` 变体(AVA2 语料出现的 17 种全覆盖)(常量 / 关键帧 / `K32f` / `K16u` / `K8u` 量化 / `D4n` 压缩四元数),统一解到 `Curve` 走 B 样条求值 - 自描述类型树遍历(不硬编码 struct 布局) - `FileInfo`:skeletons / meshes / materials / textures / models / animations - 骨架 + `granny_transform` → 4x4 组合(`BuildCompositeTransform4x4` 语义) @@ -26,14 +28,16 @@ |---|---|---| | **writer** | 无(设计上只读)| 大,PoC 不需要 | | Oodle0 解压(`Format==1`)| `decompress_status=1`,不崩 | 中,同族算法变体 | -| BitKnit 解压(`Format==4`)| `decompress_status=4`,不崩 | 大,无公开实现;退路:Windows 侧离线转未压缩 | -| 压缩曲线(`curve2` / `CurveData*` 变体)| `classify_curve` 标 `Identity`/`Unknown`,`read_old_curve` 跳过 | 中,`granny_curve.cpp` 各 `Da*` 分支 | +| BitKnit v1 解压(`Format==3`)| `decompress_status=3`,不崩(AVA2 语料 0 个;`Format==4` 是 BitKnit2,已支持)| 中,与 BitKnit2 同族 | | B 样条 degree ≥ 3 | `eval` 退化到 degree 2 | 小,加 `CubicCoefficients` | -| 64 位 / big-endian gr2 | `load` 直接拒(`only 32-bit little-endian`)| 中 | +| big-endian gr2 | `load` 直接拒(`big-endian Granny files not supported`;AVA2 语料 0 个)| 中,全部读取加字节序翻转 | | 多 skeleton 文件里刚体挂件的 skeleton 归属 | mesh binding 取「悬空最少」的 skeleton;`oracle_diff` 对这种 mesh 会误判(不是 libgr2 的问题)| 需要 FileInfo 暴露 per-model skeleton 索引 | ## ⚠ 许可 +`src/bitknit2.cpp` 依据 MIT 许可的 BG3ModStudio `LibLS/Bitknit2Decompressor.cpp`(© 2025 Thomas A. Rieck,https://github.com/trieck/BG3ModStudio)重写,并对照 powzix/ooz `bitknit.cpp`;不含 RAD 代码,可随 MIT 声明发布。 + + `src/oodle1.c` 是从泄露的 Granny SDK **直接端口**的解码路径(约 450 行)。 - **内部研究 / 不发布 / 非商用**:可用(和「拿泄露 SDK 当字节级规格」同一风险类别,全项目都这么做)。 diff --git a/shared/gr2/include/gr2/types.h b/shared/gr2/include/gr2/types.h index 1e3f3a79..ef60d2d1 100644 --- a/shared/gr2/include/gr2/types.h +++ b/shared/gr2/include/gr2/types.h @@ -94,7 +94,8 @@ struct Mesh { // ── 动画 ────────────────────────────────────────────────────────────── // 曲线子类型:T7a 分类。Metin2 = Granny 2.4,全是 OldCurveType(granny_curve.cpp): // {Int32 Degree; RefToArray Knots(Real32[]); RefToArray Controls(Real32[])} -// 无压缩变体。label 形如 "Old(d=2,dim=4)"。 +// label 形如 "Old(d=2,dim=4)"。AVA2 = Granny 2.11 的 curve2 变体 label 是去掉 +// "CurveDataHeader_" 的变体名(D4nK16uC15u、DaK32fC32f…),同样解到 Curve。 enum class CurveFormat { Keyframes32f, /* T7a 跑 fuzz 后补齐 */ Unknown }; // T7b:解出的曲线(B 样条:knots 时间轴 + controls 控制点,行优先 [knot][dim]) @@ -192,7 +193,7 @@ struct FileInfo { // ── section 表(T1,gr2dump --sections 用)──────────────────────────── struct SectionInfo { - uint32_t compression; // 0=none 1/2=Oodle0/1 4=BitKnit + uint32_t compression; // 0=none 1/2=Oodle0/1 3=BitKnit 4=BitKnit2 uint32_t data_size; // 压缩后 uint32_t expanded_size; // 展开后 uint32_t pointer_fixup_count; diff --git a/shared/gr2/src/bitknit2.cpp b/shared/gr2/src/bitknit2.cpp new file mode 100644 index 00000000..b37df5a6 --- /dev/null +++ b/shared/gr2/src/bitknit2.cpp @@ -0,0 +1,256 @@ +// Granny BitKnit2 decoder. Provenance and framing: see bitknit2.h +// (BG3ModStudio Bitknit2Decompressor.cpp, MIT, (c) 2025 Thomas A. Rieck; +// cross-checked against powzix/ooz bitknit.cpp). +#include "bitknit2.h" +#include +#include + +namespace gr2 { +namespace { + +constexpr uint16_t kMagic = 0x75B1; +constexpr size_t kQuantum = 65536; + +// Adaptive frequency model: N symbols over a 15-bit cumulative range, with a +// coarse residue->symbol lookup (residue >> SHIFT) and a rebuild every 1024 symbols. +template +struct Model { + uint16_t lookup[(0x8000u >> SHIFT) + 4]; + uint16_t cdf[N + 1]; + uint16_t freq[N]; + uint32_t adapt; + + void build_lookup() { + uint16_t* p = lookup; + for (unsigned i = 0; i < N; ++i) { + // cdf[i+1] >= 1 always holds (initial table and the smoothed rebuild + // are both strictly increasing), so the index never goes negative. + uint16_t* end = &lookup[(unsigned(cdf[i + 1]) - 1) >> SHIFT]; + do { + p[0] = p[1] = p[2] = p[3] = uint16_t(i); + p += 4; + } while (p <= end); + p = end + 1; + } + } + + void init_uniform() { + for (unsigned i = 0; i <= N; ++i) cdf[i] = uint16_t(0x8000u * i / N); + reset(); + } + + void reset() { + for (auto& f : freq) f = 1; + adapt = 1024; + build_lookup(); + } + + void rebuild(unsigned sym) { + adapt = 1024; + freq[sym] = uint16_t(freq[sym] + BOOST); + uint32_t sum = 0; + for (unsigned i = 0; i < N; ++i) { + sum += freq[i]; + freq[i] = 1; + cdf[i + 1] = uint16_t(cdf[i + 1] + ((sum - cdf[i + 1]) >> 1)); + } + build_lookup(); + } + + unsigned decode(uint32_t& state) { + const uint32_t residue = state & 0x7FFFu; + unsigned sym = lookup[residue >> SHIFT]; + while (sym < N - 1 && residue >= cdf[sym + 1]) ++sym; + const uint32_t lo = cdf[sym]; + state = (state >> 15) * (uint32_t(cdf[sym + 1]) - lo) + (residue - lo); + freq[sym] = uint16_t(freq[sym] + 31); + if (--adapt == 0) rebuild(sym); + return sym; + } +}; + +using LiteralModel = Model<300, 6, 725>; +using DistLsbModel = Model<40, 9, 985>; +using DistBitsModel = Model<21, 9, 1004>; + +struct Decoder { + const uint8_t* src; + const uint8_t* src_end; + uint8_t* dst_start; + uint8_t* dst; + uint8_t* dst_end; + + uint32_t state1 = 0, state2 = 0; + uint32_t last_dist = 1; + uint32_t recent[8] = {1, 1, 1, 1, 1, 1, 1, 1}; + uint32_t recent_mask = (7u << 21) | (6u << 18) | (5u << 15) | (4u << 12) | + (3u << 9) | (2u << 6) | (1u << 3) | 0u; + + LiteralModel lit[4]; + DistLsbModel lsb[4]; + DistBitsModel bits; + + bool read16(uint32_t& v) { + if (src_end - src < 2) return false; + v = uint32_t(src[0]) | (uint32_t(src[1]) << 8); + src += 2; + return true; + } + + // Pull 16 bits into state1 if it dropped below the rANS floor, then swap + // the two interleaved states. + bool renorm() { + if (state1 < 0x10000) { + uint32_t w; + if (!read16(w)) return false; + state1 = (state1 << 16) | w; + } + const uint32_t t = state1; + state1 = state2; + state2 = t; + return true; + } + + bool quantum_header() { + uint32_t lo, hi; + if (!read16(lo) || !read16(hi)) return false; + // The u32 is stored as [low16][high16]; the fields assume [high16][low16]. + const uint32_t v = (lo << 16) | hi; + if (v < 0x10000) return false; + uint32_t a = v >> 4; + const uint32_t n = v & 0xF; + uint32_t w; + if (a < 0x10000) { + if (!read16(w)) return false; + a = (a << 16) | w; + } + uint32_t s1 = a >> n; + if (s1 < 0x10000) { + if (!read16(w)) return false; + s1 = (s1 << 16) | w; + } + if (!read16(w)) return false; + a = (a << 16) | w; + const uint32_t top = 1u << (n + 16); + state1 = s1; + state2 = top | (a & (top - 1)); + return true; + } + + bool decode_quantum(uint8_t* q_end) { + if (!quantum_header()) return false; + + if (dst == dst_start) { // no previous byte to delta against + *dst++ = uint8_t(state1); + state1 >>= 8; + if (!renorm()) return false; + } + + while (dst < q_end) { + unsigned sym = lit[size_t(dst - dst_start) & 3].decode(state1); + if (!renorm()) return false; + if (sym < 256) { + // last_dist <= bytes produced: it is 1 here only after the first + // byte, and every later value passed the match-distance check. + *dst = uint8_t(sym + dst[-ptrdiff_t(last_dist)]); + ++dst; + if (dst >= q_end) break; + sym = lit[size_t(dst - dst_start) & 3].decode(state1); + if (!renorm()) return false; + if (sym < 256) { + *dst = uint8_t(sym + dst[-ptrdiff_t(last_dist)]); + ++dst; + continue; + } + } + + if (sym >= 288) { // long copy length: 1..12 extra bits + const unsigned nb = sym - 287; + sym = (state1 & ((1u << nb) - 1)) + (1u << nb) + 286; + state1 >>= nb; + if (!renorm()) return false; + } + const uint32_t copy_len = sym - 254; + + const unsigned dsym = lsb[size_t(dst - dst_start) & 3].decode(state1); + if (!renorm()) return false; + + uint32_t dist; + if (dsym >= 8) { // explicit distance + const unsigned nb = bits.decode(state1); + if (!renorm()) return false; + dist = state1 & ((1u << (nb & 0xF)) - 1); + state1 >>= (nb & 0xF); + if (!renorm()) return false; + if (nb >= 0x10) { + uint32_t w; + if (!read16(w)) return false; + dist = (dist << 16) | w; + } + dist = (32u << nb) + (dist << 5) + dsym - 39; + recent[(recent_mask >> 21) & 7] = recent[(recent_mask >> 18) & 7]; + recent[(recent_mask >> 18) & 7] = dist; + } else { // recent-distance cache hit: move to front + const unsigned shift = 3 * dsym; + const uint32_t idx = (recent_mask >> shift) & 7; + const uint32_t mask = ~7u << shift; + dist = recent[idx]; + recent_mask = (recent_mask & mask) | ((idx + 8 * recent_mask) & ~mask); + } + + if (dist == 0 || dist > size_t(dst - dst_start)) return false; + if (copy_len > size_t(dst_end - dst)) return false; + const uint8_t* from = dst - dist; + for (uint32_t i = 0; i < copy_len; ++i) dst[i] = from[i]; // overlapping copy + dst += copy_len; + last_dist = dist; + } + + // A well-formed quantum leaves both states at the rANS floor. + return state1 == 0x10000 && state2 == 0x10000; + } + + bool run() { + uint32_t magic; + if (!read16(magic) || magic != kMagic) return false; + while (dst < dst_end) { + const size_t q_start = size_t(dst - dst_start) & ~(kQuantum - 1); + const size_t total = size_t(dst_end - dst_start); + uint8_t* q_end = dst_start + (total - q_start < kQuantum ? total : q_start + kQuantum); + if (src_end - src < 2) return false; + if (src[0] == 0 && src[1] == 0) { // stored quantum + src += 2; + const size_t n = size_t(q_end - dst); + if (size_t(src_end - src) < n) return false; + std::memcpy(dst, src, n); + dst += n; + src += n; + } else if (!decode_quantum(q_end)) { + return false; + } + } + return true; + } +}; + +} // namespace + +bool bitknit2_decompress(const uint8_t* src, size_t src_size, uint8_t* dst, size_t dst_size) { + if (!src || !dst || dst_size == 0) return false; + auto d = std::make_unique(); + d->src = src; + d->src_end = src + src_size; + d->dst_start = d->dst = dst; + d->dst_end = dst + dst_size; + for (auto& m : d->lit) { + // 264 regular symbols share the range; the 36 long-length symbols get one unit each. + for (unsigned i = 0; i < 264; ++i) m.cdf[i] = uint16_t((0x8000u - 300 + 264) * i / 264); + for (unsigned i = 264; i <= 300; ++i) m.cdf[i] = uint16_t(0x8000u - 300 + i); + m.reset(); + } + for (auto& m : d->lsb) m.init_uniform(); + d->bits.init_uniform(); + return d->run(); +} + +} // namespace gr2 diff --git a/shared/gr2/src/bitknit2.h b/shared/gr2/src/bitknit2.h new file mode 100644 index 00000000..d3137db8 --- /dev/null +++ b/shared/gr2/src/bitknit2.h @@ -0,0 +1,37 @@ +// Granny "BitKnit2" (granny_compression_type 4, Granny 2.11+) decoder. +// +// Provenance: decode path re-implemented from the MIT-licensed BG3ModStudio +// LibLS/Bitknit2Decompressor.cpp (c) 2025 Thomas A. Rieck, +// https://github.com/trieck/BG3ModStudio, cross-checked against the BitKnit +// core of powzix/ooz bitknit.cpp (https://github.com/powzix/ooz). +// Granny framing: u16 magic 0x75B1, then one 64 KB quantum after another +// (u16 0 = stored quantum, otherwise a rANS quantum header). +// +// BG3ModStudio notice (applies to the algorithm this file set derives from): +// Copyright (c) 2025 Thomas A. Rieck +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#pragma once +#include +#include + +namespace gr2 { + +// Decompresses exactly dst_size bytes. Every read and write is bounds-checked. +// Returns false on a malformed or truncated stream. +bool bitknit2_decompress(const uint8_t* src, size_t src_size, uint8_t* dst, size_t dst_size); + +} // namespace gr2 diff --git a/shared/gr2/src/gr2_anim.cpp b/shared/gr2/src/gr2_anim.cpp index 211a3834..5a0e427b 100644 --- a/shared/gr2/src/gr2_anim.cpp +++ b/shared/gr2/src/gr2_anim.cpp @@ -86,6 +86,233 @@ void File::Impl::read_old_curve(Ref curve_obj, Ref curve_type, Curve& out) { for (float v : out.controls) if (!std::isfinite(v)) { out.dim = 0; return; } } +// ── curve2 压缩曲线(Granny 2.6+,AVA2 = 2.11)──────────────────────── +// curve2{VariantRef CurveData},CurveData 对象都以 inline CurveDataHeader{u8 Format; u8 Degree} +// 开头。各变体统一解成 knots + float controls,求值仍走下面的 Curve::eval(B 样条)。 +// 变体字段名来自文件自带的 type tree(CurveData*Type),反量化公式与 D4n 四元数表参照 +// MIT 许可的 LSLib(Norbyte,https://github.com/Norbyte/lslib)GR2 CurveData 实现重写, +// 未拷贝其代码;用 AVA2 全库 60 万条 curve2 校验(单位四元数、knot 末端 ≈ Duration)。 +// 成员一律按名字找,不硬编码偏移。 +// Da* dimension 来自数据(ControlScaleOffsets/2,或 Controls/Knots) +// D3* / D4n* 固定 3 / 4 维;D3I1 = 一个标量映射到 3 维;D9I1 / D9I3 = 3x3 对角 +// *K16u/*K8u 量化 knot:knot = k / OneOverKnotScale,OneOverKnotScaleTrunc 是 f32 的高 16 位 +// D4nK16uC15u / D4nK8uC7u:每个 knot 3 个分量 + 2 位 swizzle + 符号位,第 4 分量 = sqrt(1-Σ²) +namespace { +const float kQuatScale[16] = { + 1.4142135f, 0.70710677f, 0.35355338f, 0.35355338f, 0.35355338f, 0.17677669f, 0.17677669f, 0.17677669f, + -1.4142135f, -0.70710677f, -0.35355338f, -0.35355338f, -0.35355338f, -0.17677669f, -0.17677669f, -0.17677669f}; +const float kQuatOffset[16] = { + -0.70710677f, -0.35355338f, -0.53033006f, -0.17677669f, 0.17677669f, -0.17677669f, -0.088388346f, 0.0f, + 0.70710677f, 0.35355338f, 0.53033006f, 0.17677669f, -0.17677669f, 0.17677669f, 0.088388346f, -0.0f}; + +float trunc_to_f32(uint16_t hi) { + const uint32_t bits = uint32_t(hi) << 16; + float f; std::memcpy(&f, &bits, 4); + return f; +} +} // namespace + +void File::Impl::read_curve2(Ref curve_obj, Ref curve_type, float keyframe_dt, Curve& out) { + if (!curve_obj.valid() || !curve_type.valid()) return; + const auto& cms = parse_type(curve_type); + if (cms.empty() || cms[0].name != "CurveData") return; + const Ref vslot = member_slot(curve_obj, cms[0]); + const Ref dtype = follow(vslot); + const Ref dobj = follow({vslot.section, vslot.offset + ptr}); + if (!dtype.valid() || !dobj.valid()) return; // DaIdentity 之外的空 variant → identity + const auto& ms = parse_type(dtype); + if (ms.empty()) return; + const char* pfx = "CurveDataHeader_"; + if (ms[0].name.rfind(pfx, 0) != 0) return; + const std::string v = ms[0].name.substr(std::strlen(pfx)); + + const uint8_t* hdr = at(dobj, 2); + if (!hdr) return; + const int32_t degree = hdr[1]; + + auto mem = [&](const char* n) { return find_member(ms, n); }; + auto f32 = [&](const char* n, uint32_t i) -> float { + const TypeMember* m = mem(n); + if (!m) return 0.0f; + return rd_f32({dobj.section, dobj.offset + m->offset + i * 4u}); + }; + auto u16m = [&](const char* n, uint16_t& o) -> bool { + const TypeMember* m = mem(n); + const uint8_t* p = m ? at(member_slot(dobj, *m), 2) : nullptr; + if (!p) return false; + o = uint16_t(p[0] | (p[1] << 8)); + return true; + }; + // RefToArray {int32 count; ptr data} + auto arr = [&](const char* n, uint32_t esz, uint32_t& cnt) -> const uint8_t* { + cnt = 0; + const TypeMember* m = mem(n); + if (!m) return nullptr; + const Ref slot = member_slot(dobj, *m); + const int32_t c = rd_i32(slot); + if (c <= 0 || c > (1 << 24)) return nullptr; + const uint8_t* p = at(follow({slot.section, slot.offset + 4}), size_t(c) * esz); + if (p) cnt = uint32_t(c); + return p; + }; + auto rf = [](const uint8_t* p, size_t i) { float f; std::memcpy(&f, p + i * 4, 4); return f; }; + auto ru = [](const uint8_t* p, size_t i, uint32_t esz) -> uint32_t { + return esz == 1 ? p[i] : uint32_t(p[i * 2] | (p[i * 2 + 1] << 8)); + }; + + auto finish = [&](uint32_t dim) { + out.degree = degree; + out.dim = dim; + out.knots_sorted = std::is_sorted(out.knots.begin(), out.knots.end()); + if (out.knots.empty() || out.controls.size() != out.knots.size() * dim) { out = Curve{}; return; } + for (float x : out.knots) if (!std::isfinite(x)) { out = Curve{}; return; } + for (float x : out.controls) if (!std::isfinite(x)) { out = Curve{}; return; } + }; + + if (v == "DaIdentity") return; // 调用方取单位分量 + + if (v == "DaConstant32f" || v == "D3Constant32f" || v == "D4Constant32f") { + if (v == "DaConstant32f") { + uint32_t n = 0; + const uint8_t* p = arr("Controls", 4, n); + if (!p) return; + for (uint32_t i = 0; i < n; ++i) out.controls.push_back(rf(p, i)); + } else { + const uint32_t n = v[1] == '3' ? 3 : 4; + if (!mem("Controls")) return; + for (uint32_t i = 0; i < n; ++i) out.controls.push_back(f32("Controls", i)); + } + out.knots = {0.0f}; + finish(uint32_t(out.controls.size())); + out.degree = 0; + return; + } + + if (v == "DaK32fC32f") { + uint32_t nk = 0, nc = 0; + const uint8_t* pk = arr("Knots", 4, nk); + const uint8_t* pc = arr("Controls", 4, nc); + if (!pk || !pc || nc % nk) return; // 0 knot = 导出器写的空曲线 → identity + for (uint32_t i = 0; i < nk; ++i) out.knots.push_back(rf(pk, i)); + for (uint32_t i = 0; i < nc; ++i) out.controls.push_back(rf(pc, i)); + return finish(nc / nk); + } + + if (v == "DaKeyframes32f") { + // 关键帧:knot 不存,第 i 帧在 i*TimeStep(AVA2 全库 19045 条都满足 N-1 == Duration/TimeStep)。 + // Degree 0 = 逐帧保持,见 Curve::eval。 + uint16_t dim16 = 0; + uint32_t nc = 0; + const uint8_t* pc = arr("Controls", 4, nc); + if (!u16m("Dimension", dim16) || dim16 == 0 || !pc || nc % dim16) return; + for (uint32_t i = 0; i < nc / dim16; ++i) out.knots.push_back(float(i) * keyframe_dt); + for (uint32_t i = 0; i < nc; ++i) out.controls.push_back(rf(pc, i)); + return finish(dim16); + } + + // 其余都是量化 knot + KnotsControls 一块数组:先 N 个 knot,再 N*每knot分量数 个 control。 + const bool k8 = v.find("K8u") != std::string::npos; + const bool k32 = v.find("K32f") != std::string::npos; + const uint32_t esz = k32 ? 4 : (k8 ? 1 : 2); + uint32_t total = 0; + const uint8_t* kc = arr("KnotsControls", esz, total); + if (!kc) return; + float one_over_knot_scale = 1.0f; + if (!k32) { + uint16_t trunc = 0; + if (u16m("OneOverKnotScaleTrunc", trunc)) one_over_knot_scale = trunc_to_f32(trunc); + else if (mem("OneOverKnotScale")) one_over_knot_scale = f32("OneOverKnotScale", 0); + else return; + if (!(one_over_knot_scale != 0.0f) || !std::isfinite(one_over_knot_scale)) return; + } + auto knot = [&](uint32_t i) { + return k32 ? rf(kc, i) : float(ru(kc, i, esz)) / one_over_knot_scale; + }; + auto ctl = [&](uint32_t i) { return k32 ? rf(kc, i) : float(ru(kc, i, esz)); }; + + if (v == "D4nK16uC15u" || v == "D4nK8uC7u") { + if (total % 4) return; + const uint32_t n = total / 4; + uint16_t sel = 0; + if (!u16m("ScaleOffsetTableEntries", sel)) return; + const float unit = k8 ? (1.0f / 127.0f) : (1.0f / 32767.0f); + float sc[4], of[4]; + for (int i = 0; i < 4; ++i) { + sc[i] = kQuatScale[(sel >> (4 * i)) & 0xF] * unit; + of[i] = kQuatOffset[(sel >> (4 * i)) & 0xF]; + } + const uint32_t sign = k8 ? 0x80u : 0x8000u, mask = sign - 1, sh = k8 ? 7 : 15; + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n; ++i) { + const uint32_t a = ru(kc, n + i * 3 + 0, esz); + const uint32_t b = ru(kc, n + i * 3 + 1, esz); + const uint32_t c = ru(kc, n + i * 3 + 2, esz); + const uint32_t s1 = (((b & sign) >> sh) << 1) | ((c & sign) >> sh); // 被省略的分量 + const uint32_t s2 = (s1 + 1) & 3, s3 = (s2 + 1) & 3, s4 = (s3 + 1) & 3; + float q[4]; + q[s2] = float(a & mask) * sc[s2] + of[s2]; + q[s3] = float(b & mask) * sc[s3] + of[s3]; + q[s4] = float(c & mask) * sc[s4] + of[s4]; + const float r = 1.0f - (q[s2] * q[s2] + q[s3] * q[s3] + q[s4] * q[s4]); + q[s1] = std::sqrt(r > 0.0f ? r : 0.0f); + if (a & sign) q[s1] = -q[s1]; + out.controls.insert(out.controls.end(), q, q + 4); + } + return finish(4); + } + + if (v == "D3K16uC16u" || v == "D3K8uC8u") { + if (total % 4) return; + const uint32_t n = total / 4; + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n * 3; ++i) + out.controls.push_back(ctl(n + i) * f32("ControlScales", i % 3) + f32("ControlOffsets", i % 3)); + return finish(3); + } + + if (v == "D3I1K16uC16u" || v == "D3I1K8uC8u" || v == "D3I1K32fC32f") { + if (total % 2) return; + const uint32_t n = total / 2; + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n; ++i) + for (uint32_t d = 0; d < 3; ++d) + out.controls.push_back(ctl(n + i) * f32("ControlScales", d) + f32("ControlOffsets", d)); + return finish(3); + } + + if (v == "D9I1K16uC16u" || v == "D9I1K8uC8u" || v == "D9I3K16uC16u" || v == "D9I3K8uC8u") { + const bool i3 = v[3] == '3'; + const uint32_t per = i3 ? 3 : 1; + if (total % (per + 1)) return; + const uint32_t n = total / (per + 1); + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n; ++i) { + float m[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; + for (uint32_t d = 0; d < 3; ++d) { + const uint32_t c = i3 ? d : 0; + m[d * 4] = i3 ? ctl(n + i * 3 + c) * f32("ControlScales", d) + f32("ControlOffsets", d) + : ctl(n + i) * f32("ControlScale", 0) + f32("ControlOffset", 0); + } + out.controls.insert(out.controls.end(), m, m + 9); + } + return finish(9); + } + + if (v == "DaK16uC16u" || v == "DaK8uC8u") { + uint32_t nso = 0; + const uint8_t* so = arr("ControlScaleOffsets", 4, nso); + if (!so || nso < 2 || nso % 2) return; + const uint32_t dim = nso / 2; + if (total % (dim + 1)) return; + const uint32_t n = total / (dim + 1); + for (uint32_t i = 0; i < n; ++i) out.knots.push_back(knot(i)); + for (uint32_t i = 0; i < n * dim; ++i) + out.controls.push_back(ctl(n + i) * rf(so, i % dim) + rf(so, dim + i % dim)); + return finish(dim); + } + ADBG("curve2 variant %s not decoded\n", v.c_str()); +} + // animation: {String Name; Real32 Duration; Real32 TimeStep; Real32 Oversampling; // ArrayOfRefs TrackGroups; ...} // track_group: {String Name; RefToArray VectorTracks; RefToArray TransformTracks; ...} @@ -187,14 +414,17 @@ bool File::Impl::extract_animation(Ref anim_obj, Ref anim_type, const Skeleton* if (mPos) { bt.pos_type = classify_curve_obj(member_slot(t, *mPos), mPos->ref_type); read_old_curve(member_slot(t, *mPos), mPos->ref_type, bt.position); + read_curve2(member_slot(t, *mPos), mPos->ref_type, out.time_step, bt.position); } if (mOri) { bt.rot_type = classify_curve_obj(member_slot(t, *mOri), mOri->ref_type); read_old_curve(member_slot(t, *mOri), mOri->ref_type, bt.orientation); + read_curve2(member_slot(t, *mOri), mOri->ref_type, out.time_step, bt.orientation); } if (mScl) { bt.scale_type = classify_curve_obj(member_slot(t, *mScl), mScl->ref_type); read_old_curve(member_slot(t, *mScl), mScl->ref_type, bt.scale_shear); + read_curve2(member_slot(t, *mScl), mScl->ref_type, out.time_step, bt.scale_shear); } if (skel) for (size_t k = 0; k < skel->bones.size(); ++k) if (skel->bones[k].name == bt.bone_name) { bt.bone_index = int32_t(k); break; } @@ -206,9 +436,10 @@ bool File::Impl::extract_animation(Ref anim_obj, Ref anim_type, const Skeleton* } // ── T7b:曲线解码 ───────────────────────────────────────────────────── -// Metin2 曲线全是 OldCurveType(B 样条:Degree + Knots[] + Controls[knot*dim])。 +// Metin2 曲线全是 OldCurveType(B 样条:Degree + Knots[] + Controls[knot*dim]); +// AVA2 的 curve2 变体由 read_curve2 解成同样的 knots/controls。 // 求值照 granny_bspline.cpp SampleBSpline{0,1,2}xN + granny_bspline_inlines.h -// {Linear,Quadratic}Coefficients。degree 0=常量,1=线性,2=二次 B 样条。 +// {Linear,Quadratic}Coefficients。degree 0=常量/阶梯,1=线性,2=二次 B 样条。 // KnotIndex = "第一个 > t 的 knot"(granny CurveFindKnot),窗口越界按端点 clamp。 // // dim==4(四元数):blend 之前对本 span 参与的 degree+1 个控制点做 @@ -223,10 +454,21 @@ void Curve::eval(float t, float* out) const { return knots[(uint32_t)i]; }; - if (n == 1 || degree <= 0) { // 常量 + if (n == 1) { // 常量 for (uint32_t d = 0; d < dim; ++d) out[d] = controls[d]; return; } + if (degree <= 0) { // 阶梯(granny SampleBSpline0:最后一个 <= t 的 knot) + uint32_t k = 0; + if (knots_sorted) { + const auto it = std::upper_bound(knots.begin(), knots.end(), t); + k = it == knots.begin() ? 0 : uint32_t(it - knots.begin()) - 1; + } else { + for (uint32_t j = 0; j < n; ++j) if (knots[j] <= t) k = j; + } + for (uint32_t d = 0; d < dim; ++d) out[d] = controls[k * dim + d]; + return; + } if (t <= knots[0]) t = knots[0]; if (t >= knots[n - 1]) t = knots[n - 1]; // 第一个 > t 的 knot(找不到 → n-1);升序时二分 diff --git a/shared/gr2/src/gr2_decompress.cpp b/shared/gr2/src/gr2_decompress.cpp index 9de5821f..3a1a4c74 100644 --- a/shared/gr2/src/gr2_decompress.cpp +++ b/shared/gr2/src/gr2_decompress.cpp @@ -1,6 +1,7 @@ // M0 T2 —— section 解压分派。见 docs/reference/steps/M0-gr2-reader.md #include "internal.h" #include "oodle1.h" +#include "bitknit2.h" #include namespace gr2 { @@ -44,10 +45,19 @@ bool File::Impl::decompress_section(const detail::GrnSection& s, const uint8_t* } return true; } - case 4: // BitKnit —— 无公开实现(全样本 0 个) - out.info.decompress_status = 4; - if (err) *err = {"section", "BitKnit unsupported (M0 T2)"}; + case 3: // BitKnit(v1)—— Granny 2.11 之前的旧格式,AVA2 语料未出现 + out.info.decompress_status = 3; + if (err) *err = {"section", "BitKnit (v1) not implemented"}; return false; + case 4: { // BitKnit2(Granny 2.11+;AVA2 pc/item 约 90% 的 gr2) + out.data.assign(s.expanded_data_size, 0); + if (!bitknit2_decompress(src, s.data_size, out.data.data(), out.data.size())) { + out.info.decompress_status = 4; + if (err) *err = {"section", "BitKnit2 decompress failed"}; + return false; + } + return true; + } default: out.info.decompress_status = -1; if (err) *err = {"section", "unknown compression format"}; diff --git a/shared/gr2/src/gr2_file.cpp b/shared/gr2/src/gr2_file.cpp index fb329dc4..8e548eda 100644 --- a/shared/gr2/src/gr2_file.cpp +++ b/shared/gr2/src/gr2_file.cpp @@ -75,8 +75,10 @@ std::optional File::load(const uint8_t* bytes, size_t len, LoadError* err) } if (magic == Magic::Unknown) return fail("header", "not a Granny file (unknown magic)"); - if (magic != Magic::Bit32_LE) - return fail("header", "only 32-bit little-endian supported (M0 range)"); + // 64 位 LE(Granny 64 位导出器,如 AVA2 plechi_* 资源):头 / section 表 / fixup 与 + // 32 位相同,只有 section 数据里的指针槽是 8 字节(Impl::ptr)。 + if (magic != Magic::Bit32_LE && magic != Magic::Bit64_LE) + return fail("header", "big-endian Granny files not supported"); uint32_t header_size = 0, header_format = 0; rd32(bytes, len, 16, header_size); @@ -120,6 +122,7 @@ std::optional File::load(const uint8_t* bytes, size_t len, LoadError* err) out.version_ = version; out.total_size_ = total_size; out.impl_ = std::make_shared(); + out.impl_->ptr = (magic == Magic::Bit64_LE) ? 8 : 4; out.impl_->sections.resize(sec_count); out.impl_->raw.resize(sec_count); out.sections_.reserve(sec_count); @@ -161,7 +164,8 @@ std::optional File::load(const uint8_t* bytes, size_t len, LoadError* err) } // ── T1:fixup 索引(需要展开后的 section 数据 + 原始 section 头)────── - out.impl_->build_fixups(bytes, len); + if (!out.impl_->build_fixups(bytes, len, err)) + return std::nullopt; out.impl_->root_type = { int32_t(rt_sec), rt_off }; out.impl_->root_obj = { int32_t(ro_sec), ro_off }; diff --git a/shared/gr2/src/gr2_mesh.cpp b/shared/gr2/src/gr2_mesh.cpp index f02cc82b..5dd2e3dc 100644 --- a/shared/gr2/src/gr2_mesh.cpp +++ b/shared/gr2/src/gr2_mesh.cpp @@ -88,12 +88,12 @@ bool File::Impl::extract_mesh(Ref mesh_obj, Ref mesh_type, const auto& vdms = parse_type(mVD->ref_type); const TypeMember* mVerts = find_member(vdms, "Vertices"); if (!mVerts) { MDBG("no Vertices member (vdms=%zu)\n", vdms.size()); return false; } - // ReferenceToVariantArray on-disk (32-bit): {def* Type; int32 Count; void* Ptr} - // (granny_data_type_definition.cpp: Ptr32 + int32 + Ptr32) + // ReferenceToVariantArray on-disk: {def* Type; int32 Count; void* Ptr}, packed + // (granny_data_type_definition.cpp: Ptr + int32 + Ptr; ptr = 4 or 8 bytes) Ref vslot = member_slot(vd, *mVerts); Ref vtype = follow({vslot.section, vslot.offset + 0}); - int32_t vcount = rd_i32({vslot.section, vslot.offset + 4}); - Ref vdata = follow({vslot.section, vslot.offset + 8}); + int32_t vcount = rd_i32({vslot.section, vslot.offset + ptr}); + Ref vdata = follow({vslot.section, vslot.offset + ptr + 4}); MDBG("Vertices count=%d vtype=(%d,%u) vdata=(%d,%u)\n", vcount, vtype.section, vtype.offset, vdata.section, vdata.offset); if (vcount <= 0 || vcount > (1 << 24) || !vtype.valid() || !vdata.valid()) return false; @@ -365,10 +365,10 @@ int32_t File::Impl::intern_material(Ref mat_obj, Ref mat_type, int depth) { return idx; } -// VariantRef 在 32 位文件里 = {ptr Type; ptr Object}。 +// VariantRef = {ptr Type; ptr Object}(ptr = 4 或 8 字节)。 bool File::Impl::extended_i32(Ref slot, const char* name, int32_t& out) { Ref type = follow(slot); - Ref obj = follow({slot.section, slot.offset + 4}); + Ref obj = follow({slot.section, slot.offset + ptr}); if (!type.valid() || !obj.valid()) return false; const TypeMember* m = find_member(parse_type(type), name); if (!m || (m->type != detail::MT_Int32 && m->type != detail::MT_UInt32)) return false; diff --git a/shared/gr2/src/gr2_typetree.cpp b/shared/gr2/src/gr2_typetree.cpp index b670ecf8..bb31be25 100644 --- a/shared/gr2/src/gr2_typetree.cpp +++ b/shared/gr2/src/gr2_typetree.cpp @@ -1,16 +1,20 @@ // M0 T1(fixup 索引)+ T3(自描述类型树遍历)。见 docs/reference/steps/M0-gr2-reader.md // 规格:granny_file_format.h(fixup)+ granny_data_type_definition.h/.cpp(成员类型 + stride) #include "internal.h" +#include "bitknit2.h" +#include +#include #include +#include namespace gr2 { using detail::Ref; using detail::TypeMember; -using detail::kTypeDefEntrySize; -// ── member_type → 文件里的单元字节数(32 位指针)────────────────────── +// ── member_type → 文件里的单元字节数 ────────────────────────────────── // 序数见 internal.h MemberType。InlineMember 需递归(这里在 member_unit_size 处理)。 +// 表里是 32 位文件的值;含指针的类型按 kPtrSlots 个指针加宽(64 位文件每个指针 +4)。 static const int8_t kUnit32[detail::MT_OnePastLast] = { /* End */ 0, /* Inline */ 0, /* 特判 */ @@ -19,7 +23,7 @@ static const int8_t kUnit32[detail::MT_OnePastLast] = { /* ArrayOfRefs */ 8, /* VariantRef */ 8, /* ptr + ptr */ /* Removed */ 0, - /* RefToVariantArr*/ 12, + /* RefToVariantArr*/ 12, /* ptr + int32 + ptr */ /* String */ 4, /* Transform */ 68, /* u32 flags + f32[3] + f32[4] + f32[3][3] */ /* Real32 */ 4, @@ -36,6 +40,11 @@ static const int8_t kUnit32[detail::MT_OnePastLast] = { /* Real16 */ 2, /* EmptyRef */ 4, }; +static const int8_t kPtrSlots[detail::MT_OnePastLast] = { + 0, 0, /*Reference*/ 1, /*RefToArray*/ 1, /*ArrayOfRefs*/ 1, /*VariantRef*/ 2, 0, + /*RefToVariantArray*/ 2, /*String*/ 1, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*EmptyRef*/ 1, +}; // ── section 内指针 + 边界检查 ──────────────────────────────────────── const uint8_t* File::Impl::at(Ref r, size_t need) const { @@ -79,19 +88,46 @@ std::string File::Impl::rd_str(Ref slot) const { // ── T1:建 fixup 索引 ──────────────────────────────────────────────── // grn_pointer_fixup 数组在文件里(PointerFixupArrayOffset 从文件起点算,Count 项,每 12B)。 // 每项 { u32 FromOffset(本 section 展开数据内偏移); u32 DestSection; u32 DestOffset }。 -void File::Impl::build_fixups(const uint8_t* file, size_t file_len) { - auto le32 = [&](size_t off) -> uint32_t { - if (off + 4 > file_len) return 0; - return uint32_t(file[off]) | (uint32_t(file[off + 1]) << 8) | - (uint32_t(file[off + 2]) << 16) | (uint32_t(file[off + 3]) << 24); +// BitKnit2 section(Format==4)的 fixup 表也被压缩:偏移处是 u32 压缩长度 + BitKnit2 流, +// 解出 Count*12 字节(Granny 2.11 changelog「fixup metadata is compressed」; +// BG3ModStudio GR2Reader 同样处理)。MixedMarshalling fixup 本读取器不用,不展开。 +bool File::Impl::build_fixups(const uint8_t* file, size_t file_len, LoadError* err) { + auto le32 = [](const uint8_t* p) -> uint32_t { + return uint32_t(p[0]) | (uint32_t(p[1]) << 8) | + (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24); }; fixups.clear(); + std::vector unpacked; for (size_t si = 0; si < raw.size(); ++si) { const GrnSection& gs = raw[si]; + if (gs.pointer_fixup_count == 0) continue; + const uint8_t* table = nullptr; + size_t count = gs.pointer_fixup_count; size_t base = gs.pointer_fixup_off; - for (uint32_t k = 0; k < gs.pointer_fixup_count; ++k) { - size_t p = base + size_t(k) * 12; - if (p + 12 > file_len) break; + if (gs.compression == 4) { + if (base > file_len || file_len - base < 4) { + if (err) *err = {"fixup", "compressed fixup header out of range (section " + std::to_string(si) + ")"}; + return false; + } + const size_t csize = le32(file + base); + if (csize > file_len - base - 4 || count > SIZE_MAX / 12) { + if (err) *err = {"fixup", "compressed fixup data out of range (section " + std::to_string(si) + ")"}; + return false; + } + unpacked.assign(count * 12, 0); + if (!bitknit2_decompress(file + base + 4, csize, unpacked.data(), unpacked.size())) { + if (err) *err = {"fixup", "BitKnit2 fixup decompress failed (section " + std::to_string(si) + ")"}; + return false; + } + table = unpacked.data(); + } else { + // 未压缩:保持旧行为,越界的尾部项丢弃 + if (base > file_len) continue; + count = std::min(count, (file_len - base) / 12); + table = file + base; + } + for (size_t k = 0; k < count; ++k) { + const uint8_t* p = table + k * 12; uint32_t from = le32(p + 0); uint32_t dsec = le32(p + 4); uint32_t doff = le32(p + 8); @@ -100,13 +136,14 @@ void File::Impl::build_fixups(const uint8_t* file, size_t file_len) { Ref{int32_t(dsec), doff}; } } + return true; } // ── T3:走 data_type_definition 数组 ───────────────────────────────── uint32_t File::Impl::member_unit_size(const TypeMember& m) { if (m.type == detail::MT_Inline) return object_size(m.ref_type); if (m.type <= 0 || m.type >= detail::MT_OnePastLast) return 0; - return (uint32_t)kUnit32[m.type]; + return uint32_t(kUnit32[m.type]) + uint32_t(kPtrSlots[m.type]) * (ptr - 4); } uint32_t File::Impl::object_size(Ref type_ref) { @@ -127,8 +164,9 @@ const std::vector& File::Impl::parse_type(Ref type_ref) { Ref cur = type_ref; uint32_t inst_off = 0; + const uint32_t entry = detail::type_def_entry_size(ptr); for (int guard = 0; guard < 4096; ++guard) { - const uint8_t* e = at(cur, kTypeDefEntrySize); + const uint8_t* e = at(cur, entry); if (!e) break; int32_t type = (int32_t)rd_u32(cur); if (type == detail::MT_End) break; @@ -137,10 +175,10 @@ const std::vector& File::Impl::parse_type(Ref type_ref) { m.type = type; // Name @ +4(指针槽) m.name = rd_str({cur.section, cur.offset + 4}); - // ReferenceType @ +8(指针槽 → data_type_definition 数组) - m.ref_type = follow({cur.section, cur.offset + 8}); - // ArrayWidth @ +12 - m.array_width = (int32_t)rd_u32({cur.section, cur.offset + 12}); + // ReferenceType @ +4+ptr(指针槽 → data_type_definition 数组) + m.ref_type = follow({cur.section, cur.offset + 4 + ptr}); + // ArrayWidth @ +4+2*ptr + m.array_width = (int32_t)rd_u32({cur.section, cur.offset + 4 + 2 * ptr}); uint32_t width = (m.array_width <= 0) ? 1u : (uint32_t)m.array_width; m.offset = inst_off; @@ -148,7 +186,7 @@ const std::vector& File::Impl::parse_type(Ref type_ref) { inst_off += m.size; out.push_back(std::move(m)); - cur.offset += kTypeDefEntrySize; + cur.offset += entry; } slot = std::move(out); return slot; @@ -169,7 +207,7 @@ std::vector File::Impl::read_array_of_refs(Ref obj, const TypeMember& m) co if (!arr.valid()) return out; out.reserve(count); for (int32_t i = 0; i < count; ++i) { - Ref elem = follow({arr.section, arr.offset + uint32_t(i) * 4}); + Ref elem = follow({arr.section, arr.offset + uint32_t(i) * ptr}); out.push_back(elem); // 可能 invalid(NULL 项) } return out; diff --git a/shared/gr2/src/internal.h b/shared/gr2/src/internal.h index 1d975928..07c326da 100644 --- a/shared/gr2/src/internal.h +++ b/shared/gr2/src/internal.h @@ -36,7 +36,7 @@ struct Section { SectionInfo info; }; -// section 内的位置。不物化指针(文件是 32 位指针,本进程 64 位), +// section 内的位置。不物化指针(文件是 32 或 64 位指针), // 全程用 (section, offset) + fixup 表按需解引用。 struct Ref { int32_t section = -1; @@ -53,9 +53,10 @@ enum MemberType { MT_Int32, MT_UInt32, MT_Real16, MT_EmptyRef, MT_OnePastLast }; -// data_type_definition 在文件里的字节数(32 位指针): -// Type(4) Name(ptr4) ReferenceType(ptr4) ArrayWidth(4) Extra[3](12) Ignored(ptr4) -constexpr uint32_t kTypeDefEntrySize = 32; +// data_type_definition 在文件里的字节数(结构紧排,指针宽度随文件 magic): +// Type(4) Name(ptr) ReferenceType(ptr) ArrayWidth(4) Extra[3](12) Ignored(ptr) +// 32 位文件 = 32B,64 位文件 = 44B(与 BG3ModStudio GR2TypeNode pack(1) 一致) +constexpr uint32_t type_def_entry_size(uint32_t ptr) { return 4 + ptr + ptr + 4 + 12 + ptr; } struct TypeMember { std::string name; @@ -81,13 +82,16 @@ struct File::Impl { Ref root_obj; // grn_file_header.RootObject Ref root_type; // grn_file_header.RootObjectTypeDefinition bool typetree_ready = false; + // 文件指针宽度:32 位 magic = 4,64 位 magic = 8。指针槽都靠 fixup 表解引用, + // 只有成员大小 / 复合成员内部偏移随它变化。 + uint32_t ptr = 4; // 类型解析缓存:typedef 的 Ref -> 成员列表 std::unordered_map> type_cache; // ── T2 / T1 ── bool decompress_section(const GrnSection&, const uint8_t* src, detail::Section& out, LoadError*); - void build_fixups(const uint8_t* file, size_t file_len); // T1 + bool build_fixups(const uint8_t* file, size_t file_len, LoadError* err); // T1 // ── T3 ── const uint8_t* at(Ref r, size_t need = 0) const; // section 内指针 + 边界检查 @@ -106,7 +110,7 @@ struct File::Impl { // 成员访问(obj = 对象实例的 Ref,m = 其类型的某个成员) Ref member_slot(Ref obj, const TypeMember& m) const { return {obj.section, obj.offset + m.offset}; } Ref read_reference(Ref obj, const TypeMember& m) const { return follow(member_slot(obj, m)); } - // ArrayOfReferences: {int32 count; ptr → [count] 个指针槽 → 各自的对象} + // ArrayOfReferences: {int32 count; ptr → [count] 个指针槽(各 ptr 字节)→ 各自的对象} std::vector read_array_of_refs(Ref obj, const TypeMember& m) const; // ReferenceToArray: {int32 count; ptr → [count] 个连续对象(elem_type)} bool read_ref_to_array(Ref obj, const TypeMember& m, Ref& base, uint32_t& count, uint32_t& stride); @@ -121,6 +125,9 @@ struct File::Impl { // 曲线子类型分类(T7a)。curve_obj 指向 inline 曲线对象本体,curve_type 是它的类型。 std::string classify_curve_obj(Ref curve_obj, Ref curve_type); void read_old_curve(Ref curve_obj, Ref curve_type, Curve& out); // T7b + // curve2{variant CurveData}:各 CurveData* 压缩变体解到同一 Curve(knots + float controls)。 + // keyframe_dt = 所在 animation 的 TimeStep(DaKeyframes32f 的隐含 knot 间距)。 + void read_curve2(Ref curve_obj, Ref curve_type, float keyframe_dt, Curve& out); double skeleton_self_check(int skeleton) const; // granny_transform (68B) → 行主序 4x4(BuildCompositeTransform4x4 语义) diff --git a/src/ava2_text_file.h b/src/ava2_text_file.h new file mode 100644 index 00000000..50516b97 --- /dev/null +++ b/src/ava2_text_file.h @@ -0,0 +1,26 @@ +#pragma once +#include +#include +#include +namespace ava2 { +// CMemoryTextFileLoader::Bind and SplitLine/SplitLineByTab (AVA2 EterBase/FileLoader.cpp). +inline std::vector ava2TextLines(const std::string& input) { + std::vector lines;std::string line; + for(size_t i=0;i ava2TabTokens(const std::string& line,bool preserveEmpty) { + std::vector fields;if(line.empty())return fields;size_t pos=0; + while(pos +#include +#include +#include +#include +#include +#include +#include +namespace ava2 { +// Returns 0 = tokens, -1 = no token, -2 = unmatched '"' (SplitLine2). SplitLine == (result==0). +inline int ava2SplitLine2(const std::string& line,std::vector* tokens,const char* delim=" \t") { + tokens->clear();size_t base=0; + do { + size_t begin=line.find_first_not_of(delim,base); + if(begin==std::string::npos)return -1; + size_t end; + if(line[begin]=='"') {++begin;end=line.find('"',begin);if(end==std::string::npos)return -2;base=end+1;} + else {end=line.find_first_of(delim,begin);base=end;} + tokens->push_back(line.substr(begin,end==std::string::npos?std::string::npos:end-begin)); + if(base==std::string::npos||line.find_first_not_of(delim,base)==std::string::npos)break; + } while(base(c))); } + +// LoadMultipleTextData (EterLib/Util.cpp): "key values..." lines plus "start key" ... "end" blocks whose +// tokens are concatenated. Each line's first token is lower-cased (inside blocks too); first insert wins. +inline void ava2LoadMultipleTextData(const std::string& text,std::map>& map) { + const std::vector lines=ava2TextLines(text); + std::vector tok,sub; + for(size_t i=0;i> children; + std::map> tokens; + }; + bool load(const std::string& text,std::vector* errors=nullptr) { + m_lines=ava2TextLines(text);m_line=0;m_global=Node{};m_global.name="global";m_cur=&m_global;m_errors=errors; + return loadGroup(&m_global); + } + size_t childCount() const { return m_cur->children.size(); } + bool setChild(size_t i) { if(i>=m_cur->children.size())return false;m_cur=m_cur->children[i].get();return true; } + bool setParent() { if(!m_cur->parent)return false;m_cur=m_cur->parent;return true; } + const std::string& nodeName() const { return m_cur->name; } + void setTop() { m_cur=&m_global; } + // SetChildNode(c_szKey): first child whose (lower-cased) group name matches. + bool setChildNode(const std::string& key) { + std::string k=key;ava2Lowers(k); + for(auto& c:m_cur->children)if(c->name==k){m_cur=c.get();return true;} + return false; + } + // SetChildNode(c_rstrKeyHead, dwIndex): "%s%02u". + bool setChildNode(const std::string& head,unsigned index) { + char key[33];std::snprintf(key,sizeof(key),"%s%02u",head.c_str(),index);return setChildNode(std::string(key)); + } + bool tokenString(const std::string& key,std::string* value) const { + auto* v=tokenVector(key);if(!v||v->empty())return false;*value=v->front();return true; + } + const std::vector* tokenVector(const std::string& key) const { + auto it=m_cur->tokens.find(key);return it==m_cur->tokens.end()?nullptr:&it->second; + } + bool tokenInteger(const std::string& key,int* value) const { + auto* v=tokenVector(key);if(!v||v->empty())return false;*value=std::atoi(v->front().c_str());return true; + } +private: + void error(const std::string& s) { if(m_errors)m_errors->push_back(s); } + bool loadGroup(Node* node) { + std::vector tok;int depth=0; + for(;m_line();child->parent=node;child->name=tok[1];ava2Lowers(child->name); + Node* raw=child.get();node->children.push_back(std::move(child)); + ++m_line; + if(!loadGroup(raw))return false; + } else if(tok[0]=="list") { + if(tok.size()!=2)continue; + std::string key=tok[1];ava2Lowers(key);std::vector values,sub; + for(++m_line;m_linetokens.insert({key,values}); + } else { + if(tok.size()==1) {error("CTextFileLoader::LoadGroup : must have a value (line: "+std::to_string(m_line)+" key: "+tok[0]+")");break;} + std::string key=tok[0];tok.erase(tok.begin());node->tokens.insert({key,tok}); + } + } + return depth==0; + } + std::vector m_lines;size_t m_line=0; + Node m_global;Node* m_cur=&m_global;std::vector* m_errors=nullptr; +}; +} diff --git a/src/battlepass_state.h b/src/battlepass_state.h new file mode 100644 index 00000000..66d52357 --- /dev/null +++ b/src/battlepass_state.h @@ -0,0 +1,18 @@ +#pragma once +// AVA2 UserInterface/PythonBattlePass.cpp uses separate ordered information and +// progress lists. UPDATE appends; it does not replace a matching mission. +#include "eter_net/Packet.h" +#include +#include +namespace ava2 { +struct BattlePassState { + int32_t time=0; + std::vector info,progress; + PyObject* handler=nullptr; + void SetHandler(PyObject* value); + void Clear(uint8_t subheader); + void Loading(uint8_t subheader); + void Reset(); +}; +BattlePassState& GetBattlePassState(); +} diff --git a/src/cube_renewal_state.h b/src/cube_renewal_state.h new file mode 100644 index 00000000..d7ce31d6 --- /dev/null +++ b/src/cube_renewal_state.h @@ -0,0 +1,15 @@ +#pragma once +#include "eter_net/Packet.h" +#include +#include +namespace ava2 { +// AVA2 PythonCubeRenewal.cpp: a vector, not a map keyed by recipe index. +struct CubeRenewalState { + std::vector records; + PyObject* handler=nullptr; + void SetHandler(PyObject* value); + void LoadingList(); + void Reset(); +}; +CubeRenewalState& GetCubeRenewalState(); +} diff --git a/src/drop_item_state.h b/src/drop_item_state.h new file mode 100644 index 00000000..65c930dd --- /dev/null +++ b/src/drop_item_state.h @@ -0,0 +1,17 @@ +#pragma once +// AVA2 PythonDropItem.cpp: ordered results and unconstrained page selection. +#include "eter_net/Packet.h" +#include +#include +namespace ava2 { +struct DropItemState { + int32_t page=1; + std::vector records; + PyObject* handler=nullptr; + void SetHandler(PyObject* value); + void Clear(); + void Loading(); + void Reset(); +}; +DropItemState& GetDropItemState(); +} diff --git a/src/dungeon_info_state.h b/src/dungeon_info_state.h new file mode 100644 index 00000000..60c8da7f --- /dev/null +++ b/src/dungeon_info_state.h @@ -0,0 +1,14 @@ +#pragma once +// AVA2 PythonDungeonInfo.cpp. Clear resets info/missions/page but retains ranking. +#include "eter_net/Packet.h" +#include +namespace ava2 { +struct DungeonInfoState { + int32_t page=1; + std::vector info; + std::vector missions; + std::vector ranking; + void Clear() {page=1;info.clear();missions.clear();} +}; +DungeonInfoState& GetDungeonInfoState(); +} diff --git a/src/eter_base/Random.cpp b/src/eter_base/Random.cpp new file mode 100644 index 00000000..8e043bd0 --- /dev/null +++ b/src/eter_base/Random.cpp @@ -0,0 +1,52 @@ +// Provenance: AVA2 EterBase/Random.cpp. +#include "Random.h" +#include + +namespace eter { +namespace { +uint32_t randseed = 1; +} // namespace + +void srandom(uint32_t seed) +{ + randseed = seed; +} + +/* + * Pseudo-random number generator for randomizing the profiling clock, + * and whatever else we might use it for. The result is uniform on + * [0, 2^31 - 1]. + */ +uint32_t random() +{ + int32_t x, hi, lo, t; + + /* + * Compute x[n + 1] = (7^5 * x[n]) mod (2^31 - 1). + * From "Random number generators: good ones are hard to find", + * Park and Miller, Communications of the ACM, vol. 31, no. 10, + * October 1988, p. 1195. + */ + x = int32_t(randseed); + hi = x / 127773; + lo = x % 127773; + t = 16807 * lo - 2836 * hi; + if (t <= 0) + t += 0x7fffffff; + randseed = uint32_t(t); + return uint32_t(t); +} + +float frandom(float flLow, float flHigh) +{ + float fl = float(random()) / float(2147483648.0f); // float in [0,1) + return (fl * (flHigh - flLow)) + flLow; // float in [low,high) +} + +int32_t random_range(int32_t from, int32_t to) +{ + assert(from <= to); + // Windows: unsigned long random() % long range is an unsigned 32-bit modulo. + return int32_t(random() % (uint32_t(to) - uint32_t(from) + 1u) + uint32_t(from)); +} +} // namespace eter diff --git a/src/eter_base/Random.h b/src/eter_base/Random.h new file mode 100644 index 00000000..7cdd5f85 --- /dev/null +++ b/src/eter_base/Random.h @@ -0,0 +1,13 @@ +#pragma once +// EterBase random: the Park-Miller generator behind random_range / app.GetRandom. +// Provenance: AVA2 EterBase/Random.cpp (32-bit long arithmetic kept with fixed-width types). +#include + +namespace eter { +void srandom(uint32_t seed); +// Uniform on [1, 2^31 - 2]. +uint32_t random(); +float frandom(float flLow, float flHigh); +// from <= to: random() % (to - from + 1) + from. +int32_t random_range(int32_t from, int32_t to); +} // namespace eter diff --git a/src/eter_effect/EffectData.cpp b/src/eter_effect/EffectData.cpp index 8fe30ac6..abed6632 100644 --- a/src/eter_effect/EffectData.cpp +++ b/src/eter_effect/EffectData.cpp @@ -1,3 +1,4 @@ +#include #include "EffectData.h" #include #include @@ -7,6 +8,13 @@ namespace ava2 { +namespace { +// CTextFileLoader values go through atof(): unparsable text reads as 0 instead of throwing. +float ScriptFloat(const std::string& token) { return std::strtof(token.c_str(), nullptr); } +int ScriptInt(const std::string& token) { return std::atoi(token.c_str()); } +} + + float InterpolateTimeEvent(const std::vector& events, float time, float defaultValue) { if (events.empty()) return defaultValue; if (events.size() == 1 || time <= events.front().time) return events.front().value; @@ -123,9 +131,9 @@ bool EffectData::LoadScript(const std::string& filepath) { if (idx < numTokens && tokens[idx] == "{") { idx++; while (idx < numTokens && tokens[idx] != "}") { - float t = std::stof(tokens[idx++]); + float t = ScriptFloat(tokens[idx++]); if (idx < numTokens && tokens[idx] != "}") { - float v = std::stof(tokens[idx++]); + float v = ScriptFloat(tokens[idx++]); outEvents.push_back({t, v}); } } @@ -138,12 +146,12 @@ bool EffectData::LoadScript(const std::string& filepath) { if (tokenLower == "boundingsphereradius" && idx + 1 < numTokens) { idx++; - m_bounding_sphere_radius = std::stof(tokens[idx++]); + m_bounding_sphere_radius = ScriptFloat(tokens[idx++]); } else if (tokenLower == "boundingsphereposition" && idx + 3 < numTokens) { idx++; - m_bounding_sphere_position[0] = std::stof(tokens[idx++]); - m_bounding_sphere_position[1] = std::stof(tokens[idx++]); - m_bounding_sphere_position[2] = std::stof(tokens[idx++]); + m_bounding_sphere_position[0] = ScriptFloat(tokens[idx++]); + m_bounding_sphere_position[1] = ScriptFloat(tokens[idx++]); + m_bounding_sphere_position[2] = ScriptFloat(tokens[idx++]); } else if (tokenLower == "group" && idx + 1 < numTokens && ToLower(tokens[idx + 1]) == "particle") { idx += 2; if (idx < numTokens && tokens[idx] == "{") idx++; @@ -166,23 +174,27 @@ bool EffectData::LoadScript(const std::string& filepath) { std::string pKey = ToLower(tokens[idx++]); if (pKey == "starttime" && idx < numTokens) { - pe.start_time = std::stof(tokens[idx++]); + pe.start_time = ScriptFloat(tokens[idx++]); } else if (pKey == "list" && idx + 1 < numTokens && ToLower(tokens[idx]) == "timeeventposition") { idx++; // skip timeeventposition if (idx < numTokens && tokens[idx] == "{") { idx++; while (idx < numTokens && tokens[idx] != "}") { // format: time "MOVING_TYPE_DIRECT" x y z + // CEffectElementBase::LoadScript: time, moving type, position and, + // for MOVING_TYPE_BEZIER_CURVE, a control point. idx++; // time - if (idx < numTokens && tokens[idx] != "}") idx++; // moving type string + bool bezier = false; + if (idx < numTokens && tokens[idx] != "}") bezier = tokens[idx++].find("MOVING_TYPE_BEZIER_CURVE") != std::string::npos; if (idx + 2 < numTokens && tokens[idx] != "}") { - float mx = std::stof(tokens[idx++]); - float my = std::stof(tokens[idx++]); - float mz = std::stof(tokens[idx++]); + float mx = ScriptFloat(tokens[idx++]); + float my = ScriptFloat(tokens[idx++]); + float mz = ScriptFloat(tokens[idx++]); // Map Metin2 3ds Max Z-up (X:right, Y:forward, Z:up) to Ava2 Y-up (X:right, Y:up, Z:forward) pe.position[0] = mx; pe.position[1] = mz; pe.position[2] = my; + if (bezier) idx = std::min(idx + 3, numTokens); // control point } } if (idx < numTokens && tokens[idx] == "}") idx++; @@ -198,21 +210,21 @@ bool EffectData::LoadScript(const std::string& filepath) { std::string eKey = ToLower(tokens[idx++]); if (eKey == "maxemissioncount" && idx < numTokens) { - pe.emitter.max_emission_count = std::stoul(tokens[idx++]); + pe.emitter.max_emission_count = ScriptInt(tokens[idx++]); } else if (eKey == "cyclelength" && idx < numTokens) { - pe.emitter.cycle_length = std::stof(tokens[idx++]); + pe.emitter.cycle_length = ScriptFloat(tokens[idx++]); } else if (eKey == "cycleloopenable" && idx < numTokens) { - pe.emitter.cycle_loop_enable = (std::stoi(tokens[idx++]) != 0); + pe.emitter.cycle_loop_enable = (ScriptInt(tokens[idx++]) != 0); } else if (eKey == "loopcount" && idx < numTokens) { - pe.emitter.loop_count = std::stoi(tokens[idx++]); + pe.emitter.loop_count = ScriptInt(tokens[idx++]); } else if (eKey == "emittershape" && idx < numTokens) { - pe.emitter.emitter_shape = static_cast(std::stoi(tokens[idx++])); + pe.emitter.emitter_shape = static_cast(ScriptInt(tokens[idx++])); } else if (eKey == "emittingradius" && idx < numTokens) { - pe.emitter.emitting_radius = std::stof(tokens[idx++]); + pe.emitter.emitting_radius = ScriptFloat(tokens[idx++]); } else if (eKey == "emittingdirection" && idx + 2 < numTokens) { - float ex = std::stof(tokens[idx++]); - float ey = std::stof(tokens[idx++]); - float ez = std::stof(tokens[idx++]); + float ex = ScriptFloat(tokens[idx++]); + float ey = ScriptFloat(tokens[idx++]); + float ez = ScriptFloat(tokens[idx++]); pe.emitter.emitting_direction[0] = ex; pe.emitter.emitting_direction[1] = ez; pe.emitter.emitting_direction[2] = ey; @@ -251,31 +263,31 @@ bool EffectData::LoadScript(const std::string& filepath) { std::string prKey = ToLower(tokens[idx++]); if (prKey == "srcblendtype" && idx < numTokens) { - pe.particle.src_blend_type = static_cast(std::stoi(tokens[idx++])); + pe.particle.src_blend_type = static_cast(ScriptInt(tokens[idx++])); } else if (prKey == "destblendtype" && idx < numTokens) { - pe.particle.dest_blend_type = static_cast(std::stoi(tokens[idx++])); + pe.particle.dest_blend_type = static_cast(ScriptInt(tokens[idx++])); } else if (prKey == "coloroperationtype" && idx < numTokens) { - pe.particle.color_op_type = static_cast(std::stoi(tokens[idx++])); + pe.particle.color_op_type = static_cast(ScriptInt(tokens[idx++])); } else if (prKey == "billboardtype" && idx < numTokens) { - pe.particle.billboard_type = static_cast(std::stoi(tokens[idx++])); + pe.particle.billboard_type = static_cast(ScriptInt(tokens[idx++])); } else if (prKey == "rotationtype" && idx < numTokens) { - pe.particle.rotation_type = static_cast(std::stoi(tokens[idx++])); + pe.particle.rotation_type = static_cast(ScriptInt(tokens[idx++])); } else if (prKey == "rotationspeed" && idx < numTokens) { - pe.particle.rotation_speed = std::stof(tokens[idx++]); + pe.particle.rotation_speed = ScriptFloat(tokens[idx++]); } else if (prKey == "rotationrandomstartingbegin" && idx < numTokens) { - pe.particle.rotation_random_begin = std::stoi(tokens[idx++]); + pe.particle.rotation_random_begin = ScriptInt(tokens[idx++]); } else if (prKey == "rotationrandomstartingend" && idx < numTokens) { - pe.particle.rotation_random_end = std::stoi(tokens[idx++]); + pe.particle.rotation_random_end = ScriptInt(tokens[idx++]); } else if (prKey == "attachenable" && idx < numTokens) { - pe.particle.attach_enable = (std::stoi(tokens[idx++]) != 0); + pe.particle.attach_enable = (ScriptInt(tokens[idx++]) != 0); } else if (prKey == "stretchenable" && idx < numTokens) { - pe.particle.stretch_enable = (std::stoi(tokens[idx++]) != 0); + pe.particle.stretch_enable = (ScriptInt(tokens[idx++]) != 0); } else if (prKey == "texanitype" && idx < numTokens) { - pe.particle.tex_ani_type = static_cast(std::stoi(tokens[idx++])); + pe.particle.tex_ani_type = static_cast(ScriptInt(tokens[idx++])); } else if (prKey == "texanidelay" && idx < numTokens) { - pe.particle.tex_ani_delay = std::stof(tokens[idx++]); + pe.particle.tex_ani_delay = ScriptFloat(tokens[idx++]); } else if (prKey == "texanirandomstartframeenable" && idx < numTokens) { - pe.particle.tex_ani_random_start_frame = (std::stoi(tokens[idx++]) != 0); + pe.particle.tex_ani_random_start_frame = (ScriptInt(tokens[idx++]) != 0); } else if (prKey == "list" && idx < numTokens) { std::string listName = ToLower(tokens[idx++]); if (listName == "timeeventscalex") ReadTimeEvents(pe.particle.time_scale_x); diff --git a/src/eter_image/GrpImage.h b/src/eter_image/GrpImage.h index 5e822bb5..78100620 100644 --- a/src/eter_image/GrpImage.h +++ b/src/eter_image/GrpImage.h @@ -38,12 +38,12 @@ public: const CGraphicTexture& GetTextureReference() const { return m_imageTexture; } CGraphicTexture* GetTexturePointer() { return &m_imageTexture; } - bool LoadFile(const char* c_szFileName) + bool LoadFile(const char* c_szFileName,const char* logicalName=nullptr) { if (!c_szFileName || !*c_szFileName) return false; - SetFileName(c_szFileName); + SetFileName(logicalName?logicalName:c_szFileName); std::ifstream file(c_szFileName, std::ios::binary | std::ios::ate); if (!file.is_open()) diff --git a/src/eter_image/GrpImageInstance.cpp b/src/eter_image/GrpImageInstance.cpp index b8cc06d4..fc19af9a 100644 --- a/src/eter_image/GrpImageInstance.cpp +++ b/src/eter_image/GrpImageInstance.cpp @@ -37,6 +37,37 @@ CGraphicImage* GrpGetImagePointer(uint32_t handle) return nullptr; } +static uint32_t s_nextInstanceHandle = 1; +static std::unordered_map s_handleToInstance; + +uint32_t GrpRegisterImageInstanceHandle(CGraphicImageInstance* pInstance) +{ + if (!pInstance) + return 0; + std::lock_guard lock(s_imageHandleMutex); + const uint32_t handle = s_nextInstanceHandle++; + s_handleToInstance[handle] = pInstance; + return handle; +} + +CGraphicImageInstance* GrpGetImageInstancePointer(uint32_t handle) +{ + std::lock_guard lock(s_imageHandleMutex); + auto it = s_handleToInstance.find(handle); + return it == s_handleToInstance.end() ? nullptr : it->second; +} + +CGraphicImageInstance* GrpReleaseImageInstanceHandle(uint32_t handle) +{ + std::lock_guard lock(s_imageHandleMutex); + auto it = s_handleToInstance.find(handle); + if (it == s_handleToInstance.end()) + return nullptr; + CGraphicImageInstance* pInstance = it->second; + s_handleToInstance.erase(it); + return pInstance; +} + CDynamicPool CGraphicImageInstance::ms_kPool; CDynamicPool CGraphicExpandedImageInstance::ms_kExpandedPool; CDynamicPool CGraphicMarkInstance::ms_kPool; diff --git a/src/eter_image/GrpImageInstance.h b/src/eter_image/GrpImageInstance.h index 6dc5ba22..05d81117 100644 --- a/src/eter_image/GrpImageInstance.h +++ b/src/eter_image/GrpImageInstance.h @@ -162,3 +162,9 @@ public: uint32_t GrpRegisterImageHandle(CGraphicImage* pImage); CGraphicImage* GrpGetImagePointer(uint32_t handle); +// Win32 hands CGraphicImageInstance* to Python as an int (skill/item.GetIconInstance*, grpImage); +// 64-bit hosts hand out these handles instead. Release drops the handle and returns the instance. +uint32_t GrpRegisterImageInstanceHandle(CGraphicImageInstance* pInstance); +CGraphicImageInstance* GrpGetImageInstancePointer(uint32_t handle); +CGraphicImageInstance* GrpReleaseImageInstanceHandle(uint32_t handle); + diff --git a/src/eter_lib/parser.cpp b/src/eter_lib/parser.cpp new file mode 100644 index 00000000..1bc74fcf --- /dev/null +++ b/src/eter_lib/parser.cpp @@ -0,0 +1,342 @@ +// Provenance: AVA2 EterLib/parser.cpp (script::Group). CharNextExA/CharPrevExA walk the default +// code page (a DBCS lead byte and its trail are one character); NUL ends the source like it does +// for CharNextExA. Kept quirks: LocaleString_Skip never advances past a single-byte space, and a +// "name|" argument without a value reuses the previous argument's value buffer. +#include "parser.h" +#include "python_app.h" +#include "shared/codepage/codepage.h" +#include +#include +#include + +using namespace script; + +namespace { + +// CharNextExA: one character, two bytes for a lead byte with a trail; NUL does not advance. +const char* CharNext(unsigned codePage, const char* cur) +{ + if (!*cur) + return cur; + if (mt_codepage::is_lead_byte(codePage, static_cast(*cur)) && cur[1]) + return cur + 2; + return cur + 1; +} + +// CharPrevExA: the start of the character before cur, scanning from base. +char* CharPrev(unsigned codePage, char* base, char* cur) +{ + char* prev = base; + for (char* p = base; p < cur;) + { + prev = p; + const char* next = CharNext(codePage, p); + if (next == p) + break; + p = const_cast(next); + } + return prev; +} + +const char* LocaleString_FindChar(const char* base, int len, char test) +{ + if (!base) + return nullptr; + + const unsigned codePage = ava2::GetDefaultCodePage(); + int pos = 0; + while (pos < len) + { + const char* cur = base + pos; + const int cur_len = int(CharNext(codePage, cur) - cur); + if (cur_len > 1) + pos += cur_len; + else if (1 == cur_len) + { + if (*cur == test) + return cur; + ++pos; + } + else + break; + } + return nullptr; +} + +int LocaleString_RightTrim(char* base, int len) +{ + const unsigned codePage = ava2::GetDefaultCodePage(); + int pos = len; + while (pos > 0) + { + char* cur = base + pos; + char* prev = CharPrev(codePage, base, cur); + const int prev_len = int(cur - prev); + if (prev_len != 1) + break; + if (!isspace(static_cast(*prev)) && *prev != '\n' && *prev != '\r') + break; + *prev = '\0'; + pos -= prev_len; + } + return pos > 0 ? pos : 0; +} + +// The Windows loop never advances on a single-byte whitespace, so it spins 9216 times, traces +// "Infinite loop" and returns that space; the result is the same without the spin. +const char* LocaleString_Skip(unsigned codePage, const char* cur) +{ + while (*cur) + { + const char* next = CharNext(codePage, cur); + const int cur_len = int(next - cur); + if (cur_len > 1) + cur = next; + else + { + if (isspace(static_cast(*cur)) || *cur == '\n' || *cur == '\r') + SDL_Log("Infinite loop in LocaleString_Skip [%s]", cur); + return cur; + } + } + return cur; +} + +} // namespace + +bool Group::GetArg(const char* c_arg_base, int arg_len, TArgList& argList) +{ + // Windows: char szName[32 + 1], szValue[64 + 1] on the stack; one spare byte here keeps a + // two-byte character written at length 31 / 63 inside the buffer. + char szName[32 + 2] = {}; + char szValue[64 + 2] = {}; + + int iNameLen = 0; + int iValueLen = 0; + int pos = 0; + bool isValue = false; + + const unsigned codePage = ava2::GetDefaultCodePage(); + + while (pos < arg_len) + { + const char* cur = c_arg_base + pos; + const int iCharLen = int(CharNext(codePage, cur) - cur); + + if (iCharLen > 1) + { + if (isValue) + { + if (iValueLen >= 64) + { + SDL_Log("argument value overflow: must be shorter than 64 letters"); + return false; + } + memcpy(szValue + iValueLen, cur, iCharLen); + iValueLen += iCharLen; + szValue[iValueLen] = '\0'; + } + else + { + if (iNameLen >= 32) + { + SDL_Log("argument name overflow: must be shorter than 32 letters"); + return false; + } + memcpy(szName + iNameLen, cur, iCharLen); + iNameLen += iCharLen; + szName[iNameLen] = '\0'; + } + } + else if (iCharLen == 1) + { + const char c = *cur; + if (c == '|') + { + if (iNameLen == 0) + { + SDL_Log("no argument name"); + return false; + } + + isValue = false; + iNameLen = LocaleString_RightTrim(szName, iNameLen); + iValueLen = LocaleString_RightTrim(szValue, iValueLen); + argList.push_back(TArg(szName, szValue)); + iNameLen = 0; + iValueLen = 0; + } + else if (c == ';') + { + isValue = true; + } + else if (!isValue && iNameLen == 0 && isspace(static_cast(c))) + { + // leading spaces of a name are skipped + } + else if (c == '\r' || c == '\n') + { + } + else if (isValue) + { + if (iValueLen >= 64) + { + SDL_Log("argument value overflow: must be shorter than 64 letters"); + return false; + } + szValue[iValueLen++] = c; + szValue[iValueLen] = '\0'; + } + else + { + if (iNameLen >= 32) + { + SDL_Log("argument name overflow: must be shorter than 32 letters"); + return false; + } + szName[iNameLen++] = c; + szName[iNameLen] = '\0'; + } + } + else + { + break; + } + + pos += iCharLen; + } + + if (iNameLen != 0 && iValueLen != 0) + { + iNameLen = LocaleString_RightTrim(szName, iNameLen); + iValueLen = LocaleString_RightTrim(szValue, iValueLen); + argList.push_back(TArg(szName, szValue)); + } + + return true; +} + +int Group::Create(const std::string& stSource) +{ + m_cmdList.clear(); + + if (stSource.empty()) + return -1; + + const char* str_base = stSource.c_str(); + if (!*str_base) + { + SDL_Log("Source file has no content"); + return -1; + } + + const int str_len = int(stSource.length()); + int str_pos = 0; + int len_line = 0; + + const unsigned codePage = ava2::GetDefaultCodePage(); + char box_data[1024 + 1]; + + while (str_pos < str_len) + { + TCmd cmd; + + const char* word = str_base + str_pos; + const char* word_next = CharNext(codePage, word); + const int word_len = int(word_next - word); + + if (word_len > 1) + { + str_pos += word_len; + cmd.name.assign("LETTER"); + cmd.argList.push_back(TArg("value", std::string(word, word_next))); + m_cmdList.push_back(cmd); + } + else if (word_len == 1) + { + const char cur = *word; + + if ('[' == cur) + { + ++str_pos; + + const char* box_begin = str_base + str_pos; + const char* box_end = LocaleString_FindChar(box_begin, str_len - str_pos, ']'); + if (!box_end) + { + SDL_Log(" !! PARSING ERROR - Syntax Error : %s", box_begin); + return -1; + } + + str_pos += int(box_end - box_begin) + 1; + const char* data_begin = LocaleString_Skip(codePage, box_begin); + int data_len = int(box_end - data_begin); + if (data_len >= 1024) + { + SDL_Log(" !! PARSING ERROR - Buffer Overflow : %d, %s", data_len, str_base); + return -1; + } + + memcpy(box_data, data_begin, data_len); + box_data[data_len] = '\0'; + data_len = LocaleString_RightTrim(box_data, data_len); + const char* space = LocaleString_FindChar(box_data, data_len, ' '); + if (space) + { + cmd.name.assign(box_data, space - box_data); + + const char* arg = LocaleString_Skip(codePage, CharNext(codePage, space)); + const int arg_len = data_len - int(arg - box_data); + if (!GetArg(arg, arg_len, cmd.argList)) + { + SDL_Log(" !! PARSING ERROR - Unknown Arguments : %d, %s", arg_len, arg); + return -1; + } + } + else + { + cmd.name.assign(box_data); + cmd.argList.clear(); + } + + m_cmdList.push_back(cmd); + } + else if (cur == '\r' || cur == '\n') + { + if (cur == '\n') + len_line += 1; + ++str_pos; + } + else + { + ++str_pos; + cmd.name.assign("LETTER"); + cmd.argList.push_back(TArg("value", std::string(1, cur))); + m_cmdList.push_back(cmd); + } + } + else + break; + } + + return len_line; +} + +bool Group::GetCmd(TCmd& cmd) +{ + if (m_cmdList.empty()) + return false; + + cmd = m_cmdList.front(); + m_cmdList.pop_front(); + return true; +} + +bool Group::ReadCmd(TCmd& cmd) +{ + if (m_cmdList.empty()) + return false; + + cmd = m_cmdList.front(); + return true; +} diff --git a/src/eter_lib/parser.h b/src/eter_lib/parser.h new file mode 100644 index 00000000..de926515 --- /dev/null +++ b/src/eter_lib/parser.h @@ -0,0 +1,43 @@ +#pragma once +// script::Group, the quest/description script tokenizer. +// Provenance: AVA2 EterLib/parser.{h,cpp}, ported as is: "[NAME a;1|b;2]" commands, one LETTER +// command per (code-page) character, '\n' outside commands counted as the returned line count. +#include +#include + +namespace script +{ + struct SArgumet + { + SArgumet(const std::string& c_stName, const std::string& c_stValue) : strName(c_stName), strValue(c_stValue) {} + std::string strName; + std::string strValue; + }; + typedef SArgumet TArg; + typedef std::list TArgList; + + struct SCmd + { + std::string name; + TArgList argList; + }; + typedef SCmd TCmd; + + class Group + { + public: + // The number of '\n' outside [...] commands, or -1 on a syntax error. + int Create(const std::string& stSource); + // Pops the next command; false when none is left. + bool GetCmd(TCmd& cmd); + // Peeks at the next command without popping it. + bool ReadCmd(TCmd& cmd); + std::string& GetError() { return m_stError; } + + private: + bool GetArg(const char* c_arg_base, int arg_len, TArgList& argList); + + std::string m_stError; + std::list m_cmdList; + }; +} diff --git a/src/eter_net/Ava2GcPacketTable.inc b/src/eter_net/Ava2GcPacketTable.inc new file mode 100644 index 00000000..1563a28e --- /dev/null +++ b/src/eter_net/Ava2GcPacketTable.inc @@ -0,0 +1,144 @@ +// Generated by tools/generate_ava2_gc_packet_table.py from the AVA2 Windows reference +// (CMainPacketHeaderMap in PythonNetworkStream.cpp + GamePhase() switch, Win32 i686 layout). +// {header, size, dynamic, in CMainPacketHeaderMap, handled by GamePhase()} + {1, 36, 0, 1, 1}, + {2, 5, 0, 1, 1}, + {3, 24, 0, 1, 1}, + {4, 9, 1, 1, 1}, + {5, 3, 1, 1, 1}, + {6, 270, 0, 1, 0}, + {7, 10, 0, 1, 0}, + {8, 72, 0, 1, 0}, + {9, 2, 0, 1, 0}, + {10, 1, 0, 1, 0}, + {11, 1, 0, 1, 0}, + {13, 5, 0, 1, 1}, + {14, 8, 0, 1, 1}, + {15, 45, 0, 1, 0}, + {16, 2041, 0, 1, 1}, + {17, 25, 0, 1, 1}, + {18, 7, 0, 1, 1}, + {19, 56, 0, 1, 1}, + {20, 135, 0, 1, 1}, + {21, 144, 0, 1, 1}, + {22, 16, 0, 1, 1}, + {25, 131, 0, 1, 1}, + {26, 104, 0, 1, 1}, + {27, 5, 0, 1, 1}, + {28, 4, 0, 1, 1}, + {29, 2, 0, 1, 1}, + {30, 3, 0, 1, 1}, + {31, 30, 0, 1, 1}, + {32, 444, 0, 1, 0}, + {34, 31, 0, 1, 1}, + {36, 11, 0, 1, 1}, + {38, 4, 1, 1, 1}, + {39, 5, 1, 1, 1}, + {40, 3, 1, 1, 1}, + {41, 10, 0, 1, 1}, + {42, 144, 0, 1, 1}, + {43, 6, 0, 1, 1}, + {44, 1, 0, 1, 1}, + {45, 6, 1, 1, 1}, + {46, 74, 0, 1, 1}, + {47, 4, 1, 1, 1}, + {48, 51, 0, 1, 1}, + {58, 17, 0, 1, 1}, + {61, 18, 0, 1, 1}, + {62, 9, 0, 1, 1}, + {63, 263, 0, 1, 1}, + {65, 15, 0, 1, 1}, + {66, 5, 1, 1, 1}, + {68, 37, 0, 1, 1}, + {69, 17, 0, 1, 1}, + {70, 10, 0, 1, 1}, + {71, 17, 0, 1, 1}, + {72, 256, 0, 1, 1}, + {73, 2, 0, 1, 0}, + {74, 4, 1, 1, 1}, + {75, 4, 1, 1, 1}, + {76, 1531, 0, 1, 1}, + {77, 5, 0, 1, 1}, + {78, 30, 0, 1, 1}, + {79, 21, 0, 1, 1}, + {80, 5, 0, 1, 1}, + {81, 6, 1, 1, 1}, + {82, 1, 0, 1, 1}, + {83, 2, 0, 1, 1}, + {84, 5, 0, 1, 1}, + {85, 135, 0, 1, 1}, + {86, 2, 0, 1, 1}, + {87, 1, 0, 1, 1}, + {88, 2, 0, 1, 1}, + {89, 7, 0, 1, 1}, + {90, 2, 0, 1, 0}, + {91, 9, 0, 1, 1}, + {92, 9, 0, 1, 1}, + {93, 5, 1, 1, 1}, + {95, 65, 0, 1, 1}, + {96, 0, 0, 0, 1}, + {97, 0, 0, 0, 1}, + {98, 0, 0, 0, 1}, + {99, 3397, 0, 1, 1}, + {106, 5, 0, 1, 1}, + {107, 30, 0, 1, 0}, + {110, 4, 1, 1, 1}, + {111, 6, 0, 1, 1}, + {112, 2, 0, 1, 1}, + {113, 46, 0, 1, 0}, + {114, 6, 0, 1, 1}, + {115, 5, 1, 1, 1}, + {116, 9, 0, 1, 0}, + {117, 52, 0, 1, 1}, + {118, 5, 0, 1, 0}, + {119, 66, 0, 1, 1}, + {120, 85, 0, 1, 1}, + {121, 3, 0, 1, 1}, + {122, 2, 0, 1, 1}, + {123, 14, 0, 1, 1}, + {124, 5, 0, 1, 1}, + {125, 43, 0, 1, 1}, + {126, 22, 0, 1, 1}, + {127, 6, 0, 1, 1}, + {128, 135, 0, 1, 1}, + {129, 2, 0, 1, 1}, + {130, 3, 1, 1, 1}, + {131, 27, 0, 1, 1}, + {132, 2, 0, 1, 1}, + {134, 10, 0, 1, 1}, + {135, 10, 0, 1, 1}, + {136, 75, 0, 1, 1}, + {137, 71, 0, 1, 0}, + {138, 75, 0, 1, 0}, + {141, 79001, 0, 1, 1}, + {150, 6, 0, 1, 0}, + {152, 11, 1, 1, 1}, + {153, 11, 1, 1, 1}, + {154, 37, 0, 1, 0}, + {156, 5, 1, 1, 1}, + {171, 7, 1, 1, 1}, + {201, 10, 0, 1, 0}, + {202, 1, 0, 1, 0}, + {203, 130, 0, 1, 0}, + {204, 403, 0, 1, 1}, + {205, 129, 0, 1, 1}, + {208, 133, 0, 1, 1}, + {209, 5, 0, 1, 1}, + {213, 2, 0, 1, 1}, + {214, 411, 0, 1, 1}, + {215, 23, 0, 1, 1}, + {216, 206, 0, 1, 1}, + {217, 618, 0, 1, 1}, + {218, 30, 0, 1, 1}, + {220, 114, 0, 1, 1}, + {221, 167, 0, 1, 1}, + {230, 58, 0, 1, 1}, + {231, 5, 0, 1, 1}, + {235, 5, 1, 1, 1}, + {241, 4, 0, 1, 1}, + {242, 1, 0, 1, 1}, + {249, 1025, 0, 1, 1}, + {252, 1, 0, 1, 1}, + {253, 2, 0, 1, 1}, + {254, 7, 0, 1, 0}, + {255, 13, 0, 1, 1}, diff --git a/src/eter_net/NetworkActorManager.cpp b/src/eter_net/NetworkActorManager.cpp index 4b09da36..13105360 100644 --- a/src/eter_net/NetworkActorManager.cpp +++ b/src/eter_net/NetworkActorManager.cpp @@ -1,5 +1,12 @@ #include "NetworkActorManager.h" #include "eter_render/TextTailManager.h" +#include "eter_effect/EffectManager.h" +#include "nonplayer_data.h" +#include "eter_render/RaceData.h" +#include +#include +#include +#include #include #include #include @@ -8,61 +15,391 @@ namespace ava2 { namespace { -std::string ResolveModelPath(const std::string& rel) { - if (std::filesystem::exists(rel)) return rel; - if (std::filesystem::exists("build/dev/" + rel)) return "build/dev/" + rel; - if (std::filesystem::exists("../" + rel)) return "../" + rel; - return rel; +// InstanceBaseEffect.cpp g_akD3DXClrName / g_akD3DXClrTitle / g_TitleNameMap: zero (transparent +// black) until introLoading.__main__ registers them through chrmgr. +std::array& NameColors() { static std::array s{}; return s; } +std::array& TitleColors() { static std::array s{}; return s; } +std::map& TitleNames() { static std::map s; return s; } +bool (*s_isPartyMemberByVID)(uint32_t) = nullptr; +int (*s_getNPCWear)(uint32_t, uint8_t) = nullptr; +bool (*s_getItemScale)(uint32_t, uint32_t, float[3], float[3]) = nullptr; +bool (*s_getItemData)(uint32_t, SItemModelData*) = nullptr; +bool s_hairColorEnable = false; // InstanceBase.cpp HAIR_COLOR_ENABLE=FALSE until app.SetHairColorEnable +bool s_armorSpecular = false; // USE_ARMOR_SPECULAR=FALSE until app.SetArmorSpecularEnable + +bool GetItemData(uint32_t vnum, SItemModelData* out) { return s_getItemData && s_getItemData(vnum, out); } + +// CItemData::GetWeaponType (ENABLE_WEAPON_COSTUME_SYSTEM): costume weapons carry the type in value 3. +uint32_t GetWeaponType(const SItemModelData& item) { + enum { ITEM_TYPE_COSTUME = 28, COSTUME_WEAPON = 4 }; + if (item.type == ITEM_TYPE_COSTUME && item.subType == COSTUME_WEAPON) return uint32_t(item.values[3]); + return item.subType; } -std::string GetRaceModelPath(uint32_t race) { - switch (race) { - case 0: return ResolveModelPath("ymir work/pc/warrior/warrior_assasin1.gr2"); - case 1: return ResolveModelPath("ymir work/pc/assassin/assassin_halloween1_lod_01.gr2"); - case 2: return ResolveModelPath("ymir work/pc/sura/sura_soccer1_germany_lod_02.gr2"); - case 3: return ResolveModelPath("ymir work/pc/shaman/shaman_fencing1_germany_lod_02.gr2"); - case 4: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/warrior_w.gr2"); - case 5: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/assassin_m.gr2"); - case 6: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/sura_w.gr2"); - case 7: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/shaman_m.gr2"); - case 101: return ResolveModelPath("ymir work/npc_mount/christmas_2017_sleddog/christmas_2017_sleddog.gr2"); - case 102: return ResolveModelPath("ymir work/monster/plechi_golden_frog/plechi_golden_frog.gr2"); - case 103: return ResolveModelPath("ymir work/monster/plechi_slime_monster1/plechi_slime_monster1.gr2"); - case 2018: return ResolveModelPath("ymir work/npc_mount/halloween_2018_cerberos/halloween_2018_cerberos.gr2"); - case 8001: case 8002: case 8003: return ResolveModelPath("ymir work/monster/metinstone_02/metinstone_10.gr2"); - case 20001: case 20016: return ResolveModelPath("ymir work/npc/12zi_statue_rabbit_npc/12zi_statue_rabbit_npc.gr2"); - default: return ResolveModelPath("ymir work/pc/warrior/warrior_assasin1.gr2"); - } +// InstanceBase.cpp __ArmorVnumToShape. +bool ArmorVnumToShape(uint32_t vnum, uint32_t* shape) { + *shape = vnum; + if (vnum == 0 || vnum == 1) return false; + if (!s_armorSpecular) return false; + SItemModelData item; + if (!GetItemData(vnum, &item)) return false; + *shape = uint32_t(item.values[3]); + return true; } -std::string GetWeaponModelPath(uint32_t weapon) { - if (weapon > 0) { - return ResolveModelPath("ymir work/item/weapon/set_11_sword.gr2"); - } - return ""; +constexpr uint8_t kTypePC = 6; // CActorInstance::TYPE_PC +bool IsPC(const SNetworkActorData& actor) { return actor.m_bType == kTypePC; } + +// InstanceBase.h RaceToJob / RaceToSex (ENABLE_WOLFMAN_CHARACTER off). +int RaceToJob(int race) { return race % 4; } +int RaceToSex(int race) { + switch (race) { case 0: case 2: case 5: case 7: return 1; default: return 0; } } -std::string GetHairModelPath(uint32_t hair) { - if (hair > 0) { - return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/hair/warrior_m.gr2"); - } - return ""; +uint32_t RGBToColor(unsigned r, unsigned g, unsigned b) { + // __RGBToD3DXColoru: 0xff alpha, components shifted in without masking. + uint32_t c = 0xff; c <<= 8; c |= r; c <<= 8; c |= g; c <<= 8; c |= b; + return c; } -std::string GetAlignmentTitle(int16_t alignment, uint32_t& titleColor) { - if (alignment >= 12000) { titleColor = 0xFF00BFFF; return "Chivalric"; } - if (alignment >= 8000) { titleColor = 0xFF1E90FF; return "Noble"; } - if (alignment >= 4000) { titleColor = 0xFF6495ED; return "Good"; } - if (alignment >= 1000) { titleColor = 0xFF87CEEB; return "Friendly"; } - if (alignment > -1000) { titleColor = 0xFFFFFFFF; return ""; } - if (alignment > -4000) { titleColor = 0xFFFF8C00; return "Aggressive"; } - if (alignment > -8000) { titleColor = 0xFFFF4500; return "Fraudulent"; } - if (alignment > -12000) { titleColor = 0xFFFF0000; return "Malicious"; } - titleColor = 0xFF8B0000; return "Cruel"; +// CInstanceBase::ms_astAffectEffectAttachBone / ms_adwCRCAffectEffect. +std::unordered_map& EffectAttachBones() { static std::unordered_map s; return s; } +std::unordered_map& EffectCRCs() { static std::unordered_map s; return s; } + +bool IsAffect(const SNetworkActorData& actor, unsigned affect) { + return affect < 64 && (actor.m_affectFlags[affect / 32] & (1u << (affect % 32))) != 0; } } // namespace +bool NetworkActorManager::RegisterEffect(unsigned type, const std::string& bone, const std::string& file, bool isCache) { + (void)isCache; // CEffectManager::RegisterEffect2 cache flag: the port keeps every loaded script. + if (type >= EFFECT_NUM) return false; + + EffectAttachBones()[type] = bone; + uint32_t& crc = EffectCRCs()[type]; + if (!EffectManager::Instance().RegisterEffect(file, &crc)) { + std::cerr << "[AVA2 TraceError] CInstanceBase::RegisterEffect(eEftType=" << type << ", c_szEftAttachBone=" << bone + << ", c_szEftName=" << file << ", isCache=" << (isCache ? 1 : 0) << ") - Error" << std::endl; + crc = 0; + return false; + } + return true; +} + +uint32_t NetworkActorManager::GetEffectCRC(unsigned type) { + auto it = EffectCRCs().find(type); + return it != EffectCRCs().end() ? it->second : 0; +} + +std::string NetworkActorManager::GetEffectAttachBone(unsigned type) { + auto it = EffectAttachBones().find(type); + return it != EffectAttachBones().end() ? it->second : std::string(); +} + +uint32_t NetworkActorManager::NowMSec() const { + if (m_now) return m_now(); + static const auto start = std::chrono::steady_clock::now(); + return static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()); +} + +uint32_t NetworkActorManager::AttachEffectByID(SNetworkActorData& actor, const std::string& bone, uint32_t crc, float offsetHeight) { + float x = static_cast(actor.m_lCurX), y = static_cast(actor.m_lCurZ), z = static_cast(actor.m_lCurY), yaw = actor.m_fRot; + if (actor.m_pActorInstance) { + x = actor.m_pActorInstance->GetX(); y = actor.m_pActorInstance->GetY(); z = actor.m_pActorInstance->GetZ(); + yaw = actor.m_pActorInstance->GetYaw(); + if (!bone.empty()) actor.m_pActorInstance->GetBonePosition(bone, x, y, z); + } + if (bone.empty()) y += offsetHeight; + const uint32_t id = EffectManager::Instance().CreateEffect(crc, x, y, z, yaw); + if (id) actor.m_attachedEffects.push_back(SAttachedEffect{id, bone, offsetHeight}); + return id; +} + +void NetworkActorManager::DestroyAttachedEffects(SNetworkActorData& actor) { + for (const auto& eft : actor.m_attachedEffects) EffectManager::Instance().DestroyEffectInstance(eft.instanceId); + actor.m_attachedEffects.clear(); +} + +uint32_t NetworkActorManager::AttachSpecialEffect(uint32_t vid, unsigned type) { + auto* actor = GetActorData(vid); + if (!actor) return 0; + if (IsAffect(*actor, AFFECT_INVISIBILITY)) return 0; + if (type >= EFFECT_NUM) return 0; + + const std::string bone = GetEffectAttachBone(type); + if (bone.empty()) return AttachEffectByID(*actor, "", GetEffectCRC(type), 0.0f); + if (bone == "PART_WEAPON" || bone == "PART_WEAPON_LEFT") { + // GetAttachingBoneName(PART_WEAPON[_LEFT]): fails (no effect) when no weapon is attached. + if (actor->m_dwWeapon == 0) return 0; + // The bone name comes from the race (warrior equip_right_hand, others equip_right/equip_left). + const uint32_t part = bone == "PART_WEAPON" ? RaceData::PART_WEAPON : RaceData::PART_WEAPON_LEFT; + std::string raceBone; + const RaceData* race = RaceManager::Instance().GetRaceDataPointer(actor->m_dwRace); + if (!race || !race->GetAttachingBoneName(part, &raceBone)) return 0; + return AttachEffectByID(*actor, raceBone, GetEffectCRC(type), 0.0f); + } + return AttachEffectByID(*actor, bone, GetEffectCRC(type), 0.0f); +} + +void NetworkActorManager::CreateSpecialEffect(uint32_t vid, unsigned type) { + auto* actor = GetActorData(vid); + if (!actor) return; + float x = static_cast(actor->m_lCurX), y = static_cast(actor->m_lCurZ), z = static_cast(actor->m_lCurY), yaw = actor->m_fRot; + if (actor->m_pActorInstance) { + x = actor->m_pActorInstance->GetX(); y = actor->m_pActorInstance->GetY(); z = actor->m_pActorInstance->GetZ(); + yaw = actor->m_pActorInstance->GetYaw(); + } + EffectManager::Instance().CreateEffect(GetEffectCRC(type), x, y, z, yaw); +} + +bool NetworkActorManager::IsPossibleEmoticon(uint32_t vid) const { + const auto* actor = GetActorData(vid); + if (!actor) return false; + // Windows passes the registered effect CRC to IsAliveEffect (an instance-index lookup). + for (unsigned e = 0; e < EMOTICON_NUM; ++e) { + const uint32_t effectID = GetEffectCRC(EFFECT_EMOTICON + e); + if (effectID && EffectManager::Instance().IsAliveEffect(effectID)) return false; + } + return NowMSec() - actor->m_dwEmoticonTime >= 1000; +} + +void NetworkActorManager::SetEmoticon(uint32_t vid, unsigned emoticon) { + auto* actor = GetActorData(vid); + if (!actor) return; + if (emoticon >= EMOTICON_NUM) { + std::cerr << "[AVA2 TraceError] CInstanceBase[VID:" << vid << "]::SetEmoticon(eEmoticon:" << emoticon << "m_pActorInstance ? actor->m_pActorInstance->GetHeightOffset() : 0.0f; + AttachEffectByID(*actor, "", GetEffectCRC(EFFECT_EMOTICON + emoticon), height); + actor->m_dwEmoticonTime = NowMSec(); +} + +bool NetworkActorManager::RegisterNameColor(unsigned index, unsigned r, unsigned g, unsigned b) { + if (index >= NAMECOLOR_NUM) return false; + NameColors()[index] = RGBToColor(r, g, b); + return true; +} + +bool NetworkActorManager::RegisterTitleColor(unsigned index, unsigned r, unsigned g, unsigned b) { + if (index >= TITLE_NUM) return false; + TitleColors()[index] = RGBToColor(r, g, b); + return true; +} + +void NetworkActorManager::RegisterTitleName(int index, const std::string& name) { + TitleNames().insert(std::make_pair(index, name)); // std::map::insert keeps the first name +} + +void NetworkActorManager::SetEmpireNameMode(bool enable) { + auto& c = NameColors(); + if (enable) { + c[NAMECOLOR_MOB] = c[NAMECOLOR_EMPIRE_MOB]; + c[NAMECOLOR_NPC] = c[NAMECOLOR_EMPIRE_NPC]; + c[NAMECOLOR_PC] = c[NAMECOLOR_NORMAL_PC]; + for (unsigned empire = 1; empire < EMPIRE_NUM; ++empire) + c[NAMECOLOR_PC + empire] = c[NAMECOLOR_EMPIRE_PC + empire]; + } else { + c[NAMECOLOR_MOB] = c[NAMECOLOR_NORMAL_MOB]; + c[NAMECOLOR_NPC] = c[NAMECOLOR_NORMAL_NPC]; + for (unsigned empire = 0; empire < EMPIRE_NUM; ++empire) + c[NAMECOLOR_PC + empire] = c[NAMECOLOR_NORMAL_PC]; + } +} + +uint32_t NetworkActorManager::GetIndexedNameColor(unsigned index) { + return index >= NAMECOLOR_NUM ? 0xffffffff : NameColors()[index]; +} + +unsigned NetworkActorManager::GetAlignmentGrade(int16_t alignment) { + if (alignment >= 12000) return 0; + if (alignment >= 8000) return 1; + if (alignment >= 4000) return 2; + if (alignment >= 1000) return 3; + if (alignment >= 0) return 4; + if (alignment > -4000) return 5; + if (alignment > -8000) return 6; + if (alignment > -12000) return 7; + return 8; +} + +void NetworkActorManager::SetPartyMemberQuery(bool (*query)(uint32_t)) { s_isPartyMemberByVID = query; } +bool NetworkActorManager::IsPartyMember(uint32_t vid) { return s_isPartyMemberByVID && s_isPartyMemberByVID(vid); } +void NetworkActorManager::SetNPCWearQuery(int (*query)(uint32_t, uint8_t)) { s_getNPCWear = query; } +void NetworkActorManager::SetItemScaleQuery(bool (*query)(uint32_t, uint32_t, float[3], float[3])) { s_getItemScale = query; } +void NetworkActorManager::SetItemDataQuery(bool (*query)(uint32_t, SItemModelData*)) { s_getItemData = query; } +void NetworkActorManager::SetHairColorEnable(bool enable) { s_hairColorEnable = enable; } +void NetworkActorManager::SetArmorSpecularEnable(bool enable) { s_armorSpecular = enable; } + +// CInstanceBase::SetArmor. __GetRefinedEffect / __ClearArmorRefineEffect are not ported. +void NetworkActorManager::SetArmor(SNetworkActorData& actor, uint32_t armor) { + uint32_t shape; + if (ArmorVnumToShape(armor, &shape)) { + SItemModelData item; + if (GetItemData(armor, &item)) { + SetShape(actor, shape, item.specular); + return; + } + } + SetShape(actor, armor); +} + +// CInstanceBase::SetShape (IsPoly() never holds for network actors in the port). +void NetworkActorManager::SetShape(SNetworkActorData& actor, uint32_t shape, float specular) { + if (actor.m_pActorInstance) actor.m_pActorInstance->SetShape(shape, specular); + actor.m_awPart[RaceData::PART_MAIN] = shape; +} + +// CInstanceBase::SetHair. +void NetworkActorManager::SetHair(SNetworkActorData& actor, uint32_t hair) { + if (!s_hairColorEnable) return; + if (!IsPC(actor) && actor.m_dwRace > 8) return; + actor.m_awPart[RaceData::PART_HAIR] = hair; + if (actor.m_pActorInstance) actor.m_pActorInstance->SetHair(hair); +} + +// CInstanceBase::SetWeapon(eWeapon, eArrow). Weapon refine / shining effects are not ported. +bool NetworkActorManager::SetWeapon(SNetworkActorData& actor, uint32_t weapon, uint32_t arrow) { + const uint32_t shape = actor.m_pActorInstance ? actor.m_pActorInstance->GetShape() : actor.m_awPart[RaceData::PART_MAIN]; + if (shape >= 100 && shape <= 103) return false; // __IsShapeAnimalWear + actor.m_awPart[RaceData::PART_ARROW_TYPE] = arrow; + // __IsChangableWeapon: the wedding dress (shape 201) only holds the bouquets. + if (shape == 201 && !(weapon >= 50201 && weapon <= 50204)) weapon = 0; + if (actor.m_pActorInstance) { + SItemModelData item; + if (GetItemData(weapon, &item)) { + ActorInstance::SPartItem part{item.model, GetWeaponType(item)}; + actor.m_pActorInstance->AttachWeapon(weapon, &part, actor.m_dwMountVnum != 0); + } else { + actor.m_pActorInstance->AttachWeapon(weapon, nullptr, actor.m_dwMountVnum != 0); + } + } + actor.m_awPart[RaceData::PART_WEAPON] = weapon; + return true; +} + +// CInstanceBase::ChangeArmor: rebuilds the race and re-applies hair / sash / weapon. +bool NetworkActorManager::ChangeArmor(SNetworkActorData& actor, uint32_t armor) { + uint32_t shape; + ArmorVnumToShape(armor, &shape); + if (!actor.m_pActorInstance || actor.m_pActorInstance->GetShape() == shape) return false; + const uint32_t hair = actor.m_awPart[RaceData::PART_HAIR]; + const uint32_t sash = actor.m_awPart[RaceData::PART_SASH]; + const uint32_t weapon = actor.m_awPart[RaceData::PART_WEAPON]; + if (!actor.m_pActorInstance->SetRace(actor.m_dwRace)) { + std::cerr << "[AVA2 TraceError] CPythonCharacterManager::ChangeArmor - SetRace VID[" << actor.m_dwVID + << "] Race[" << actor.m_dwRace << "] ERROR" << std::endl; + return false; + } + SetArmor(actor, armor); + SetHair(actor, hair); + Instance().SetSash(actor.m_dwVID, sash); + SetWeapon(actor, weapon); + actor.m_pActorInstance->PlayMotion(MotionType::Wait, true); // RefreshState(NAME_WAIT) + return true; +} + +// CInstanceBase::ChangeWeapon(eWeapon, eArrow). The bow motion-mode switch is not ported. +void NetworkActorManager::ChangeWeapon(SNetworkActorData& actor, uint32_t weapon, uint32_t arrow) { + actor.m_awPart[RaceData::PART_ARROW_TYPE] = arrow; + if (!actor.m_pActorInstance) return; + if (weapon == actor.m_pActorInstance->GetPartItemID(RaceData::PART_WEAPON)) return; + if (SetWeapon(actor, weapon, arrow)) actor.m_pActorInstance->PlayMotion(MotionType::Wait, true); +} + +// CInstanceBase::ChangeHair. +void NetworkActorManager::ChangeHair(SNetworkActorData& actor, uint32_t hair) { + if (!s_hairColorEnable) return; + if (!IsPC(actor)) return; + if (actor.m_awPart[RaceData::PART_HAIR] == hair) return; + SetHair(actor, hair); + if (actor.m_pActorInstance) actor.m_pActorInstance->PlayMotion(MotionType::Wait, true); +} + +// CInstanceBase::IsGameMaster. +bool IsGameMaster(const SNetworkActorData& a) { + return a.m_stName.find('[') != std::string::npos || IsAffect(a, 0 /* AFFECT_YMIR */); +} + +namespace { +// CActorInstance::TYPE_* (GameLib/ActorInstance.h, ENABLE_NEW_PET_SYSTEM on). +enum { TYPE_ENEMY = 0, TYPE_NPC = 1, TYPE_PC = 6, TYPE_POLY = 7, TYPE_PET = 10 }; + +bool IsSameEmpire(const SNetworkActorData& self, const SNetworkActorData& dst) { + if (dst.m_dwEmpireID == 0) return true; + if (IsGameMaster(self) || IsGameMaster(dst)) return true; + return dst.m_dwEmpireID == self.m_dwEmpireID; +} +} // namespace + +bool IsBossRace(uint32_t race) { + // CInstanceBase::IsBoss (NAMECOLOR_BOSS_CLIENT). + static const uint32_t races[] = {691,692,693,791,991,992,993,1091,1092,1093,1094,1095,2191,1191,1192,1304,1306,1307, + 1901,1902,1903,2206,2207,2291,2306,2307,2492,2493,2494,2598,3090,3091,3190,3191,3290,3291,3390,3391,3490,3491, + 3590,3591,3690,3691,3790,3791,3890,3891,5001,5004,5002,5161,5162,5163,6091,6191,20035,20036,20037}; + return std::find(std::begin(races), std::end(races), race) != std::end(races); +} + +unsigned NetworkActorManager::GetNameColorIndex(uint32_t vid) const { + const auto* self = GetActorData(vid); + if (!self) return 0xffffffff; + if (self->m_bType == TYPE_PC) { + if (self->m_dwStateFlags & ADD_CHARACTER_STATE_KILLER) return NAMECOLOR_PK; + const auto* main = GetActorData(m_mainVID); + if (main && vid != m_mainVID) { + if (main->m_duelMode) { + switch (main->m_duelMode) { + case DUEL_CANNOTATTACK: return NAMECOLOR_PC + self->m_dwEmpireID; + case DUEL_START: return FindDUELKey(m_mainVID, vid) ? unsigned(NAMECOLOR_PVP) : NAMECOLOR_PC + self->m_dwEmpireID; + } + } + if (IsSameEmpire(*main, *self)) { + if (FindPVPKey(m_mainVID, vid)) return NAMECOLOR_PVP; + if (FindGVGKey(main->m_dwGuildID, self->m_dwGuildID)) return NAMECOLOR_PVP; + } else { + return NAMECOLOR_PVP; + } + } + if (s_isPartyMemberByVID && s_isPartyMemberByVID(vid)) return NAMECOLOR_PARTY; + return NAMECOLOR_PC + self->m_dwEmpireID; + } + if (self->m_bType == TYPE_PET) return NAMECOLOR_NPC; + if (self->m_bType == TYPE_NPC) { + if (self->m_dwRace >= 30000 && self->m_dwRace <= 30020) return NAMECOLOR_SHOP; // CActorInstance::IsShop + return NAMECOLOR_NPC; + } + if (self->m_bType == TYPE_ENEMY) return IsBossRace(self->m_dwRace) ? unsigned(NAMECOLOR_BOSS) : NAMECOLOR_MOB; + if (self->m_bType == TYPE_POLY) return NAMECOLOR_MOB; + return 0xffffffff; // D3DXCOLOR(0xffffffff) converted to UINT: out of range -> white +} + +void NetworkActorManager::RefreshTextTail(uint32_t vid) { + const auto* self = GetActorData(vid); + if (!self) return; + auto& tt = TextTailManager::Instance(); + tt.SetCharacterTextTailColor(vid, GetIndexedNameColor(GetNameColorIndex(vid))); + const unsigned grade = GetAlignmentGrade(self->m_sAlignment); + if (grade == TITLE_NONE) { + tt.DetachTitle(vid); + } else { + auto it = TitleNames().find(int(grade)); + if (it != TitleNames().end()) tt.AttachTitle(vid, it->second, grade < TITLE_NUM ? TitleColors()[grade] : 0xffffffff); + } +} + +void NetworkActorManager::RefreshAllPCTextTail() { + for (const auto& [vid, actor] : m_actors) + if (actor.m_bType == TYPE_PC) RefreshTextTail(vid); +} + +void NetworkActorManager::ChangeGVG(uint32_t srcGuild, uint32_t dstGuild) { + for (const auto& [vid, actor] : m_actors) + if (actor.m_dwGuildID == srcGuild || actor.m_dwGuildID == dstGuild) RefreshTextTail(vid); +} + NetworkActorManager& NetworkActorManager::Instance() { static NetworkActorManager s_instance; return s_instance; @@ -77,6 +414,31 @@ void NetworkActorManager::SetMainActorVID(uint32_t vid) { void NetworkActorManager::AppendActor(const SNetworkActorData& data) { auto& actorData = m_actors[data.m_dwVID]; actorData = data; + actorData.m_dwVirtualNumber = data.m_dwRace; // SetVirtualNumber(c_rkCreateData.m_dwRace) + actorData.m_dwSash = 0; + + // CInstanceBase::Create (ENABLE_NPC_WEAR_ITEM): an npc_wear row replaces the race and all + // parts; otherwise only PCs take hair/sash/weapon/shining from the add packet. + using NPD = NonPlayerData; + const int npcRace = s_getNPCWear ? s_getNPCWear(data.m_dwRace, NPD::NPC_WEAR_RACE) : -1; + uint32_t sash = 0; + if (npcRace != -1) { + actorData.m_dwRace = uint32_t(npcRace); + const int mount = s_getNPCWear(data.m_dwRace, NPD::NPC_WEAR_MOUNT); + actorData.m_dwMountVnum = mount != 0 ? uint32_t(mount) : 0; + actorData.m_dwArmor = uint32_t(s_getNPCWear(data.m_dwRace, NPD::NPC_WEAR_ARMOR)); + actorData.m_dwWeapon = uint32_t(s_getNPCWear(data.m_dwRace, NPD::NPC_WEAR_WEAPON)); + actorData.m_dwArrowType = 0; + actorData.m_dwHair = uint32_t(s_getNPCWear(data.m_dwRace, NPD::NPC_WEAR_HAIR)); + sash = uint32_t(s_getNPCWear(data.m_dwRace, NPD::NPC_WEAR_ACCE) - 85000); + for (int i = 0; i < CHR_SHINING_NUM; ++i) + actorData.m_shining[i] = uint32_t(s_getNPCWear(data.m_dwRace, uint8_t(NPD::NPC_WEAR_SHINING_WEAPON1 + i))); + } else if (data.m_bType == 6) { // IsPC() + sash = data.m_dwSash; + } else { + actorData.m_dwWeapon = actorData.m_dwHair = actorData.m_dwArrowType = 0; + std::fill(std::begin(actorData.m_shining), std::end(actorData.m_shining), 0u); + } // Instantiate 3D ActorInstance auto actor = std::make_shared(); @@ -92,33 +454,34 @@ void NetworkActorManager::AppendActor(const SNetworkActorData& data) { float worldZ = static_cast(data.m_lCurY); actor->SetPosition(worldX, worldY, worldZ); - std::string modelPath = GetRaceModelPath(data.m_dwRace); - if (!modelPath.empty()) { - actor->SetModel(modelPath); - } - - if (data.m_dwWeapon > 0) { - std::string weaponPath = GetWeaponModelPath(data.m_dwWeapon); - if (!weaponPath.empty()) { - actor->SetWeapon(weaponPath, "equip_right_hand"); - } - } - - if (data.m_dwHair > 0) { - std::string hairPath = GetHairModelPath(data.m_dwHair); - if (!hairPath.empty()) { - actor->AttachPart(hairPath); + actorData.m_pActorInstance = actor; + std::fill(std::begin(actorData.m_awPart), std::end(actorData.m_awPart), 0u); + // CInstanceBase::Create: SetRace(npc wear race or race). A failed SetRace makes Create fail on + // Windows; the port keeps the model-less instance so the name tail and movement still work. + if (!actor->SetRace(actorData.m_dwRace)) + std::cerr << "[AVA2 TraceError] CInstanceBase::Create - SetRace(" << actorData.m_dwRace << ") failed" << std::endl; + if (npcRace != -1) { + SetArmor(actorData, actorData.m_dwArmor); + SetWeapon(actorData, actorData.m_dwWeapon); + SetHair(actorData, actorData.m_dwHair); + SetSash(data.m_dwVID, sash); + } else { + SetArmor(actorData, actorData.m_dwArmor); + if (IsPC(actorData)) { + SetHair(actorData, actorData.m_dwHair); + SetSash(data.m_dwVID, sash); + SetWeapon(actorData, actorData.m_dwWeapon, actorData.m_dwArrowType); } } + actor->PlayMotion(MotionType::Wait, true); // AVA2 InstanceBase::SetAffect(AFFECT_STUN=5) controls the sleep action flag. actor->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0); - actorData.m_pActorInstance = actor; // Register TextTail overhead display auto& tt = TextTailManager::Instance(); - uint32_t nameColor = (data.m_bType == 0) ? 0xFFFF4444 : 0xFFFFFFFF; // Red for mobs, white for players - tt.RegisterCharacterTextTail(data.m_dwGuildID, data.m_dwVID, nameColor); + // AttachTextTail registers white; RefreshTextTail below applies GetNameColor/title. + tt.RegisterCharacterTextTail(data.m_dwGuildID, data.m_dwVID, 0xFFFFFFFF); tt.SetCharacterName(data.m_dwVID, data.m_stName); tt.SetCharacterPosition(data.m_dwVID, worldX, worldY, worldZ); @@ -130,13 +493,7 @@ void NetworkActorManager::AppendActor(const SNetworkActorData& data) { tt.SetGuildName(data.m_dwVID, data.m_stGuildName); } - if (data.m_sAlignment != 0) { - uint32_t titleColor = 0xFFFFFFFF; - std::string title = GetAlignmentTitle(data.m_sAlignment, titleColor); - if (!title.empty()) { - tt.AttachTitle(data.m_dwVID, title, titleColor); - } - } + RefreshTextTail(data.m_dwVID); if (IsMainActorVID(data.m_dwVID)) { m_mainPosX = data.m_lCurX; @@ -147,7 +504,12 @@ void NetworkActorManager::AppendActor(const SNetworkActorData& data) { void NetworkActorManager::RemoveActor(uint32_t vid) { auto it = m_actors.find(vid); if (it != m_actors.end()) { + DestroyAttachedEffects(it->second); m_actors.erase(it); + // CPythonCharacterManager::DeleteInstance drops m_pkInstBind / m_pkInstPick (and + // m_pkInstMain; the port's main VID is set from packets before the actor exists, so it stays). + if (m_hasSelected && m_selectedVID == vid) m_hasSelected = false; + if (m_hasPicked && m_pickedVID == vid) m_hasPicked = false; } TextTailManager::Instance().DeleteCharacterTextTail(vid); } @@ -157,7 +519,6 @@ void NetworkActorManager::UpdateActor(const SNetworkUpdateActorData& data) { if (it == m_actors.end()) return; auto& actorData = it->second; - actorData.m_dwSash = data.m_dwSash; actorData.m_dwArrowType = data.m_dwArrowType; actorData.m_dwConquerorLevel = data.m_dwConquerorLevel; actorData.m_dwStateFlags = data.m_dwStateFlags; @@ -165,7 +526,7 @@ void NetworkActorManager::UpdateActor(const SNetworkUpdateActorData& data) { std::copy_n(data.m_shining, CHR_SHINING_NUM, actorData.m_shining); actorData.m_dwArmor = data.m_dwArmor; actorData.m_dwWeapon = data.m_dwWeapon; - actorData.m_dwHair = data.m_dwHair; + if (actorData.m_bType == 6) actorData.m_dwHair = data.m_dwHair; // ChangeHair: IsPC() only actorData.m_dwGuildID = data.m_dwGuildID; actorData.m_sAlignment = data.m_sAlignment; actorData.m_byPKMode = data.m_byPKMode; @@ -173,33 +534,20 @@ void NetworkActorManager::UpdateActor(const SNetworkUpdateActorData& data) { actorData.m_dwMovSpd = data.m_dwMovSpd; actorData.m_dwAtkSpd = data.m_dwAtkSpd; + // CNetworkActorManager::UpdateActor: ChangeArmor, ChangeWeapon(weapon, arrow), ChangeHair, ChangeSash. + ChangeArmor(actorData, data.m_dwArmor); + ChangeWeapon(actorData, data.m_dwWeapon, data.m_dwArrowType); + ChangeHair(actorData, data.m_dwHair); if (actorData.m_pActorInstance) { actorData.m_pActorInstance->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0); - if (data.m_dwWeapon > 0) { - std::string weaponPath = GetWeaponModelPath(data.m_dwWeapon); - if (!weaponPath.empty()) { - actorData.m_pActorInstance->SetWeapon(weaponPath, "equip_right_hand"); - } - } - if (data.m_dwHair > 0) { - std::string hairPath = GetHairModelPath(data.m_dwHair); - if (!hairPath.empty()) { - actorData.m_pActorInstance->AttachPart(hairPath); - } - } if (data.m_dwMovSpd > 0) { actorData.m_pActorInstance->SetSpeed(static_cast(data.m_dwMovSpd)); } } - auto& tt = TextTailManager::Instance(); - if (data.m_sAlignment != 0) { - uint32_t titleColor = 0xFFFFFFFF; - std::string title = GetAlignmentTitle(data.m_sAlignment, titleColor); - if (!title.empty()) { - tt.AttachTitle(data.m_dwVID, title, titleColor); - } - } + ChangeSash(data.m_dwVID, data.m_dwSash); + // ChangeGuild / SetAlignment / SetStateFlags(KILLER) each end in RefreshTextTail. + RefreshTextTail(data.m_dwVID); } void NetworkActorManager::MoveActor(const SNetworkMoveActorData& data) { @@ -260,7 +608,7 @@ void NetworkActorManager::SetActorOwner(uint32_t ownerVID, uint32_t victimVID) { } } -void NetworkActorManager::Update(float dt, const TerrainHeightmap* terrain) { +void NetworkActorManager::Update(float dt, const TerrainHeightSource* terrain) { for (auto& [vid, actorData] : m_actors) { if (!actorData.m_pActorInstance) continue; @@ -305,16 +653,145 @@ void NetworkActorManager::Update(float dt, const TerrainHeightmap* terrain) { } actorData.m_pActorInstance->Update(dt, terrain); + + auto& effects = actorData.m_attachedEffects; + for (auto e = effects.begin(); e != effects.end();) { + auto& eftMgr = EffectManager::Instance(); + if (!eftMgr.IsAliveEffect(e->instanceId)) { e = effects.erase(e); continue; } + const auto& inst = *actorData.m_pActorInstance; + float x = inst.GetX(), y = inst.GetY() + (e->bone.empty() ? e->offsetHeight : 0.0f), z = inst.GetZ(); + if (!e->bone.empty()) inst.GetBonePosition(e->bone, x, y, z); + eftMgr.SetEffectInstancePosition(e->instanceId, x, y, z); + eftMgr.SetEffectInstanceRotation(e->instanceId, inst.GetYaw(), 0.0f, 0.0f); + ++e; + } } } void NetworkActorManager::Clear() { + // CPythonCharacterManager::DeleteAllInstances: each CInstanceBase::Destroy detaches its text tail. + for (auto& [vid, actorData] : m_actors) { + DestroyAttachedEffects(actorData); + TextTailManager::Instance().DeleteCharacterTextTail(vid); + } m_actors.clear(); + m_hasSelected = false; + m_hasPicked = false; + ClearPVPKeySystem(); m_mainVID = 0; m_mainPosX = 0; m_mainPosY = 0; } +void NetworkActorManager::Destroy() { + Clear(); + std::fill(std::begin(m_adwPointEffect), std::end(m_adwPointEffect), 0u); +} + +SNetworkActorData* NetworkActorManager::RegisterInstance(uint32_t vid) { + if (m_actors.count(vid)) return nullptr; + auto& actorData = m_actors[vid]; + actorData.m_dwVID = vid; + actorData.m_bType = TYPE_PC; // CActorInstance::__Initialize: m_eActorType = TYPE_PC + // CInstanceBase::New: an empty graphic instance; chr.SetRace/SetArmor build it afterwards. + auto actor = std::make_shared(); + actor->SetVID(vid); + actor->SetScale(0.8f); // AppendActor's port scale + actorData.m_pActorInstance = actor; + return &actorData; +} + +void NetworkActorManager::SelectInstance(uint32_t vid) { + if (!m_actors.count(vid)) return; // Tracef("SelectCharacterInstance: no vid by %d") + m_selectedVID = vid; + m_hasSelected = true; +} + +SNetworkActorData* NetworkActorManager::GetSelectedInstance() { + return m_hasSelected ? GetActorData(m_selectedVID) : nullptr; +} + +bool NetworkActorManager::OLD_GetPickedInstanceVID(uint32_t* vid) const { + if (!m_hasPicked || !m_actors.count(m_pickedVID)) return false; + *vid = m_pickedVID; + return true; +} + +namespace { +float s_dustGap = 0.0f; +float s_horseDustGap = 0.0f; +} +void NetworkActorManager::SetDustGap(float gap) { s_dustGap = gap; } +void NetworkActorManager::SetHorseDustGap(float gap) { s_horseDustGap = gap; } +float NetworkActorManager::GetDustGap() { return s_dustGap; } +float NetworkActorManager::GetHorseDustGap() { return s_horseDustGap; } + +bool NetworkActorManager::RegisterPointEffect(uint32_t point, const std::string& file) { + if (point >= 255) return false; // POINT_MAX_NUM + EffectManager::Instance().RegisterEffect(file, &m_adwPointEffect[point]); // RegisterEffect2 + return true; +} + +// CPythonCharacterManager::ShowPointEffect: POINT_LEVEL(1) / POINT_CONQUEROR_LEVEL -> LevelUp, +// POINT_LEVEL_STEP(25) / POINT_CONQUEROR_LEVEL_STEP -> SkillUp. The registered point effects are +// not used by it (LevelUp/SkillUp attach EFFECT_LEVELUP/EFFECT_SKILLUP). +void NetworkActorManager::ShowPointEffect(uint32_t point, uint32_t vid) { + SNetworkActorData* actor = vid == 0xffffffffu ? GetMainInstance() : GetActorData(vid); + if (!actor) return; + enum { POINT_LEVEL = 1, POINT_LEVEL_STEP = 25, POINT_CONQUEROR_LEVEL = 205, POINT_CONQUEROR_LEVEL_STEP = 206 }; + switch (point) { + case POINT_LEVEL: case POINT_CONQUEROR_LEVEL: AttachSpecialEffect(actor->m_dwVID, EFFECT_LEVELUP); break; + case POINT_LEVEL_STEP: case POINT_CONQUEROR_LEVEL_STEP: AttachSpecialEffect(actor->m_dwVID, EFFECT_SKILLUP); break; + } +} + +// CInstanceBase::__SetAffect. The alpha blends (EUNHYEONG / REVIVE_INVISIBILITY), the warrior +// geomgyeong weapon effect and CHEONGEUN resist-fallen are not ported; their effect bookkeeping is. +void NetworkActorManager::SCRIPT_SetAffect(uint32_t vid, unsigned affect, bool isVisible) { + SNetworkActorData* actor = vid == 0xffffffffu ? GetSelectedInstance() : GetActorData(vid); + if (!actor) return; + enum { AFFECT_YMIR = 0, AFFECT_INVISIBILITY = 1, AFFECT_STUN = 5, AFFECT_GEOMGYEONG = 15, + AFFECT_GYEONGGONG = 17, AFFECT_KWAESOK = 24, AFFECT_NUM = 64, EFFECT_AFFECT = 27 }; + switch (affect) { + case AFFECT_YMIR: + if (IsAffect(*actor, AFFECT_INVISIBILITY)) return; + break; + case AFFECT_GEOMGYEONG: + return; // __Warrior_SetGeomgyeongAffect + case AFFECT_GYEONGGONG: + case AFFECT_KWAESOK: + if (isVisible && !actor->m_isMoving) return; // !IsWalking(): CActorInstance walking = moving + break; + case AFFECT_INVISIBILITY: + if (isVisible) { + DestroyAttachedEffects(*actor); // ClearAttachingEffect + __EffectContainer_Destroy + TextTailManager::Instance().DeleteCharacterTextTail(actor->m_dwVID); // DetachTextTail + } else { + RefreshTextTail(actor->m_dwVID); + } + return; + case AFFECT_STUN: + if (actor->m_pActorInstance) actor->m_pActorInstance->SetSleep(isVisible); + break; + } + if (affect >= AFFECT_NUM) { + std::cerr << "[AVA2 TraceError] CInstanceBase[VID:" << actor->m_dwVID << "]::SetAffect(eAffect:" << affect + << "m_adwAffectEffect[affect]; + if (isVisible) { + if (!eft) eft = AttachSpecialEffect(actor->m_dwVID, EFFECT_AFFECT + affect); + } else if (eft) { + // __DetachEffect + EffectManager::Instance().DestroyEffectInstance(eft); + auto& effects = actor->m_attachedEffects; + effects.erase(std::remove_if(effects.begin(), effects.end(), + [&](const SAttachedEffect& e) { return e.instanceId == eft; }), effects.end()); + eft = 0; + } +} + SNetworkActorData* NetworkActorManager::GetActorData(uint32_t vid) { auto it = m_actors.find(vid); return (it != m_actors.end()) ? &it->second : nullptr; @@ -334,7 +811,7 @@ std::vector NetworkActorManager::BuildDrawCommands(float animTime) (void)animTime; std::vector allDraws; for (auto& [vid, actorData] : m_actors) { - if (!actorData.m_pActorInstance) continue; + if (!actorData.m_pActorInstance || actorData.m_isHidden) continue; auto actorDraws = actorData.m_pActorInstance->BuildDrawCommands(); for (auto& d : actorDraws) { allDraws.push_back(std::move(d)); @@ -343,4 +820,56 @@ std::vector NetworkActorManager::BuildDrawCommands(float animTime) return allDraws; } +void NetworkActorManager::SetSash(uint32_t vid, uint32_t sash) { + auto* actor = GetActorData(vid); + if (!actor) return; + // IsPC() && IsPoly() can never both hold: both test the same instance type. + if (actor->m_bType != TYPE_PC && actor->m_dwRace > 8) return; + + actor->m_dwSash = sash; + const uint32_t vnum = sash + 85000; + + // ClearSashEffect + if (actor->m_dwSashEffect) { + auto& effects = actor->m_attachedEffects; + for (auto it = effects.begin(); it != effects.end(); ++it) + if (it->instanceId == actor->m_dwSashEffect) { + EffectManager::Instance().DestroyEffectInstance(it->instanceId); + effects.erase(it); + break; + } + actor->m_dwSashEffect = 0; + } + if (vnum > 86000) actor->m_dwSashEffect = AttachSpecialEffect(vid, EFFECT_REFINED + EFFECT_SASH); + + // GetItemDataPointer(dwSash) fails -> no AttachSash and no item scale (the previous sash model + // and scale stay, as on Windows). + SItemModelData item; + if (!GetItemData(vnum, &item)) return; + actor->m_awPart[RaceData::PART_SASH] = sash; + // CInstanceBase::SetSash: specular 100 for the refined (+86000) sashes, 65 otherwise. + const float specular = (vnum > 86000 ? 100.0f : 65.0f) / 100.0f; + if (actor->m_pActorInstance) { + ActorInstance::SPartItem part{item.model, 0}; + actor->m_pActorInstance->AttachSash(&part, specular); + } + if (!s_getItemScale) return; + uint32_t pos = uint32_t(RaceToJob(int(actor->m_dwRace))) + 1; + if (RaceToSex(int(actor->m_dwRace)) == 0) pos += 5; + float scale[3] = {}, position[3] = {}; + // CItemManager::GetItemScale always returns true; a missing item_scale row yields zero scale. + s_getItemScale(vnum, pos, scale, position); + if (actor->m_dwMountVnum != 0) position[2] += 10.0f; // m_kHorse.IsMounting() + std::copy_n(scale, 3, actor->m_sashScale); + std::copy_n(position, 3, actor->m_sashScalePosition); + actor->m_hasSashScale = true; + if (actor->m_pActorInstance) actor->m_pActorInstance->SetSashScale(scale[0], scale[1], scale[2]); +} + +void NetworkActorManager::ChangeSash(uint32_t vid, uint32_t sash) { + const auto* actor = GetActorData(vid); + if (!actor || (actor->m_bType != TYPE_PC && actor->m_dwRace > 7)) return; + SetSash(vid, sash); +} + } // namespace ava2 diff --git a/src/eter_net/NetworkActorManager.h b/src/eter_net/NetworkActorManager.h index 707bfd9a..f923244e 100644 --- a/src/eter_net/NetworkActorManager.h +++ b/src/eter_net/NetworkActorManager.h @@ -6,14 +6,28 @@ #include #include #include +#include +#include namespace ava2 { +// CInstanceBase::IsBoss (NAMECOLOR_BOSS_CLIENT race list). +bool IsBossRace(uint32_t race); + +// CActorInstance::AttachEffectByID record: the effect follows the actor root (bone empty, +// optional z offset) or the named bone every frame until it dies or the actor is destroyed. +struct SAttachedEffect { + uint32_t instanceId = 0; + std::string bone; + float offsetHeight = 0.0f; +}; + struct SNetworkActorData { uint32_t m_dwVID = 0; std::string m_stName; uint8_t m_bType = 0; // 0=Mob, 1=NPC, 6=PC uint32_t m_dwRace = 0; + uint32_t m_dwVirtualNumber = 0; // CInstanceBase::m_dwVirtualNumber (the add-packet race; 0 for chr.CreateInstance(vid)) uint32_t m_dwLevel = 0; uint32_t m_dwGuildID = 0; std::string m_stGuildName; @@ -49,13 +63,33 @@ struct SNetworkActorData { uint32_t m_dwMountVnum = 0; uint32_t m_dwOwnerVID = 0; - bool m_duelMode = false; + uint8_t m_duelMode = DUEL_NONE; // CInstanceBase::SetDuelMode + uint8_t m_walkMode = 0; // CInstanceBase::SetRunMode/SetWalkMode (WALKMODE_RUN=0) + bool m_isFishing = false; // IsFishing(): FISHING_WAIT/FISHING_REACT motion stand-in bool m_isMoving = false; float m_moveElapsed = 0.0f; + uint32_t m_dwEmoticonTime = 0; // CInstanceBase::m_dwEmoticonTime (ELTimer_GetMSec) + // CInstanceBase::SetSash: m_dwSashEffect plus the ENABLE_OBJ_SCALLING item_scale.txt row + // (CGraphicThingInstance::SetScale(x,y,z,true) / SetScalePosition) for the sash part. + uint32_t m_dwSashEffect = 0; + bool m_hasSashScale = false; + float m_sashScale[3] = {}; + float m_sashScalePosition[3] = {}; + // CInstanceBase::m_awPart (CRaceData::EParts): the instance-side part state, separate from the + // packet copies above (SetHair/SetSash/SetWeapon may refuse a value the packet carried). + uint32_t m_awPart[7] = {}; + std::vector m_attachedEffects; + // CInstanceBase::m_adwCRCAffectEffect[AFFECT_NUM]: the effect instance __SetAffect attached. + uint32_t m_adwAffectEffect[64] = {}; + // CGraphicThingInstance::Hide/Show (chr.Hide/chr.Show); hidden instances are not drawn. + bool m_isHidden = false; std::shared_ptr m_pActorInstance; }; +// CInstanceBase::IsGameMaster: a "[" in the name or AFFECT_YMIR. +bool IsGameMaster(const SNetworkActorData& actor); + struct SNetworkMoveActorData { uint32_t m_dwVID = 0; uint32_t m_dwTime = 0; @@ -67,6 +101,16 @@ struct SNetworkMoveActorData { uint32_t m_dwDuration = 0; }; +// The CItemData fields CInstanceBase/CActorInstance read when mounting item models. +struct SItemModelData { + uint32_t vnum = 0; // the resolved item (GetItemDataPointer range lookup) + std::string model; // GetModelThing file (item_list column 4) + uint8_t type = 0; + uint8_t subType = 0; + int32_t values[6] = {}; + float specular = 0.0f; // GetSpecularPowerf (item_proto bSpecular / 100) +}; + struct SNetworkUpdateActorData { uint32_t m_dwVID = 0; uint32_t m_dwArmor = 0; @@ -110,8 +154,117 @@ public: void SyncActor(uint32_t vid, int32_t lPosX, int32_t lPosY); void SetActorOwner(uint32_t ownerVID, uint32_t victimVID); - void Update(float dt, const TerrainHeightmap* terrain = nullptr); + // CInstanceBase g_kSet_dwPVPKey / g_kSet_dwDUELKey. Windows stores a hash of the + // ordered VID pair (__GetPVPKey); the ordered pair itself is kept here. + void InsertPVPKey(uint32_t src, uint32_t dst) { m_pvpKeys.insert(PVPKey(src,dst)); } + void RemovePVPKey(uint32_t src, uint32_t dst) { m_pvpKeys.erase(PVPKey(src,dst)); } + bool FindPVPKey(uint32_t src, uint32_t dst) const { return m_pvpKeys.count(PVPKey(src,dst))!=0; } + void InsertDUELKey(uint32_t src, uint32_t dst) { m_duelKeys.insert(PVPKey(src,dst)); } + bool FindDUELKey(uint32_t src, uint32_t dst) const { return m_duelKeys.count(PVPKey(src,dst))!=0; } + void InsertGVGKey(uint32_t src,uint32_t dst) { m_gvgKeys.insert(PVPKey(src,dst)); } + void RemoveGVGKey(uint32_t src,uint32_t dst) { m_gvgKeys.erase(PVPKey(src,dst)); } + bool FindGVGKey(uint32_t src,uint32_t dst) const { return m_gvgKeys.count(PVPKey(src,dst))!=0; } + void ClearPVPKeySystem() { m_pvpKeys.clear();m_duelKeys.clear();m_gvgKeys.clear(); } + + // CInstanceBase effect table (InstanceBaseEffect.cpp). Indices follow CInstanceBase::EFFECT_* + // with the AVA2 Locale_inc.h set (SASH, VERSION_162, SHINING, ZODIAC on; COMBAT_ZONE off). + enum { + EFFECT_LEVELUP = 11, + EFFECT_SKILLUP = 12, + EFFECT_EMOTICON = 92, + EFFECT_REFINED = 229, + EFFECT_SASH = 22, // EFFECT_REFINED + EFFECT_SASH: acc_01.mse + EMOTICON_NUM = 128, + EFFECT_TEMP = 276, + EFFECT_NUM = 14328, + AFFECT_INVISIBILITY = 1, + }; + static bool RegisterEffect(unsigned type, const std::string& bone, const std::string& file, bool isCache); + static uint32_t GetEffectCRC(unsigned type); + static std::string GetEffectAttachBone(unsigned type); + uint32_t AttachSpecialEffect(uint32_t vid, unsigned type); // CInstanceBase::__AttachEffect + void CreateSpecialEffect(uint32_t vid, unsigned type); // effect at the actor transform + bool IsPossibleEmoticon(uint32_t vid) const; + void SetEmoticon(uint32_t vid, unsigned emoticon); + void SetTimeSourceForTest(uint32_t (*now)()) { m_now = now; } + + // CInstanceBase name/title colour tables (InstanceBaseEffect.cpp g_akD3DXClrName/Title, + // g_TitleNameMap). Indices follow InstanceBase.h with EMPIRE_NUM=5, OFFLINESHOP, + // NAMECOLOR_BOSS_CLIENT, CONQUEROR_LEVEL and STONEMINIMAP on, TOURNAMENT_PVP off. + enum { + NAMECOLOR_MOB = 0, NAMECOLOR_NPC = 1, NAMECOLOR_PC = 2, EMPIRE_NUM = 5, + NAMECOLOR_NORMAL_MOB = 7, NAMECOLOR_NORMAL_NPC = 8, NAMECOLOR_NORMAL_PC = 9, + NAMECOLOR_EMPIRE_MOB = 14, NAMECOLOR_EMPIRE_NPC = 15, NAMECOLOR_EMPIRE_PC = 16, + NAMECOLOR_FUNC = 21, NAMECOLOR_PK = 22, NAMECOLOR_PVP = 23, NAMECOLOR_PARTY = 24, + NAMECOLOR_WARP = 25, NAMECOLOR_WAYPOINT = 26, NAMECOLOR_SHOP = 27, NAMECOLOR_BOSS = 28, + NAMECOLOR_EXTRA = 31, NAMECOLOR_NUM = 41, + TITLE_NUM = 9, TITLE_NONE = 4, + ADD_CHARACTER_STATE_KILLER = 1 << 3, + }; + static bool RegisterNameColor(unsigned index, unsigned r, unsigned g, unsigned b); + static bool RegisterTitleColor(unsigned index, unsigned r, unsigned g, unsigned b); + static void RegisterTitleName(int index, const std::string& name); + static void SetEmpireNameMode(bool enable); + static uint32_t GetIndexedNameColor(unsigned index); + static unsigned GetAlignmentGrade(int16_t alignment); + // IAbstractPlayer::IsPartyMemberByVID lives in the Python player module. + static void SetPartyMemberQuery(bool (*query)(uint32_t vid)); + // CPythonNonPlayer::GetNPCWear (ENABLE_NPC_WEAR_ITEM, warp map name resolved by the caller) + // and CItemData::GetItemScale live in the Python-side tables as well. + static void SetNPCWearQuery(int (*query)(uint32_t race, uint8_t wearIndex)); + static void SetItemScaleQuery(bool (*query)(uint32_t vnum, uint32_t pos, float scale[3], float position[3])); + // CItemManager::GetItemDataPointer for item model mounting (weapon / armor shape / sash). + static void SetItemDataQuery(bool (*query)(uint32_t vnum, SItemModelData* out)); + // app.SetHairColorEnable / app.SetArmorSpecularEnable (HAIR_COLOR_ENABLE / USE_ARMOR_SPECULAR). + static void SetHairColorEnable(bool enable); + static void SetArmorSpecularEnable(bool enable); + void SetSash(uint32_t vid, uint32_t sash); // CInstanceBase::SetSash + void ChangeSash(uint32_t vid, uint32_t sash); // CInstanceBase::ChangeSash + unsigned GetNameColorIndex(uint32_t vid) const; + void RefreshTextTail(uint32_t vid); // CInstanceBase::RefreshTextTail + void RefreshAllPCTextTail(); // CPythonCharacterManager::RefreshAllPCTextTail + void ChangeGVG(uint32_t srcGuild, uint32_t dstGuild); // CPythonCharacterManager::ChangeGVG + + void Update(float dt, const TerrainHeightSource* terrain = nullptr); void Clear(); + // CPythonCharacterManager::Destroy: DeleteAllInstances + __Initialize (point effects too). + void Destroy(); + + // CPythonCharacterManager instance bookkeeping behind the chr module. + // RegisterInstance: CInstanceBase::New() under the VID, nothing created yet (null if the VID exists). + SNetworkActorData* RegisterInstance(uint32_t vid); + // SelectInstance keeps the previous binding when the VID is unknown (Tracef only). + void SelectInstance(uint32_t vid); + SNetworkActorData* GetSelectedInstance(); + SNetworkActorData* GetMainInstance() { return m_mainVID ? GetActorData(m_mainVID) : nullptr; } + // DeleteInstanceByFade: Windows blends the instance out on the dead list; the port removes it. + void DeleteInstanceByFade(uint32_t vid) { if (m_actors.count(vid)) RemoveActor(vid); } + // m_pkInstPick: set by the frame picking pass (not ported yet), read by chr.Pick/GetPickedVID. + void SetPickedInstanceVID(uint32_t vid) { m_pickedVID = vid; m_hasPicked = true; } + void ClearPickedInstance() { m_hasPicked = false; } + bool OLD_GetPickedInstanceVID(uint32_t* vid) const; + // CPythonCharacterManager::SCRIPT_SetAffect / CInstanceBase::__SetAffect (0xffffffff = selected). + void SCRIPT_SetAffect(uint32_t vid, unsigned affect, bool isVisible); + // CPythonCharacterManager::RegisterPointEffect / ShowPointEffect (0xffffffff = main instance). + bool RegisterPointEffect(uint32_t point, const std::string& file); + void ShowPointEffect(uint32_t point, uint32_t vid); + uint32_t GetPointEffect(uint32_t point) const { return point < 255 ? m_adwPointEffect[point] : 0; } + // CInstanceBase::ms_fDustGap / ms_fHorseDustGap (the dust effect itself is not ported). + static void SetDustGap(float gap); + static void SetHorseDustGap(float gap); + static float GetDustGap(); + static float GetHorseDustGap(); + + // CInstanceBase part setters (also driven by the chr module on the selected instance). + static void SetArmor(SNetworkActorData& actor, uint32_t armor); + static void SetShape(SNetworkActorData& actor, uint32_t shape, float specular = 0.0f); + static void SetHair(SNetworkActorData& actor, uint32_t hair); + static bool SetWeapon(SNetworkActorData& actor, uint32_t weapon, uint32_t arrow = 0); + static bool ChangeArmor(SNetworkActorData& actor, uint32_t armor); + static void ChangeWeapon(SNetworkActorData& actor, uint32_t weapon, uint32_t arrow); + static void ChangeHair(SNetworkActorData& actor, uint32_t hair); + // CInstanceBase::IsPartyMember (m_isPartyMember, answered by the SetPartyMemberQuery hook). + static bool IsPartyMember(uint32_t vid); SNetworkActorData* GetActorData(uint32_t vid); const SNetworkActorData* GetActorData(uint32_t vid) const; @@ -127,6 +280,17 @@ private: int32_t m_mainPosY = 0; std::unordered_map m_actors; + uint32_t m_selectedVID = 0; + bool m_hasSelected = false; + uint32_t m_pickedVID = 0; + bool m_hasPicked = false; + uint32_t m_adwPointEffect[255] = {}; // POINT_MAX_NUM + uint32_t (*m_now)() = nullptr; + uint32_t NowMSec() const; + uint32_t AttachEffectByID(SNetworkActorData& actor, const std::string& bone, uint32_t crc, float offsetHeight); + static void DestroyAttachedEffects(SNetworkActorData& actor); + static std::pair PVPKey(uint32_t src, uint32_t dst) { return src>dst?std::make_pair(dst,src):std::make_pair(src,dst); } + std::set> m_pvpKeys, m_duelKeys, m_gvgKeys; }; } // namespace ava2 diff --git a/src/eter_net/Packet.h b/src/eter_net/Packet.h index 63380437..ba843e0f 100644 --- a/src/eter_net/Packet.h +++ b/src/eter_net/Packet.h @@ -53,6 +53,7 @@ enum EPacketCG { HEADER_CG_HANDSHAKE = 0xff, HEADER_CG_PONG = 0xfe, HEADER_CG_TIME_SYNC = 0xfc, + HEADER_CG_XTRAP_ACK = 204, HEADER_CG_LOGIN = 1, HEADER_CG_ATTACK = 225, HEADER_CG_CHAT = 231, @@ -91,6 +92,53 @@ enum EPacketCG { HEADER_CG_GIVE_ITEM = 83, HEADER_CG_REFINE = 96, HEADER_CG_CLIENT_VERSION2 = 241, + HEADER_CG_TARGET_INFO_LOAD = 59, // ENABLE_SEND_TARGET_INFO + HEADER_CG_MESSENGER = 67, + HEADER_CG_PARTY_INVITE = 72, + HEADER_CG_PARTY_INVITE_ANSWER= 73, + HEADER_CG_PARTY_REMOVE = 74, + HEADER_CG_PARTY_SET_STATE = 75, + HEADER_CG_PARTY_USE_SKILL = 76, + HEADER_CG_PARTY_PARAMETER = 78, + HEADER_CG_GUILD = 80, + HEADER_CG_ANSWER_MAKE_GUILD = 81, + HEADER_CG_SCRIPT_SELECT_ITEM = 114, + HEADER_CG_QUEST_INPUT_LONG_STRING = 214, +}; + +// AVA2 Packet.h limits and CG subheaders used by the messenger/guild/quest senders. +constexpr size_t GUILD_GRADE_NAME_MAX_LEN = 8; +constexpr size_t GUILD_NAME_MAX_LEN = 12; +constexpr size_t QUEST_INPUT_STRING_MAX_NUM = 64; +constexpr size_t QUEST_INPUT_STRING_LONG_MAX_NUM = 512; +enum EMessengerSubheaderCG : uint8_t { + MESSENGER_SUBHEADER_CG_ADD_BY_VID = 0, + MESSENGER_SUBHEADER_CG_ADD_BY_NAME = 1, + MESSENGER_SUBHEADER_CG_REMOVE = 2, +}; +enum EMessengerSubheaderGC : uint8_t { + MESSENGER_SUBHEADER_GC_LIST, MESSENGER_SUBHEADER_GC_LOGIN, + MESSENGER_SUBHEADER_GC_LOGOUT, MESSENGER_SUBHEADER_GC_INVITE, MESSENGER_SUBHEADER_GC_MOBILE +}; +enum EMessengerConnectedState : uint8_t { + MESSENGER_CONNECTED_STATE_OFFLINE, MESSENGER_CONNECTED_STATE_ONLINE, MESSENGER_CONNECTED_STATE_MOBILE +}; +enum EGuildSubheaderCG : uint8_t { + GUILD_SUBHEADER_CG_ADD_MEMBER = 0, + GUILD_SUBHEADER_CG_REMOVE_MEMBER = 1, + GUILD_SUBHEADER_CG_CHANGE_GRADE_NAME = 2, + GUILD_SUBHEADER_CG_CHANGE_GRADE_AUTHORITY = 3, + GUILD_SUBHEADER_CG_OFFER = 4, + GUILD_SUBHEADER_CG_POST_COMMENT = 5, + GUILD_SUBHEADER_CG_DELETE_COMMENT = 6, + GUILD_SUBHEADER_CG_REFRESH_COMMENT = 7, + GUILD_SUBHEADER_CG_CHANGE_MEMBER_GRADE = 8, + GUILD_SUBHEADER_CG_USE_SKILL = 9, + GUILD_SUBHEADER_CG_CHANGE_MEMBER_GENERAL = 10, + GUILD_SUBHEADER_CG_GUILD_INVITE_ANSWER = 11, + GUILD_SUBHEADER_CG_CHARGE_GSP = 12, + GUILD_SUBHEADER_CG_DEPOSIT_MONEY = 13, + GUILD_SUBHEADER_CG_WITHDRAW_MONEY = 14, }; enum EPacketGC { @@ -151,6 +199,61 @@ enum EPacketGC { HEADER_GC_SKILL_LEVEL=72, HEADER_GC_SKILL_LEVEL_NEW=76, HEADER_GC_TIME = 106, + HEADER_GC_EVENT_MANAGER = 39, + HEADER_GC_PVP = 41, + HEADER_GC_CHARACTER_POSITION = 43, + HEADER_GC_SCRIPT = 45, + HEADER_GC_QUEST_CONFIRM = 46, + HEADER_GC_OFFLINE_SHOP_SIGN = 48, + HEADER_GC_TARGET_INFO = 58, + HEADER_GC_MOUNT = 61, + HEADER_GC_OWNERSHIP = 62, + HEADER_GC_TARGET = 63, + HEADER_GC_CHESTDROP = 66, + HEADER_GC_KILL_LOG = 68, + HEADER_GC_PARTY_INVITE = 77, + HEADER_GC_PARTY_ADD = 78, + HEADER_GC_PARTY_UPDATE = 79, + HEADER_GC_PARTY_REMOVE = 80, + HEADER_GC_REQUEST_MAKE_GUILD = 82, + HEADER_GC_PARTY_PARAMETER = 83, + HEADER_GC_FISHING = 89, + HEADER_GC_PARTY_LINK = 91, + HEADER_GC_PARTY_UNLINK = 92, + HEADER_GC_REFINE_INFORMATION = 95, + HEADER_GC_VIEW_EQUIP = 99, + HEADER_GC_DUNGEON = 110, + HEADER_GC_WALK_MODE = 111, + HEADER_GC_CHANGE_SKILL_GROUP = 112, + HEADER_GC_SEPCIAL_EFFECT = 114, + HEADER_GC_NPC_POSITION = 115, + HEADER_GC_REFINE_INFORMATION_NEW = 119, + HEADER_GC_CHANNEL = 121, + HEADER_GC_TARGET_UPDATE = 123, + HEADER_GC_TARGET_DELETE = 124, + HEADER_GC_TARGET_CREATE_NEW = 125, + HEADER_GC_LAND_LIST = 130, + HEADER_GC_LOVER_INFO = 131, + HEADER_GC_LOVE_POINT_UPDATE = 132, + HEADER_GC_DIG_MOTION = 134, + HEADER_GC_BANK = 141, + HEADER_GC_HYBRIDCRYPT_KEYS = 152, + HEADER_GC_HYBRIDCRYPT_SDB = 153, + HEADER_GC_HS_REQUEST = 204, + HEADER_GC_XTRAP_CS1_REQUEST = 205, + HEADER_GC_SPECIFIC_EFFECT = 208, + HEADER_GC_DRAGON_SOUL_REFINE = 209, + HEADER_GC_UNK_213 = 213, + HEADER_GC_CALENDAR_SYSTEM = 214, + HEADER_GC_SASH = 215, + HEADER_GC_CALENDAR_SYSTEM_ADM = 216, + HEADER_GC_KINGDOMSWAR = 218, + HEADER_GC_SUNGMA_ATTR_UPDATE = 231, + HEADER_GC_EXCHANGE_LOG = 235, + HEADER_GC_MINI_GAME_CATCH_KING = 241, + HEADER_GC_OPEN_67_ATTR = 242, + HEADER_GC_CHEAT_BLACKLIST = 249, + HEADER_GC_HANDSHAKE_OK = 0xfc, HEADER_GC_PHASE = 0xfd, HEADER_GC_HANDSHAKE = 0xff, }; @@ -200,6 +303,24 @@ enum EChatType { CHAT_TYPE_SHOUT = 6, CHAT_TYPE_WHISPER = 7, CHAT_TYPE_BIG_NOTICE = 8, + CHAT_TYPE_MONARCH_NOTICE = 9, + CHAT_TYPE_DICE_INFO = 10, // ENABLE_DICE_SYSTEM + CHAT_TYPE_EXP_INFO = 11, // __CHAT_SETTINGS__ + CHAT_TYPE_ITEM_INFO = 12, + CHAT_TYPE_MONEY_INFO = 13, + CHAT_TYPE_MISSION = 14, // dracaryS_DUNGEON_LIB + CHAT_TYPE_MAX_NUM = 15, +}; + +// PythonChat.h CPythonChat::EWhisperType +enum EWhisperType { + WHISPER_TYPE_CHAT = 0, + WHISPER_TYPE_NOT_EXIST = 1, + WHISPER_TYPE_TARGET_BLOCKED = 2, + WHISPER_TYPE_SENDER_BLOCKED = 3, + WHISPER_TYPE_ERROR = 4, + WHISPER_TYPE_GM = 5, + WHISPER_TYPE_SYSTEM = 0xFF, }; #pragma pack(push, 1) @@ -509,6 +630,8 @@ struct TPacketGCWhisper { uint16_t wSize; uint8_t bType; char szNameFrom[CHARACTER_NAME_MAX_LEN + 1]; + uint8_t bLanguage; // ENABLE_MULTILANGUAGE_SYSTEM + uint8_t bEmpire; }; struct TPacketGCDamageInfo { @@ -667,13 +790,6 @@ struct TPacketCGSafeboxCheckout { TItemPos ItemPos; }; -struct TPacketCGSafeboxItemMove { - uint8_t header; - uint8_t bSourcePos; - uint8_t bTargetPos; - uint8_t bCount; -}; - struct TPacketCGSafeboxMoney { uint8_t header; uint8_t bState; @@ -694,13 +810,439 @@ struct TPacketGCSafeboxWrongPassword { uint8_t bHeader; }; + +// ── GamePhase packets ported 2026-10-06 (AVA2 UserInterface/Packet.h, ENABLE_* as built) ── +enum EPVPModes { PVP_MODE_NONE, PVP_MODE_AGREE, PVP_MODE_FIGHT, PVP_MODE_REVENGE }; +enum EFishingSubheaderGC { FISHING_SUBHEADER_GC_START, FISHING_SUBHEADER_GC_STOP, FISHING_SUBHEADER_GC_REACT, + FISHING_SUBHEADER_GC_SUCCESS, FISHING_SUBHEADER_GC_FAIL, FISHING_SUBHEADER_GC_FISH }; +enum EDungeonSubheaderGC { DUNGEON_SUBHEADER_GC_TIME_ATTACK_START, DUNGEON_SUBHEADER_GC_DESTINATION_POSITION }; +enum EMultiRefine { MULTIREFINE_CLEAR_INFO, MULTIREFINE_ADD_INFO, MULTIREFINE_LOAD_INFO, MULTIREFINE_OPEN, + MULTIREFINE_SEND_DATES, MULTIREFINE_SEND_DATES_CLEAR }; +enum EDSSubHeader { DS_SUB_HEADER_OPEN, DS_SUB_HEADER_CLOSE, DS_SUB_HEADER_DO_UPGRADE, DS_SUB_HEADER_DO_IMPROVEMENT, + DS_SUB_HEADER_DO_REFINE, DS_SUB_HEADER_REFINE_FAIL, DS_SUB_HEADER_REFINE_FAIL_MAX_REFINE, + DS_SUB_HEADER_REFINE_FAIL_INVALID_MATERIAL, DS_SUB_HEADER_REFINE_FAIL_NOT_ENOUGH_MONEY, + DS_SUB_HEADER_REFINE_FAIL_NOT_ENOUGH_MATERIAL, DS_SUB_HEADER_REFINE_FAIL_TOO_MUCH_MATERIAL, + DS_SUB_HEADER_REFINE_SUCCEED }; +enum ESashSubheader { SASH_SUBHEADER_GC_OPEN, SASH_SUBHEADER_GC_CLOSE, SASH_SUBHEADER_GC_ADDED, + SASH_SUBHEADER_GC_REMOVED, SASH_SUBHEADER_CG_REFINED }; +enum ECalendarSubheader { CALENDAR_SUB_HEADER_OPEN, CALENDAR_SUB_HEADER_CLOSE, CALENDAR_SUB_HEADER_SEND_EVENT, + CALENDAR_RECEIVE_EVENTS, CALENDAR_RECEIVE_OPEN, CALENDAR_RECEIVE_CLEAR_EVENTS, CALENDAR_RECEIVE_LOAD_EVENTS, + CALENDAR_RECEIVE_LOADING_EVENTS, CALENDAR_RECEIVE_OPEN_ADM, CALENDAR_RECEIVE_CLEAR_EVENTS_ADM, + CALENDAR_RECEIVE_LOAD_EVENTS_ADM, CALENDAR_RECEIVE_LOADING_EVENTS_ADM }; +enum EKingdomsWarSubheaderGC { KINGDOMSWAR_SUBHEADER_GC_OPEN, KINGDOMSWAR_SUBHEADER_GC_REFRESH }; +enum EEventManagerSubheader { EVENT_MANAGER_LOAD, EVENT_MANAGER_EVENT_STATUS, EVENT_MANAGER_REMOVE_EVENT, EVENT_MANAGER_UPDATE }; +enum EExchangeLogSubheader { SUB_EXCHANGELOG_LOAD, SUB_EXCHANGELOG_LOAD_ITEM }; +enum ECatchKingSubheaderGC { SUBHEADER_GC_CATCH_KING_EVENT_INFO, SUBHEADER_GC_CATCH_KING_START, + SUBHEADER_GC_CATCH_KING_SET_CARD, SUBHEADER_GC_CATCH_KING_RESULT_FIELD, SUBHEADER_GC_CATCH_KING_SET_END_CARD, + SUBHEADER_GC_CATCH_KING_REWARD }; +enum EDuelMode : uint8_t { DUEL_NONE, DUEL_CANNOTATTACK, DUEL_START }; +constexpr size_t REFINE_MATERIAL_MAX_NUM = 5; +constexpr size_t PARTY_AFFECT_SLOT_MAX_NUM = 7; +constexpr size_t QUEST_NAME_MAX_LEN = 32; +constexpr size_t SHOP_SIGN_MAX_LEN = 45; +constexpr size_t WEAR_MAX_NUM = 32; +constexpr size_t ACCOUNT_BANK_LOG_MAX_NUM = 1000; + +struct TPacketGCChangeSpeed { uint8_t header; uint32_t vid; uint16_t moving_speed; }; +struct TPacketGCMotion { uint8_t header; uint32_t vid; uint32_t victim_vid; uint16_t motion; }; +struct TPacketGCEventManager { uint8_t header; uint32_t size; }; +struct TEventManagerData { + uint16_t eventID; uint8_t eventIndex; int32_t startTime, endTime; uint8_t empireFlag, channelFlag; + uint32_t value[4]; uint8_t eventStatus, eventTypeOnlyStart; char startRealTime[25], endRealTime[25]; +}; +struct TPacketGCDuelStart { uint8_t header; uint16_t wSize; }; +struct TPacketGCPVP { uint8_t header; uint32_t dwVIDSrc, dwVIDDst; uint8_t bMode; }; +struct TPacketGCPosition { uint8_t header; uint32_t vid; uint8_t position; }; +struct TPacketGCScript { uint8_t header; uint16_t size; uint8_t skin; uint16_t src_size; }; +constexpr uint8_t HEADER_GC_SHOPSEARCH_SET=156,HEADER_CG_SHOP_SEARCH=143; +struct TOfflineShopItemData { + uint32_t id,vnum;int64_t price;int32_t count;uint8_t display_pos; + int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM];TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM]; + uint8_t status;char szBuyerName[CHARACTER_NAME_MAX_LEN+1];uint32_t owner_id; +}; +constexpr uint8_t HEADER_GC_OFFLINE_SHOP=47,HEADER_CG_MY_OFFLINE_SHOP=58; +enum EOfflineShopGCSubheader : uint8_t { + SHOP_SUBHEADER_GC_START=0,SHOP_SUBHEADER_GC_END=1,SHOP_SUBHEADER_GC_UPDATE_ITEM=2, + SHOP_SUBHEADER_GC_OK=4,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY=5, + SHOP_SUBHEADER_GC_INVENTORY_FULL=7,SHOP_SUBHEADER_GC_INVALID_POS=8,SHOP_SUBHEADER_GC_SOLD_OUT=9, + SHOP_SUBHEADER_GC_REFRESH_MONEY=13,SHOP_SUBHEADER_GC_CHECK_RESULT=14, + SHOP_SUBHEADER_GC_REFRESH_DISPLAY_COUNT=15,SHOP_SUBHEADER_GC_REALWATCHER_COUNT=16, + SHOP_SUBHEADER_GC_REFRESH_COUNT=17,SHOP_SUBHEADER_GC_CHANGE_TITLE=18,SHOP_SUBHEADER_GC_NOT_ENOUGH_LUCKY=19 +}; +struct TShopLog { char name[25],date[25];uint32_t itemVnum,itemCount;int64_t price; }; +struct TPacketGCShop { uint8_t header;uint16_t size;uint8_t subheader; }; +struct TPacketGCOfflineShopStart { + uint32_t owner_vid;TOfflineShopItemData items[80];uint32_t m_dwDisplayedCount; + char title[46];int64_t price;uint32_t m_dwRealWatcherCount;TShopLog log[80]; + uint64_t flag;int32_t time;uint32_t type;uint8_t IsOwner; +}; +struct TPacketGCOfflineShopUpdateItem { + uint8_t pos;TOfflineShopItemData item;uint32_t m_dwDisplayedCount,m_dwRealWatcherCount; + char title[46];int64_t price;TShopLog log;uint64_t flag;int32_t time;uint32_t type; +}; +struct TOfflineShopItemTable { uint32_t vnum;int32_t count;TItemPos pos;int64_t price;uint8_t display_pos; }; +struct TPacketCGMyOfflineShop { uint8_t bHeader;char szSign[46];uint8_t bCount;uint32_t shopVnum;uint8_t shopTitle; }; +struct TShopDecoration {char sign[46];uint32_t owner_id;uint8_t vnum,type;}; +struct TPacketGCShopSearchItemSet { uint8_t header;uint32_t size; }; +struct TPacketCGShopSearch { + uint8_t header;int32_t ItemCat,SubCat;char searchInput[50]; + uint8_t avg[2],skill[2],abs[2],level[2],refine[2],sex,enchant,alchemy,character; + int64_t price[2]; +}; +constexpr uint8_t HEADER_GC_CUBE_RENEWAL=221,HEADER_CG_CUBE_RENEWAL=216; +enum ECubeRenewalSubheader : uint8_t { + CUBE_RENEWAL_SUB_HEADER_OPEN_RECEIVE,CUBE_RENEWAL_SUB_HEADER_CLEAR_DATES_RECEIVE, + CUBE_RENEWAL_SUB_HEADER_DATES_RECEIVE,CUBE_RENEWAL_SUB_HEADER_DATES_LOADING, + CUBE_RENEWAL_SUB_HEADER_MAKE_ITEM,CUBE_RENEWAL_SUB_HEADER_CLOSE +}; +constexpr uint8_t HEADER_GC_GUILD=75; +constexpr uint8_t HEADER_GC_MESSENGER=74; +struct TPacketGCMessenger { uint8_t header;uint16_t size;uint8_t subheader; }; +struct TPacketGCMessengerListOffline { uint8_t connected,length; }; +struct TPacketGCMessengerListOnline { uint8_t connected,length; }; +struct TPacketGCMessengerLogin { uint8_t length; }; +struct TPacketGCMessengerLogout { uint8_t length; }; +constexpr uint8_t HEADER_GC_QUEST_INFO=81; +struct TPacketGCQuestInfo { uint8_t header; uint16_t size,index; uint8_t flag; }; +static_assert(sizeof(TPacketGCQuestInfo)==6); +struct TPacketGCQuestConfirm { uint8_t header; char msg[64+1]; int32_t timeout; uint32_t requestPID; }; +struct TPacketGCShopSign { uint8_t bHeader; uint32_t dwVID; char szSign[SHOP_SIGN_MAX_LEN+1]; }; +struct TPacketGCTargetInfo { uint8_t header; uint32_t dwVID, race, dwVnum, count; }; +struct TPacketGCMount { uint8_t header; uint32_t vid, mount_vid; uint8_t pos; uint32_t x, y; }; +struct TPacketGCOwnership { uint8_t bHeader; uint32_t dwOwnerVID, dwVictimVID; }; +struct TPacketGCTarget { uint8_t header; uint32_t dwVID; uint8_t bHPPercent; char costume[256]; uint8_t bElement; }; +struct TPacketGCChestDrop { uint8_t header; uint32_t size; }; +struct TPacketGCKillLOG { uint8_t header; int32_t kill_log[9]; }; +struct TPacketGCFlyTargeting { uint8_t bHeader; uint32_t dwShooterVID, dwTargetVID; int32_t lX, lY; }; +struct TPacketGCPartyInvite { uint8_t header; uint32_t leader_pid; }; +struct TPacketGCPartyAdd { uint8_t header; uint32_t pid; char name[CHARACTER_NAME_MAX_LEN+1]; }; +struct TPacketGCPartyUpdate { uint8_t header; uint32_t pid; uint8_t state, percent_hp; int16_t affects[PARTY_AFFECT_SLOT_MAX_NUM]; }; +struct TPacketGCPartyRemove { uint8_t header; uint32_t pid; }; +struct TPacketGCPartyParameter { uint8_t bHeader, bDistributeMode; }; +struct TPacketGCFishing { uint8_t header, subheader; uint32_t info; uint8_t dir; }; +struct TPacketGCPartyLink { uint8_t header; uint32_t pid, vid; }; +using TPacketGCPartyUnlink=TPacketGCPartyLink; +struct TPacketGCBlank { uint8_t header; }; +struct TRefineMaterial { uint32_t vnum, count; }; +struct TRefineTable { + uint32_t src_vnum, result_vnum; uint8_t material_count; int32_t cost, prob; uint8_t special_storage; + int32_t index; uint8_t bSubType; TRefineMaterial materials[REFINE_MATERIAL_MAX_NUM]; +}; +struct TPacketGCRefineInformation { uint8_t header, pos; TRefineTable refine_table; }; +struct TPacketGCRefineInformationNew { uint8_t header, type, pos; TRefineTable refine_table; }; +struct TEquipmentItemSet { + uint32_t vnum, count; int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM]; + TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM], aRandomAttr[GLOVE_ATTR_MAX_NUM]; +}; +struct TPacketGCViewEquip { uint8_t header; uint32_t vid; TEquipmentItemSet equips[WEAR_MAX_NUM]; }; +struct TPacketGCDungeon { uint8_t bHeader; uint16_t size; uint8_t subheader; }; +struct TPacketGCWalkMode { uint8_t header; uint32_t vid; uint8_t mode; }; +struct TPacketGCChangeSkillGroup { uint8_t header, skill_group; }; +struct TPacketGCNPCPosition { uint8_t header; uint16_t size, count; }; +struct TNPCPosition { uint8_t bType; uint32_t name; int32_t x, y, regenTime; }; +struct TPacketGCChannel { uint8_t header, channel, anti_exp; }; +struct TPacketGCTargetUpdate { uint8_t bHeader; int32_t lID, lX, lY; uint8_t bType; }; +struct TPacketGCTargetDelete { uint8_t bHeader; int32_t lID; }; +struct TPacketGCTargetCreateNew { uint8_t bHeader; int32_t lID; char szTargetName[QUEST_NAME_MAX_LEN+1]; uint32_t dwVID; uint8_t byType; }; +struct TPacketGCLandList { uint8_t header; uint16_t size; }; +struct TLandPacketElement { uint32_t dwID; int32_t x, y, width, height; uint32_t dwGuildID; }; +struct TPacketGCLoverInfo { uint8_t header; char name[CHARACTER_NAME_MAX_LEN+1]; uint8_t love_point; }; +struct TPacketGCLovePointUpdate { uint8_t header, love_point; }; +struct TPacketGCDigMotion { uint8_t header; uint32_t vid, target_vid; uint8_t count; }; +struct TAccountBank { int32_t action; int64_t money; char datetime[20], ip[30], recvmoney[17]; }; +struct TPacketGCBank { uint8_t header; TAccountBank logs[ACCOUNT_BANK_LOG_MAX_NUM]; }; +struct TPacketGCHybridCryptKeys { uint8_t bHeader; uint16_t wDynamicPacketSize; int32_t iKeyStreamLen; }; +using TPacketGCHybridSDB=TPacketGCHybridCryptKeys; +struct TPacketHSCheck { uint8_t bHeader; uint8_t Req[402]; }; +struct TPacketXTrapCSVerify { uint8_t bHeader; uint8_t bPacketData[128]; }; +struct TPacketGCSpecificEffect { uint8_t header; uint32_t vid; char effect_file[128]; }; +struct TPacketGCDragonSoulRefine { uint8_t header, bSubType; TItemPos Pos; }; +struct TPacketGCUnk213 { uint8_t header, unk; }; +struct TPacketGCCalendarReceive { + uint8_t header, bSubType, bDay; char szName[100], szImage[100], szStartAt[100], szEndAt[100]; + uint32_t dwDuration, dwCurrentTimeStamp; +}; +struct TPacketGCCalendarReceiveADM { uint8_t header, bSubType; int32_t index_event; char event[100], event_descript[100]; }; +struct TPacketSash { + uint8_t header, subheader; uint8_t bWindow; uint32_t dwPrice; uint8_t bPos; TItemPos tPos; + uint32_t dwItemVnum, dwMinAbs, dwMaxAbs; +}; +struct TPacketKingdomWar { uint8_t bHeader, bSubHeader; int32_t iKills[3]; int32_t iLimitKills, iDeads, iLimitDeads; uint32_t dwTimeRemained; }; +struct TPacketGCSungmaAttrUpdate { uint8_t bHeader, bSTR, bHP, bMOVE, bINMUNE; }; +struct TPacketGCExchangeLog { uint8_t header; uint32_t size; }; +struct TExchangeLog { + char owner[CHARACTER_NAME_MAX_LEN+1]; uint32_t ownerPID; int64_t ownerGold; char ownerIP[16]; + char target[CHARACTER_NAME_MAX_LEN+1]; uint32_t targetPID; int64_t targetGold; char targetIP[16]; + char date[25]; uint8_t itemsLoaded; +}; +struct TExchangeLogItem { + uint8_t pos; uint32_t vnum; uint16_t count; int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM]; + TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM]; uint8_t isOwner; +}; +struct TPacketGCMiniGameCatchKing { uint8_t bHeader; uint16_t wSize; uint8_t bSubheader; }; +struct TSubPacketGCCatchKingResult { uint32_t dwPoints; uint8_t bRowType, bCardPos, bCardValue, bKeepFieldCard, bDestroyHandCard, bGetReward, bIsFiveNearBy; }; +struct TPacketGCCheatBlacklist { uint8_t header; char content[1024]; }; +struct TPacketGCHandshake { uint8_t bHeader; uint32_t dwHandshake, dwTime; int32_t lDelta; }; +// Pass 4 (2026-10-06): AVA2 Packet.h layouts for the remaining GamePhase handlers. +constexpr uint8_t HEADER_GC_ITEMSHOP=93; +enum {ITEMSHOP_LOAD,ITEMSHOP_LOG,ITEMSHOP_BUY,ITEMSHOP_DRAGONCOIN,ITEMSHOP_RELOAD,ITEMSHOP_LOG_ADD,ITEMSHOP_UPDATE_ITEM}; +struct TIShopData { + uint32_t id,itemVnum;int64_t itemPrice;int32_t topSellingIndex;uint8_t discount;int32_t offerTime,addedTime; + int64_t sellCount;int32_t week_limit,month_limit,maxSellCount; +}; +struct TIShopLogData { + uint32_t accountID;char playerName[25],buyDate[21];int32_t buyTime;char ipAdress[16]; + uint32_t itemID,itemVnum;int32_t itemCount;int64_t itemPrice; +}; +struct TPacketGCItemShop {uint8_t header;uint32_t size;}; +struct TPacketGCSpecialEffect { uint8_t header, type; uint32_t vid; }; +// Packet.h enum SPECIAL_EFFECT with the AVA2 Locale_inc.h set (WJ_COMBAT_ZONE off; +// SASH, VERSION_162 and ZODIAC_MISSION on). +enum ESpecialEffect : uint8_t { + SE_NONE, SE_HPUP_RED, SE_SPUP_BLUE, SE_SPEEDUP_GREEN, SE_DXUP_PURPLE, SE_CRITICAL, SE_PENETRATE, + SE_BLOCK, SE_DODGE, SE_CHINA_FIREWORK, SE_SPIN_TOP, SE_SUCCESS, SE_FAIL, SE_FR_SUCCESS, + SE_LEVELUP_ON_14_FOR_GERMANY, SE_LEVELUP_UNDER_15_FOR_GERMANY, SE_PERCENT_DAMAGE1, SE_PERCENT_DAMAGE2, + SE_PERCENT_DAMAGE3, SE_AUTO_HPUP, SE_AUTO_SPUP, SE_EQUIP_RAMADAN_RING, SE_EQUIP_HALLOWEEN_CANDY, + SE_EQUIP_HAPPINESS_RING, SE_EQUIP_LOVE_PENDANT, SE_EFFECT_SASH_SUCCEDED, SE_EFFECT_SASH_EQUIP, + SE_EFFECT_HEALER, + SE_SKILL_DAMAGE_ZONE, SE_SKILL_DAMAGE_ZONE_BUYUK, SE_SKILL_DAMAGE_ZONE_ORTA, SE_SKILL_DAMAGE_ZONE_KUCUK, + SE_SKILL_SAFE_ZONE, SE_SKILL_SAFE_ZONE_BUYUK, SE_SKILL_SAFE_ZONE_ORTA, SE_SKILL_SAFE_ZONE_KUCUK, + SE_METEOR, SE_BEAD_RAIN, SE_FALL_ROCK, SE_ARROW_RAIN, SE_HORSE_DROP, SE_EGG_DROP, SE_DEAPO_BOOM, +}; +constexpr uint8_t HEADER_GC_DUNGEON_INFO_SYSTEM=217,HEADER_CG_DUNGEON_INFO_SYSTEM=213; +enum +{ + DUNGEON_INFO_SUB_HEADER_OPEN, + DUNGEON_INFO_SUB_HEADER_TELEPORT, + DUNGEON_INFO_SUB_HEADER_MISION, + DUNGEON_INFO_SUB_HEADER_OPEN_SEND, + DUNGEON_INFO_SUB_HEADER_DATES_SEND, + DUNGEON_INFO_SUB_HEADER_DATES_CLEAR, + DUNGEON_INFO_SUB_HEADER_DATES_RANKING_CLEAR, + DUNGEON_INFO_SUB_HEADER_DATES_RANKING_SEND, + DUNGEON_INFO_SUB_HEADER_DATES_RANKING_LOAD, + DUNGEON_INFO_SUB_HEADER_RANKING, + + DUNGEON_INFO_SUB_HEADER_DATES_MISION_CLEAR, + DUNGEON_INFO_SUB_HEADER_DATES_MISION_SEND, + DUNGEON_INFO_SUB_HEADER_DATES_MISION_LOAD, + + +}; +struct TFDateInfoPacket { + int32_t id; char name[100], img[100]; int32_t lv_min, lv_max, party_max; uint32_t respawn, time_room; + int32_t time_respawn_dungeon, time_room_dungeon; char entrance[100], resistance[100], force[100]; + int32_t vnum_item, count_item, count_finish, time_finish, difficulty, damage_done, damage_received, id_boss; +}; +struct TFDateInfoRanking { int32_t vnum_mob_r, type; char name_r[24]; int32_t extra_r; }; +struct TFDateMision { int32_t vnum_mob_mision, count_mob_mision, count_mob_a_mision, status_mision; }; +struct TPacketGCDungeonInfoReceive { uint8_t header, bSubType; TFDateInfoPacket dateinfo; TFDateInfoRanking dateinfo_ranking; TFDateMision dateinfom; }; +struct TPacketCGDungeonInfo { uint8_t header, subheader; int32_t index; }; +constexpr uint8_t HEADER_GC_DROP_ITEM_SYSTEM=220,HEADER_CG_DROP_ITEM_SYSTEM=215; +enum +{ + DROP_ITEM_SUB_HEADER_OPEN, + DROP_ITEM_SUB_HEADER_SEARCH, + DROP_ITEM_SUB_HEADER_OPEN_RECEIVE, + DROP_ITEM_SUB_HEADER_DATES_RECEIVE, + DROP_ITEM_SUB_HEADER_DATES_CLEAR_RECEIVE, + DROP_ITEM_SUB_HEADER_DATES_LOADING, +}; +struct TInfoDropItemSystem { char name_mob[100]; uint32_t id_mob, prob_item; int32_t count_item; }; +struct TPacketGCDropItemReceive { uint8_t header, subheader; TInfoDropItemSystem info_drop; }; +struct TPacketCGDropItemSend { uint8_t header, subheader; int32_t vnum_item; }; +struct TInfoDateCubeRenewal { + uint32_t npc_vnum, index, vnum_reward; int32_t count_reward; uint8_t item_reward_stackable; + uint32_t vnum_material_1; int32_t count_material_1; uint32_t vnum_material_2; int32_t count_material_2; + uint32_t vnum_material_3; int32_t count_material_3; uint32_t vnum_material_4; int32_t count_material_4; + uint32_t vnum_material_5; int32_t count_material_5; int32_t gold, percent; char category[100]; +}; +struct TPacketGCCubeRenewalReceive { uint8_t header, subheader; TInfoDateCubeRenewal date_cube_renewal; }; +struct TPacketCGCubeRenewalSend { uint8_t header, subheader; uint32_t index_item, count_item; }; +constexpr uint8_t HEADER_GC_BATTLEPASS=230,HEADER_CG_BATTLEPASS=230; +enum +{ + BATTLEPASS_SUB_HEADER_OPEN, + BATTLEPASS_SUB_HEADER_CLEAR, + BATTLEPASS_SUB_HEADER_INFO, + BATTLEPASS_SUB_HEADER_INFO_EXTRA, + BATTLEPASS_SUB_HEADER_LOADING, + BATTLEPASS_SUB_HEADER_REWARD, + BATTLEPASS_SUB_HEADER_UPDATE_CLEAR, + BATTLEPASS_SUB_HEADER_UPDATE, + BATTLEPASS_SUB_HEADER_UPDATE_LOADING, + BATTLEPASS_SUB_HEADER_MP, + +}; +struct TInfoBattlePassItem { uint32_t vnum, count; }; +struct TInfoBattlePass { uint32_t type, vnum; int32_t count, count_actual; uint32_t reward_status; TInfoBattlePassItem items[4]; }; +struct TPacketGCBattlePass { uint8_t header, subheader; int32_t time; TInfoBattlePass data; }; +struct TPacketCGBattlePass { uint8_t header, subheader; int32_t index; }; +constexpr uint8_t HEADER_GC_SWITCHBOT=171,HEADER_CG_SWITCHBOT=171; +enum {SWITCHBOT_SLOT_COUNT=6,SWITCHBOT_SLOT_COUNT_REAL=5,SWITCHBOT_ALTERNATIVE_COUNT=2,MAX_NORM_ATTR_NUM=5}; +enum {SUBHEADER_CG_SWITCHBOT_START,SUBHEADER_CG_SWITCHBOT_STOP}; +enum {SUBHEADER_GC_SWITCHBOT_UPDATE,SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM,SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION}; +enum {ATTRIBUTE_SET_WEAPON,ATTRIBUTE_SET_BODY,ATTRIBUTE_SET_WRIST,ATTRIBUTE_SET_FOOTS,ATTRIBUTE_SET_NECK,ATTRIBUTE_SET_HEAD,ATTRIBUTE_SET_SHIELD,ATTRIBUTE_SET_EAR, + ATTRIBUTE_SET_COSTUME_BODY,ATTRIBUTE_SET_COSTUME_HEAD,ATTRIBUTE_SET_COSTUME_WEAPON,ATTRIBUTE_SET_NEW_RINGS,ATTRIBUTE_SET_GLOVE,ATTRIBUTE_SET_PENDANT,ATTRIBUTE_SET_MAX_NUM}; +struct TPacketGCSwitchbot { uint8_t header; int32_t size; uint8_t subheader, slot; }; +struct TPacketCGSwitchbot { uint8_t header; int32_t size; uint8_t subheader, slot; }; +struct TSwitchbotAttributeAlternativeTable { TPlayerItemAttribute attributes[5]; }; +struct TSwitchbotTable { + uint32_t player_id; uint8_t active[6], finished[6]; uint32_t items[6]; + TSwitchbotAttributeAlternativeTable alternatives[6][2]; +}; +struct TSwitchbotUpdateItem { + uint8_t slot; uint32_t vnum; uint16_t count; int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM]; + TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM]; +}; +struct TSwitchbotAttributeTable { uint8_t attribute_set; int32_t apply_num, max_value; }; #pragma pack(pop) +static_assert(sizeof(TPacketCGExchange) == 14, "TPacketCGExchange must match upstream"); static_assert(sizeof(TPacketCGRefine) == 5, "TPacketCGRefine must match upstream"); static_assert(sizeof(TPacketCGItemUseToItem) == 7, "TPacketCGItemUseToItem must match upstream"); static_assert(sizeof(TPacketCGGiveItem) == 12, "TPacketCGGiveItem must match upstream"); static_assert(sizeof(TPacketCGScriptAnswer) == 2, "TPacketCGScriptAnswer must match upstream"); +static_assert(sizeof(TPacketGCWhisper) == 31, "TPacketGCWhisper must match upstream (ENABLE_MULTILANGUAGE_SYSTEM)"); +static_assert(sizeof(TPacketGCChat) == 9, "TPacketGCChat must match upstream"); static_assert(sizeof(TPacketCGScriptButton) == 5, "TPacketCGScriptButton must match upstream"); +#define AVA2_PACKET_SIZE(type,size) static_assert(sizeof(type)==size,#type " must match upstream") +AVA2_PACKET_SIZE(TPacketGCChangeSpeed,7);AVA2_PACKET_SIZE(TPacketGCMotion,11);AVA2_PACKET_SIZE(TPacketGCEventManager,5); +AVA2_PACKET_SIZE(TEventManagerData,81);AVA2_PACKET_SIZE(TPacketGCDuelStart,3);AVA2_PACKET_SIZE(TPacketGCPVP,10); +AVA2_PACKET_SIZE(TPacketGCPosition,6);AVA2_PACKET_SIZE(TPacketGCScript,6);AVA2_PACKET_SIZE(TPacketGCQuestConfirm,74); +AVA2_PACKET_SIZE(TPacketGCShopSign,51);AVA2_PACKET_SIZE(TPacketGCTargetInfo,17);AVA2_PACKET_SIZE(TPacketGCMount,18); +AVA2_PACKET_SIZE(TPacketGCOwnership,9);AVA2_PACKET_SIZE(TPacketGCTarget,263);AVA2_PACKET_SIZE(TPacketGCChestDrop,5); +AVA2_PACKET_SIZE(TPacketGCKillLOG,37);AVA2_PACKET_SIZE(TPacketGCFlyTargeting,17);AVA2_PACKET_SIZE(TPacketGCPartyInvite,5); +AVA2_PACKET_SIZE(TPacketGCPartyAdd,30);AVA2_PACKET_SIZE(TPacketGCPartyUpdate,21);AVA2_PACKET_SIZE(TPacketGCPartyRemove,5); +AVA2_PACKET_SIZE(TPacketGCPartyParameter,2);AVA2_PACKET_SIZE(TPacketGCFishing,7);AVA2_PACKET_SIZE(TPacketGCPartyLink,9); +AVA2_PACKET_SIZE(TRefineTable,63);AVA2_PACKET_SIZE(TPacketGCRefineInformation,65);AVA2_PACKET_SIZE(TPacketGCRefineInformationNew,66); +AVA2_PACKET_SIZE(TEquipmentItemSet,106);AVA2_PACKET_SIZE(TPacketGCViewEquip,3397);AVA2_PACKET_SIZE(TPacketGCDungeon,4); +AVA2_PACKET_SIZE(TPacketGCWalkMode,6);AVA2_PACKET_SIZE(TPacketGCChangeSkillGroup,2);AVA2_PACKET_SIZE(TPacketGCNPCPosition,5); +AVA2_PACKET_SIZE(TNPCPosition,17);AVA2_PACKET_SIZE(TPacketGCChannel,3);AVA2_PACKET_SIZE(TPacketGCTargetUpdate,14); +AVA2_PACKET_SIZE(TPacketGCTargetDelete,5);AVA2_PACKET_SIZE(TPacketGCTargetCreateNew,43);AVA2_PACKET_SIZE(TPacketGCLandList,3); +AVA2_PACKET_SIZE(TLandPacketElement,24);AVA2_PACKET_SIZE(TPacketGCLoverInfo,27);AVA2_PACKET_SIZE(TPacketGCLovePointUpdate,2); +AVA2_PACKET_SIZE(TPacketGCDigMotion,10);AVA2_PACKET_SIZE(TAccountBank,79);AVA2_PACKET_SIZE(TPacketGCBank,79001); +AVA2_PACKET_SIZE(TPacketGCHybridCryptKeys,7);AVA2_PACKET_SIZE(TPacketHSCheck,403);AVA2_PACKET_SIZE(TPacketXTrapCSVerify,129); +AVA2_PACKET_SIZE(TPacketGCSpecificEffect,133);AVA2_PACKET_SIZE(TPacketGCDragonSoulRefine,5);AVA2_PACKET_SIZE(TPacketGCUnk213,2); +AVA2_PACKET_SIZE(TPacketGCCalendarReceive,411);AVA2_PACKET_SIZE(TPacketGCCalendarReceiveADM,206);AVA2_PACKET_SIZE(TPacketSash,23); +AVA2_PACKET_SIZE(TPacketKingdomWar,30);AVA2_PACKET_SIZE(TPacketGCSungmaAttrUpdate,5);AVA2_PACKET_SIZE(TPacketGCExchangeLog,5); +AVA2_PACKET_SIZE(TExchangeLog,132);AVA2_PACKET_SIZE(TExchangeLogItem,85);AVA2_PACKET_SIZE(TPacketGCMiniGameCatchKing,4); +AVA2_PACKET_SIZE(TSubPacketGCCatchKingResult,11);AVA2_PACKET_SIZE(TPacketGCCheatBlacklist,1025);AVA2_PACKET_SIZE(TPacketGCHandshake,13); +AVA2_PACKET_SIZE(TPacketGCSpecialEffect,6);AVA2_PACKET_SIZE(TFDateInfoPacket,564);AVA2_PACKET_SIZE(TFDateInfoRanking,36); +AVA2_PACKET_SIZE(TFDateMision,16);AVA2_PACKET_SIZE(TPacketGCDungeonInfoReceive,618);AVA2_PACKET_SIZE(TPacketCGDungeonInfo,6); +AVA2_PACKET_SIZE(TInfoDropItemSystem,112);AVA2_PACKET_SIZE(TPacketGCDropItemReceive,114);AVA2_PACKET_SIZE(TPacketCGDropItemSend,6); +AVA2_PACKET_SIZE(TInfoDateCubeRenewal,165);AVA2_PACKET_SIZE(TPacketGCCubeRenewalReceive,167);AVA2_PACKET_SIZE(TPacketCGCubeRenewalSend,10); +AVA2_PACKET_SIZE(TInfoBattlePass,52);AVA2_PACKET_SIZE(TPacketGCBattlePass,58);AVA2_PACKET_SIZE(TPacketCGBattlePass,6); +AVA2_PACKET_SIZE(TPacketGCSwitchbot,7);AVA2_PACKET_SIZE(TPacketCGSwitchbot,7);AVA2_PACKET_SIZE(TSwitchbotTable,220); +AVA2_PACKET_SIZE(TSwitchbotUpdateItem,84);AVA2_PACKET_SIZE(TSwitchbotAttributeTable,9); +AVA2_PACKET_SIZE(TIShopData,49);AVA2_PACKET_SIZE(TIShopLogData,90);AVA2_PACKET_SIZE(TPacketGCItemShop,5); +#undef AVA2_PACKET_SIZE + +// AVA2 Packet.h guild receive protocol (Win32 packed types). +#pragma pack(push,1) +enum +{ + GUILD_SUBHEADER_GC_LOGIN, + GUILD_SUBHEADER_GC_LOGOUT, + GUILD_SUBHEADER_GC_LIST, + GUILD_SUBHEADER_GC_GRADE, + GUILD_SUBHEADER_GC_ADD, + GUILD_SUBHEADER_GC_REMOVE, + GUILD_SUBHEADER_GC_GRADE_NAME, + GUILD_SUBHEADER_GC_GRADE_AUTH, + GUILD_SUBHEADER_GC_INFO, + GUILD_SUBHEADER_GC_COMMENTS, + GUILD_SUBHEADER_GC_CHANGE_EXP, + GUILD_SUBHEADER_GC_CHANGE_MEMBER_GRADE, + GUILD_SUBHEADER_GC_SKILL_INFO, + GUILD_SUBHEADER_GC_CHANGE_MEMBER_GENERAL, + GUILD_SUBHEADER_GC_GUILD_INVITE, + GUILD_SUBHEADER_GC_WAR, + GUILD_SUBHEADER_GC_GUILD_NAME, + GUILD_SUBHEADER_GC_GUILD_WAR_LIST, + GUILD_SUBHEADER_GC_GUILD_WAR_END_LIST, + GUILD_SUBHEADER_GC_WAR_POINT, + GUILD_SUBHEADER_GC_MONEY_CHANGE, +}; + +typedef struct packet_guild +{ + uint8_t header; + uint16_t size; + uint8_t subheader; +} TPacketGCGuild; + + +enum +{ + GUILD_AUTH_ADD_MEMBER = (1 << 0), + GUILD_AUTH_REMOVE_MEMBER = (1 << 1), + GUILD_AUTH_NOTICE = (1 << 2), + GUILD_AUTH_SKILL = (1 << 3), +}; + +typedef struct packet_guild_sub_grade +{ + char grade_name[GUILD_GRADE_NAME_MAX_LEN+1]; + uint8_t auth_flag; +} TPacketGCGuildSubGrade; + +typedef struct packet_guild_sub_member +{ + uint32_t pid; + uint8_t byGrade; + uint8_t byIsGeneral; + uint8_t byJob; + uint8_t byLevel; + uint32_t dwOffer; + uint8_t byNameFlag; + + +} TPacketGCGuildSubMember; + +typedef struct packet_guild_sub_info +{ + uint16_t member_count; + uint16_t max_member_count; + uint32_t guild_id; + uint32_t master_pid; + uint32_t exp; + uint8_t level; + char name[GUILD_NAME_MAX_LEN+1]; + uint32_t gold; + uint8_t hasLand; +} TPacketGCGuildInfo; + +enum EGuildWarState +{ + GUILD_WAR_NONE, + GUILD_WAR_SEND_DECLARE, + GUILD_WAR_REFUSE, + GUILD_WAR_RECV_DECLARE, + GUILD_WAR_WAIT_START, + GUILD_WAR_CANCEL, + GUILD_WAR_ON_WAR, + GUILD_WAR_END, + + GUILD_WAR_DURATION = 2*60*60, +}; + +typedef struct packet_guild_war +{ + uint32_t dwGuildSelf; + uint32_t dwGuildOpp; + uint8_t bType; + uint8_t bWarState; +} TPacketGCGuildWar; + +typedef struct SPacketGuildWarPoint +{ + uint32_t dwGainGuildID; + uint32_t dwOpponentGuildID; + int32_t lPoint; +} TPacketGuildWarPoint; + +#pragma pack(pop) } // namespace ava2 diff --git a/src/eter_net/PythonNetworkStream.cpp b/src/eter_net/PythonNetworkStream.cpp index 6cf37cc2..9ca3287f 100644 --- a/src/eter_net/PythonNetworkStream.cpp +++ b/src/eter_net/PythonNetworkStream.cpp @@ -1,8 +1,14 @@ +#include "item_sound.h" #include "PythonNetworkStream.h" +#include "python_net.h" +#include "guild_state.h" +#include "switchbot_state.h" #include "protocol.h" +#include "shared/common/PythonUtils.h" #include "nonplayer_data.h" #include "python_app.h" #include "python_gameplay_modules.h" +#include "python_chat.h" #include "python_native_modules.h" #include "PythonExchange.h" #include "PythonSafeBox.h" @@ -11,6 +17,7 @@ #include "eter_sound/SoundManager.h" #include "eter_effect/EffectManager.h" #include "eter_effect/FlyingManager.h" +#include #include #include #include @@ -79,14 +86,30 @@ void PythonNetworkStream::StartGame() { } void PythonNetworkStream::ResetConnection() { - m_recvBuffer.clear();ClearSendQueue();m_startGameRequested=m_refreshInventory=m_refreshStatus=m_refreshSkill=false; + m_recvBuffer.clear();m_unportedPackets.clear();m_unknownPacketQuit=false;m_isObserverMode=m_bMobileFlag=false;std::memset(m_lastPacket,0,sizeof(m_lastPacket));ClearSendQueue();m_startGameRequested=m_refreshInventory=m_refreshStatus=m_refreshSkill=m_refreshCharacter=m_refreshShopSearch=m_stopGamePhase=false; + m_refreshGuildInfo=m_refreshGuildBoard=m_refreshGuildMember=m_refreshGuildCombo=m_refreshGuildSkill=m_refreshGuildGrade=m_refreshMessenger=false; + m_guildID=0; + m_changeServerTime=m_changeClientTime=0;m_dungeonDestination={}; ResetPlayerState();NetworkActorManager::Instance().Clear(); m_pendingActorData={};m_strFieldMusicFileName.clear();m_fFieldMusicVolume=0.02f; m_phase=PHASE_OFFLINE;m_dwMainActorVID=0;m_wMainActorRace=0; m_byMainActorEmpire=m_byMainActorSkillGroup=0;m_strMainActorName.clear(); } std::vector> PythonNetworkStream::PopSendPackets() { - auto packets=std::move(m_sendPackets);m_sendPackets.clear();m_sendBuffer.clear();return packets; + auto packets=std::move(m_sendPackets);m_sendPackets.clear();m_sendSequence.clear();m_sendBuffer.clear();return packets; +} +std::vector,bool>> PythonNetworkStream::PopSendPacketsWithSequence() { + std::vector,bool>> packets; + for(size_t i=0;isecond); } void PythonNetworkStream::SetMainActorVID(uint32_t vid) { @@ -127,43 +150,123 @@ void PythonNetworkStream::Send(const void* data, size_t size) { const uint8_t* bytes = static_cast(data); m_sendBuffer.insert(m_sendBuffer.end(), bytes, bytes + size); m_sendPackets.emplace_back(bytes,bytes+size); + m_sendSequence.push_back(true); } } +void PythonNetworkStream::SendUnsequenced(const void* data, size_t size) { + const size_t count=m_sendPackets.size(); + Send(data,size); + if(m_sendPackets.size()>count) m_sendSequence.back()=false; +} + std::vector PythonNetworkStream::PopSendBytes() { std::vector result = std::move(m_sendBuffer); - m_sendBuffer.clear();m_sendPackets.clear(); + m_sendBuffer.clear();m_sendPackets.clear();m_sendSequence.clear(); return result; } -namespace { void inventory_callback(PyObject*,const char*,PyObject*); } +namespace { +void inventory_callback(PyObject*,const char*,PyObject*); + +// CMainPacketHeaderMap + GamePhase() case labels, generated from the Windows reference. +struct GcPacketType { uint8_t header; uint32_t size; bool dynamic, mapped, gameHandled; }; +constexpr GcPacketType kGcPacketTable[] = { +#include "Ava2GcPacketTable.inc" +}; +const GcPacketType* gc_packet_type(uint8_t header) { + for(const auto& type:kGcPacketTable) if(type.header==header) return &type; + return nullptr; +} +void trace_error(const std::string& text) { std::cerr<<"[AVA2 TraceError] "<mapped) { + trace_error("Unknown packet header: "+std::to_string(header)+", last: "+std::to_string(m_lastPacket[0])+" "+std::to_string(m_lastPacket[1])); + m_recvBuffer.clear(); + m_unknownPacketQuit=true; // Windows: PostQuitMessage(0) + return false; + } + size_t need=type->size; + if(type->dynamic) { + if(m_recvBuffer.size()<3) return false; + need=size_t(m_recvBuffer[1])|size_t(m_recvBuffer[2])<<8; + } + if(m_recvBuffer.size()gameHandled) { + // Windows has a GamePhase handler that is not ported yet: consume exactly + // this packet instead of stalling the stream. + size_t size=type->dynamic?(size_t(m_recvBuffer[1])|size_t(m_recvBuffer[2])<<8):type->size; + if(size==0) size=1; + m_unportedPackets.push_back(header); + m_recvBuffer.erase(m_recvBuffer.begin(),m_recvBuffer.begin()+std::min(size,m_recvBuffer.size())); + } else { + // RecvDefaultPacket + trace_error("Unprocessed packet header "+std::to_string(header)+", state Game"); + m_recvBuffer.clear(); } progress = true; + if(m_stopGamePhase) { m_stopGamePhase=false;return progress; } } - if(m_refreshSkill) {m_refreshSkill=false;inventory_callback(m_phaseWindows[5],"RefreshSkill",nullptr);} + // GamePhase() refresh block order: Character, (Equipment), Inventory, (Exchange), Skill, ..., Status. + if(m_refreshCharacter) { m_refreshCharacter=false;inventory_callback(m_phaseWindows[5],"RefreshCharacter",nullptr); } if(m_refreshInventory) { m_refreshInventory=false;inventory_callback(m_phaseWindows[5],"RefreshInventory",nullptr); } + if(m_refreshSkill) {m_refreshSkill=false;inventory_callback(m_phaseWindows[5],"RefreshSkill",nullptr);} if(m_refreshStatus) { m_refreshStatus=false;inventory_callback(m_phaseWindows[5],"RefreshStatus",nullptr); } + if(m_refreshMessenger) { m_refreshMessenger=false;inventory_callback(m_phaseWindows[5],"RefreshMessenger",nullptr); } + if(m_refreshGuildInfo) { m_refreshGuildInfo=false;inventory_callback(m_phaseWindows[5],"RefreshGuildInfoPage",nullptr); } + if(m_refreshGuildBoard) { m_refreshGuildBoard=false;inventory_callback(m_phaseWindows[5],"RefreshGuildBoardPage",nullptr); } + if(m_refreshGuildMember) { m_refreshGuildMember=false;inventory_callback(m_phaseWindows[5],"RefreshGuildMemberPage",nullptr); } + if(m_refreshGuildCombo) { m_refreshGuildCombo=false;inventory_callback(m_phaseWindows[5],"RefreshGuildMemberPageGradeComboBox",nullptr); } + if(m_refreshGuildSkill) { m_refreshGuildSkill=false;inventory_callback(m_phaseWindows[5],"RefreshGuildSkillPage",nullptr); } + if(m_refreshGuildGrade) { m_refreshGuildGrade=false;inventory_callback(m_phaseWindows[5],"RefreshGuildGradePage",nullptr); } + if(m_refreshShopSearch) { m_refreshShopSearch=false;inventory_callback(m_phaseWindows[5],"RefreshShopSearch",nullptr); } return progress; } -bool PythonNetworkStream::DispatchGamePhasePacket(uint8_t header) { +bool PythonNetworkStream::DispatchGamePhasePacket(uint8_t header,bool& ret) { + m_dispatchUnported=false; + ret=DispatchPortedGamePhasePacket(header); + return !m_dispatchUnported; +} + +bool PythonNetworkStream::DispatchPortedGamePhasePacket(uint8_t header) { switch (header) { - case 0: { uint8_t padding;return Read(1,&padding); } case 44: { uint8_t ping;if(!Read(1,&ping)) return false;const uint8_t pong=254;Send(&pong,1);return true; } case HEADER_GC_PHASE: return RecvPhasePacket(); case HEADER_GC_SHOP: return RecvShopPacket(); + case HEADER_GC_OFFLINE_SHOP: return RecvOfflineShopPacket(); case HEADER_GC_MAIN_CHARACTER: return RecvMainCharacter(); case HEADER_GC_MAIN_CHARACTER2_EMPIRE: @@ -250,8 +353,81 @@ bool PythonNetworkStream::DispatchGamePhasePacket(uint8_t header) { return RecvMallSetPacket(); case HEADER_GC_MALL_DEL: return RecvMallDelPacket(); + case HEADER_GC_CHANGE_SPEED: return RecvChangeSpeedPacket(); + case HEADER_GC_MOTION: return RecvMotionPacket(); + case HEADER_GC_ITEMSHOP: return RecvItemShop(); + case HEADER_GC_EVENT_MANAGER: return RecvEventManager(); + case HEADER_GC_DUEL_START: return RecvDuelStartPacket(); + case HEADER_GC_PVP: return RecvPVPPacket(); + case HEADER_GC_CHARACTER_POSITION: return RecvCharacterPositionPacket(); + case HEADER_GC_SCRIPT: return RecvScriptPacket(); + case HEADER_GC_SHOPSEARCH_SET: return RecvShopSearchSet(); + case HEADER_GC_CUBE_RENEWAL: return RecvCubeRenewalPacket(); + case HEADER_GC_SWITCHBOT: return RecvSwitchbotPacket(); + case HEADER_GC_DUNGEON_INFO_SYSTEM: return RecvDungeonInfoPacket(); + case HEADER_GC_DROP_ITEM_SYSTEM: return RecvDropItemPacket(); + case HEADER_GC_BATTLEPASS: return RecvBattlePassPacket(); + case HEADER_GC_GUILD: return RecvGuild(); + case HEADER_GC_MESSENGER: return RecvMessenger(); + case HEADER_GC_QUEST_INFO: return RecvQuestInfoPacket(); + case HEADER_GC_QUEST_CONFIRM: return RecvQuestConfirmPacket(); + case HEADER_GC_OFFLINE_SHOP_SIGN: return RecvOfflineShopSignPacket(); + case HEADER_GC_TARGET_INFO: return RecvTargetInfoPacket(); + case HEADER_GC_MOUNT: return RecvMountPacket(); + case HEADER_GC_OWNERSHIP: return RecvOwnerShipPacket(); + case HEADER_GC_TARGET: return RecvTargetPacket(); + case HEADER_GC_CHESTDROP: return RecvChestDrop(); + case HEADER_GC_KILL_LOG: return RecvKillLOG(); + case HEADER_GC_ADD_FLY_TARGETING: return RecvFlyTargetingPacket(true); + case HEADER_GC_FLY_TARGETING: return RecvFlyTargetingPacket(false); + case HEADER_GC_PARTY_INVITE: return RecvPartyInvite(); + case HEADER_GC_PARTY_ADD: return RecvPartyAdd(); + case HEADER_GC_PARTY_UPDATE: return RecvPartyUpdate(); + case HEADER_GC_PARTY_REMOVE: return RecvPartyRemove(); + case HEADER_GC_REQUEST_MAKE_GUILD: return RecvRequestMakeGuild(); + case HEADER_GC_PARTY_PARAMETER: return RecvPartyParameter(); + case HEADER_GC_FISHING: return RecvFishing(); + case HEADER_GC_PARTY_LINK: return RecvPartyLink(); + case HEADER_GC_PARTY_UNLINK: return RecvPartyUnlink(); + case HEADER_GC_REFINE_INFORMATION: return RecvRefineInformationPacket(); + case HEADER_GC_REFINE_INFORMATION_NEW: return RecvRefineInformationPacketNew(); + case HEADER_GC_VIEW_EQUIP: return RecvViewEquipPacket(); + case HEADER_GC_DUNGEON: return RecvDungeon(); + case HEADER_GC_WALK_MODE: return RecvWalkModePacket(); + case HEADER_GC_CHANGE_SKILL_GROUP: return RecvChangeSkillGroupPacket(); + case HEADER_GC_SEPCIAL_EFFECT: return RecvSpecialEffect(); + case HEADER_GC_NPC_POSITION: return RecvNPCList(); + case HEADER_GC_CHANNEL: return RecvChannelPacket(); + case HEADER_GC_TARGET_UPDATE: return RecvTargetUpdatePacket(); + case HEADER_GC_TARGET_DELETE: return RecvTargetDeletePacket(); + case HEADER_GC_TARGET_CREATE_NEW: return RecvTargetCreatePacketNew(); + case HEADER_GC_LAND_LIST: return RecvLandPacket(); + case HEADER_GC_LOVER_INFO: return RecvLoverInfoPacket(); + case HEADER_GC_LOVE_POINT_UPDATE: return RecvLovePointUpdatePacket(); + case HEADER_GC_DIG_MOTION: return RecvDigMotionPacket(); + case HEADER_GC_BANK: return RecvAccountBankPacket(); + case HEADER_GC_HS_REQUEST: return RecvHSCheckRequest(); + case HEADER_GC_XTRAP_CS1_REQUEST: return RecvXTrapVerifyRequest(); + case HEADER_GC_SPECIFIC_EFFECT: return RecvSpecificEffect(); + case HEADER_GC_DRAGON_SOUL_REFINE: return RecvDragonSoulRefine(); + case HEADER_GC_UNK_213: return RecvUnk213(); + case HEADER_GC_CALENDAR_SYSTEM: return RecvCalendarSystem(); + case HEADER_GC_SASH: return RecvSashPacket(); + case HEADER_GC_CALENDAR_SYSTEM_ADM: return RecvCalendarSystemADM(); + case HEADER_GC_KINGDOMSWAR: return RecvKingdomsWarPacket(); + case HEADER_GC_SUNGMA_ATTR_UPDATE: return RecvSungmaAttrUpdatePacket(); + case HEADER_GC_EXCHANGE_LOG: return RecvExchangeLog(); + case HEADER_GC_MINI_GAME_CATCH_KING: return RecvMiniGameCatchKingPacket(); + case HEADER_GC_OPEN_67_ATTR: return Recv67AttrOpenPacket(); + case HEADER_GC_CHEAT_BLACKLIST: return RecvCheatBlacklist(); + // GamePhase() `return`s after these four: the rest of the buffer and the refresh + // block wait for the next frame, and the handler result is ignored. + case HEADER_GC_HANDSHAKE: RecvHandshakePacket();m_stopGamePhase=true;return true; + case HEADER_GC_HANDSHAKE_OK: RecvHandshakeOKPacket();m_stopGamePhase=true;return true; + case HEADER_GC_HYBRIDCRYPT_KEYS: + case HEADER_GC_HYBRIDCRYPT_SDB: RecvHybridCryptPacket();m_stopGamePhase=true;return true; default: - // Unknown packet header + m_dispatchUnported=true; return false; } } @@ -407,6 +583,7 @@ bool PythonNetworkStream::RecvCharacterAppendPacketNew() { data.m_dwEmpireID=p.bEmpire; data.m_dwGuildID=p.dwGuild; data.m_sAlignment=p.sAlignment; data.m_byPKMode=p.bPKMode; data.m_dwMountVnum=p.dwMountVnum; NetworkActorManager::Instance().AppendActor(data); + if(data.m_dwVID==m_dwMainActorVID)SetGuildID(data.m_dwGuildID); return true; } @@ -437,6 +614,7 @@ bool PythonNetworkStream::RecvCharacterAdditionalInfo() { actorData.m_dwMountVnum = p.dwMountVnum; NetworkActorManager::Instance().AppendActor(actorData); + if(actorData.m_dwVID==m_dwMainActorVID)SetGuildID(actorData.m_dwGuildID); return true; } @@ -463,6 +641,7 @@ bool PythonNetworkStream::RecvCharacterUpdatePacket() { upd.m_dwAtkSpd = p.bAttackSpeed; NetworkActorManager::Instance().UpdateActor(upd); + if(upd.m_dwVID==m_dwMainActorVID)SetGuildID(upd.m_dwGuildID); return true; } @@ -492,6 +671,7 @@ bool PythonNetworkStream::RecvCharacterUpdatePacketNew() { upd.m_dwAtkSpd = p.bAttackSpeed; NetworkActorManager::Instance().UpdateActor(upd); + if(upd.m_dwVID==m_dwMainActorVID)SetGuildID(upd.m_dwGuildID); return true; } @@ -540,48 +720,104 @@ bool PythonNetworkStream::RecvSyncPositionPacket() { return true; } +// CPythonNetworkStream::RecvChatPacket (ENABLE_MULTILANGUAGE_SYSTEM branch). bool PythonNetworkStream::RecvChatPacket() { - TPacketGCChat p; - if (!Peek(sizeof(p), &p)) return false; - if(p.size 0) { - Read(textLen, text.data()); + Read(sizeof(kChat), &kChat); + std::string text(kChat.size - sizeof(kChat), '\0'); + if (!text.empty()) Read(text.size(), text.data()); + text.resize(strnlen(text.c_str(), text.size())); // buf[uChatSize]='\0' + C-string use + + if (kChat.type >= CHAT_TYPE_MAX_NUM) + return true; + + if (CHAT_TYPE_COMMAND == kChat.type) { + ServerCommand(text); + return true; } - // Strip trailing null characters - while (!text.empty() && text.back() == '\0') text.pop_back(); + if (kChat.dwVID != 0) { + auto& actors = NetworkActorManager::Instance(); + const SNetworkActorData* chatter = actors.GetActorData(kChat.dwVID); + if (!chatter) + return true; - if (m_chatCallback) { - m_chatCallback(p.type, text, p.dwVID); - } + std::string line; + switch (kChat.type) { + case CHAT_TYPE_TALKING: + case CHAT_TYPE_PARTY: + case CHAT_TYPE_GUILD: + case CHAT_TYPE_SHOUT: + case CHAT_TYPE_WHISPER: { + const size_t colon = text.find(':'); + // p = strchr(buf, ':') + 2 + const size_t start = colon == std::string::npos ? 0 : std::min(colon + 2, text.size()); + uint32_t dwEmoticon; + if (ParseEmoticon(text.c_str() + start, &dwEmoticon)) { + actors.SetEmoticon(kChat.dwVID, dwEmoticon); + return true; + } + // __ConvertEmpireText needs lang%d.cvt, which Windows only loads for the YMIR + // locale; AVA2 runs EUROPE, so the conversion is a no-op here. + // p points into buf, so the filtered text also reaches AppendChat(buf). + if (m_isEnableChatInsultFilter && chatter->m_bType != 1 && chatter->m_bType != 0) // !IsNPC && !IsEnemy + FilterInsult(text.data() + start, strlen(text.c_str() + start)); + line = text.substr(start); + break; + } + default: + line = text; + break; + } - if (p.dwVID != 0) { - TextTailManager::Instance().RegisterChatTail(p.dwVID, text); + if (CHAT_TYPE_SHOUT != kChat.type) + TextTailManager::Instance().RegisterChatTail(kChat.dwVID, line); + + if (chatter->m_bType == 6) // IsPC: CActorInstance::TYPE_PC + CPythonChat::Instance().AppendChat(kChat.type, text.c_str()); + } else { + if (CHAT_TYPE_SHOUT == kChat.type) { + const size_t colon = text.find(':'); + if (colon != std::string::npos && m_isEnableChatInsultFilter) + FilterInsult(text.data() + colon, strlen(text.c_str() + colon)); + CPythonChat::Instance().AppendChat(kChat.type, text.c_str()); + } else + PyCallClassMemberFunc(m_phaseWindows[5], "GetLocaleString", Py_BuildValue("(is)", int(kChat.type), text.c_str())); } return true; } +// CPythonNetworkStream::RecvWhisperPacket (ENABLE_MULTILANGUAGE_SYSTEM). bool PythonNetworkStream::RecvWhisperPacket() { - TPacketGCWhisper p; - if (!Peek(sizeof(p), &p)) return false; - if(p.wSize 0) { - Read(textLen, text.data()); - } - while (!text.empty() && text.back() == '\0') text.pop_back(); + Read(sizeof(whisperPacket), &whisperPacket); + std::string buf(whisperPacket.wSize - sizeof(whisperPacket), '\0'); + if (!buf.empty()) Read(buf.size(), buf.data()); + buf.resize(strnlen(buf.c_str(), buf.size())); + char name[sizeof(whisperPacket.szNameFrom) + 1] {}; + std::memcpy(name, whisperPacket.szNameFrom, sizeof(whisperPacket.szNameFrom)); - if (m_whisperCallback) { - m_whisperCallback(p.bType, p.szNameFrom, text); + if (m_whisperCallback) + m_whisperCallback(whisperPacket.bType, name, buf); + + PyObject* gameWnd = m_phaseWindows[5]; + if (WHISPER_TYPE_CHAT == whisperPacket.bType || WHISPER_TYPE_GM == whisperPacket.bType) { + char line[256]; + std::snprintf(line, sizeof(line), "%s : %s", name, buf.c_str()); + PyCallClassMemberFunc(gameWnd, "OnRecvWhisper", Py_BuildValue("(issii)", int(whisperPacket.bType), name, line, + int(whisperPacket.bLanguage), int(whisperPacket.bEmpire))); + } else if (WHISPER_TYPE_SYSTEM == whisperPacket.bType || WHISPER_TYPE_ERROR == whisperPacket.bType) { + PyCallClassMemberFunc(gameWnd, "OnRecvWhisperSystemMessage", Py_BuildValue("(iss)", int(whisperPacket.bType), name, buf.c_str())); + } else { + PyCallClassMemberFunc(gameWnd, "OnRecvWhisperError", Py_BuildValue("(iss)", int(whisperPacket.bType), name, buf.c_str())); } return true; } @@ -662,12 +898,7 @@ template TItemData item_data(const Packet& p) { return data; } void inventory_callback(PyObject* target,const char* name,PyObject* args) { - if(!target) { Py_XDECREF(args);return; } - Py_INCREF(target); - PyObject* method=PyObject_GetAttrString(target,name); - PyObject* result=method?PyObject_CallObject(method,args):nullptr; - Py_XDECREF(result);Py_XDECREF(method);Py_XDECREF(args);Py_DECREF(target); - if(!result) throw std::runtime_error(std::string("AVA2 Python callback failed: ")+name); + PyCallClassMemberFunc(target,name,args); // ScriptLib semantics: skip missing, PyErr_Print on error } } bool PythonNetworkStream::RecvItemSetPacket() { @@ -811,6 +1042,66 @@ bool main_actor_can_act(uint32_t vid) { return actor && actor->CanAct(); } } +bool PythonNetworkStream::SendPrivateShopSearchInfo(const TPacketCGShopSearch& p) { + if(!main_actor_can_act(m_dwMainActorVID))return true; + std::vector bytes{HEADER_CG_SHOP_SEARCH}; + auto put=[&](uint64_t value,unsigned width) { for(unsigned i=0;i>(8*i))); }; + put(uint32_t(p.ItemCat),4);put(uint32_t(p.SubCat),4); + bytes.insert(bytes.end(),p.searchInput,p.searchInput+50); + for(const auto* pair:{p.avg,p.skill,p.abs,p.level,p.refine})bytes.insert(bytes.end(),pair,pair+2); + bytes.insert(bytes.end(),{p.sex,p.enchant,p.alchemy,p.character}); + put(uint64_t(p.price[0]),8);put(uint64_t(p.price[1]),8); + // Unlike normal gameplay transactions, Windows does not call SendSequence here. + SendUnsequenced(bytes.data(),bytes.size());return true; +} + +bool PythonNetworkStream::SendSwitchbotPacket(bool start,uint8_t slot) { + // Original has no main-actor action gate. Preserve slot6's declared37/actual7 quirk. + std::vector bytes{HEADER_CG_SWITCHBOT,uint8_t(start?37:7),0,0,0,uint8_t(start?SUBHEADER_CG_SWITCHBOT_START:SUBHEADER_CG_SWITCHBOT_STOP),slot}; + if(start && slot<6) { + const auto& alternatives=GetSwitchbotState().table.alternatives[slot]; + for(const auto& alt:alternatives)for(const auto& a:alt.attributes) { + const uint16_t value=uint16_t(a.sValue);bytes.push_back(a.bType);bytes.push_back(uint8_t(value));bytes.push_back(uint8_t(value>>8)); + } + } + Send(bytes.data(),bytes.size());return true; +} + +bool PythonNetworkStream::SendDungeonInfoPacket(uint8_t subheader,int32_t index) { + if(!main_actor_can_act(m_dwMainActorVID))return true; + // OPEN leaves index undefined in Windows; deterministic zero padding here. + const uint32_t value=subheader==DUNGEON_INFO_SUB_HEADER_OPEN?0:uint32_t(index); + const uint8_t bytes[]={HEADER_CG_DUNGEON_INFO_SYSTEM,subheader,uint8_t(value),uint8_t(value>>8),uint8_t(value>>16),uint8_t(value>>24)}; + Send(bytes,sizeof(bytes));return true; // All four original senders use SendSequence. +} + +bool PythonNetworkStream::SendDropItemPacket(bool search,int32_t vnum) { + if(!main_actor_can_act(m_dwMainActorVID))return true; + // Original OPEN leaves vnum undefined. Zero its padding deterministically. + const uint32_t value=search?uint32_t(vnum):0; + const uint8_t bytes[]={HEADER_CG_DROP_ITEM_SYSTEM,uint8_t(search?DROP_ITEM_SUB_HEADER_SEARCH:DROP_ITEM_SUB_HEADER_OPEN), + uint8_t(value),uint8_t(value>>8),uint8_t(value>>16),uint8_t(value>>24)}; + Send(bytes,sizeof(bytes));return true; // Both original senders use SendSequence. +} + +bool PythonNetworkStream::SendBattlePassPacket(bool reward,int32_t index) { + if(!main_actor_can_act(m_dwMainActorVID))return true; + // Windows OPEN leaves index undefined; deterministic zero padding on the port. + const uint32_t value=reward?uint32_t(index):0; + const uint8_t bytes[]={HEADER_CG_BATTLEPASS,uint8_t(reward?BATTLEPASS_SUB_HEADER_REWARD:BATTLEPASS_SUB_HEADER_OPEN), + uint8_t(value),uint8_t(value>>8),uint8_t(value>>16),uint8_t(value>>24)}; + Send(bytes,sizeof(bytes));return true; // Original SendSequence() applies to both. +} + +bool PythonNetworkStream::SendCubeRenewalPacket(bool close,uint32_t index,uint32_t count) { + if(!main_actor_can_act(m_dwMainActorVID))return true; + // Close leaves index/count undefined on Windows; deterministically zero them. + std::array bytes{};bytes[0]=HEADER_CG_CUBE_RENEWAL; + bytes[1]=close?CUBE_RENEWAL_SUB_HEADER_CLOSE:CUBE_RENEWAL_SUB_HEADER_MAKE_ITEM; + if(!close)for(unsigned i=0;i<4;++i) { bytes[2+i]=uint8_t(index>>(i*8));bytes[6+i]=uint8_t(count>>(i*8)); } + Send(bytes.data(),bytes.size());return true; +} + bool PythonNetworkStream::SendQuickSlotAddPacket(uint8_t index,uint8_t type,uint8_t pos) { if(!main_actor_can_act(m_dwMainActorVID)) return true; const uint8_t bytes[]={HEADER_CG_QUICKSLOT_ADD,index,type,pos};Send(bytes,sizeof(bytes));return true; @@ -933,8 +1224,15 @@ bool PythonNetworkStream::SendAttackPacket(uint8_t type, uint32_t victimVID) { return true; } -bool PythonNetworkStream::SendChatPacket(const std::string& text,uint8_t type) { +bool PythonNetworkStream::SendChatPacket(const std::string& input,uint8_t type) { if(m_phase!=PHASE_GAME) return false; + if(input.empty() || input.size()>=512) return true; + std::string text=input; + if(text[0]=='/') { + if(text.size()==1) { if(!m_strLastCommand.empty()) text=m_strLastCommand; } + else m_strLastCommand=text; + } + // ClientCommand() always returns false in AVA2. auto bytes=wire::chat(text,type);Send(bytes.data(),bytes.size());return true; } bool PythonNetworkStream::SendWhisperPacket(const std::string& name,const std::string& text) { @@ -943,6 +1241,12 @@ bool PythonNetworkStream::SendWhisperPacket(const std::string& name,const std::s bool PythonNetworkStream::SendItemUsePacket(uint8_t window, uint16_t cell) { if(!main_actor_can_act(m_dwMainActorVID)) return true; + if(IsPlayerEquipmentItem(window,cell)) { + const char* error=CPythonExchange::Instance().isTrading()?"CANNOT_EQUIP_EXCHANGE":IsShopOpen()?"CANNOT_EQUIP_SHOP":nullptr; + if(error) {PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_AppendNotifyMessage",Py_BuildValue("(s)",error));return true;} + if(auto actor=NetworkActorManager::Instance().GetActorInstance(m_dwMainActorVID);actor&&actor->IsAttacking())return true; + } + PlayItemUseSound(GetPlayerItemData(window,cell).vnum); TPacketCGItemUse p; p.header = HEADER_CG_ITEM_USE; p.Cell.window_type = window; @@ -953,6 +1257,14 @@ bool PythonNetworkStream::SendItemUsePacket(uint8_t window, uint16_t cell) { bool PythonNetworkStream::SendItemMovePacket(uint8_t srcWindow, uint16_t srcCell, uint8_t dstWindow, uint16_t dstCell, uint32_t count) { if(!main_actor_can_act(m_dwMainActorVID)) return true; + if(IsPlayerEquipmentItem(srcWindow,srcCell)) { + const bool equipDestination=(dstWindow==1||dstWindow==2)&&dstCell>=180&&dstCell<216; + const bool equipSource=(srcWindow==1||srcWindow==2)&&srcCell>=180&&srcCell<216; + const char* error=CPythonExchange::Instance().isTrading()?"CANNOT_EQUIP_EXCHANGE":IsShopOpen()?"CANNOT_EQUIP_SHOP":nullptr; + if(error&&(equipSource||equipDestination)) {PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_AppendNotifyMessage",Py_BuildValue("(s)",error));return true;} + if(auto actor=NetworkActorManager::Instance().GetActorInstance(m_dwMainActorVID);actor&&actor->IsAttacking())return true; + } + PlayItemDropSound(GetPlayerItemData(srcWindow,srcCell).vnum); TPacketCGItemMove p; p.header = HEADER_CG_ITEM_MOVE; p.Cell.window_type = srcWindow; @@ -1092,19 +1404,31 @@ bool PythonNetworkStream::RecvExchangePacket() { return true; } -bool PythonNetworkStream::SendExchangeStartPacket(uint32_t vid) { +// AVA2 PythonNetworkStreamPhaseGame.cpp: every exchange sender is gated by __CanActMainInstance(). +// Fields a sender leaves alone keep TItemPos's ctor value {INVENTORY, WORD_MAX}; the rest is emitted as zero. +namespace { +TPacketCGExchange exchange_packet(uint8_t subheader) { TPacketCGExchange p{}; p.header = HEADER_CG_EXCHANGE; - p.subheader = EXCHANGE_SUBHEADER_CG_START; + p.subheader = subheader; + p.Pos.window_type = 1; // INVENTORY + p.Pos.cell = 0xffff; // WORD_MAX + return p; +} +bool main_actor_can_act(uint32_t vid); +} + +bool PythonNetworkStream::SendExchangeStartPacket(uint32_t vid) { + if (!main_actor_can_act(m_dwMainActorVID)) return true; + auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_START); p.arg1 = vid; Send(&p, sizeof(p)); return true; } bool PythonNetworkStream::SendExchangeItemAddPacket(uint8_t window, uint16_t cell, uint8_t exchangePos) { - TPacketCGExchange p{}; - p.header = HEADER_CG_EXCHANGE; - p.subheader = EXCHANGE_SUBHEADER_CG_ITEM_ADD; + if (!main_actor_can_act(m_dwMainActorVID)) return true; + auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_ITEM_ADD); p.Pos.window_type = window; p.Pos.cell = cell; p.arg2 = exchangePos; @@ -1112,36 +1436,29 @@ bool PythonNetworkStream::SendExchangeItemAddPacket(uint8_t window, uint16_t cel return true; } -bool PythonNetworkStream::SendExchangeItemDelPacket(uint8_t exchangePos) { - TPacketCGExchange p{}; - p.header = HEADER_CG_EXCHANGE; - p.subheader = EXCHANGE_SUBHEADER_CG_ITEM_DEL; - p.arg2 = exchangePos; - Send(&p, sizeof(p)); +bool PythonNetworkStream::SendExchangeItemDelPacket(uint8_t) { + // Windows: assert(!"Can't be called function"); return true; -- nothing is sent. return true; } bool PythonNetworkStream::SendExchangeElkAddPacket(int64_t elk) { - TPacketCGExchange p{}; - p.header = HEADER_CG_EXCHANGE; - p.subheader = EXCHANGE_SUBHEADER_CG_ELK_ADD; + if (!main_actor_can_act(m_dwMainActorVID)) return true; + auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_ELK_ADD); p.arg1 = elk; Send(&p, sizeof(p)); return true; } bool PythonNetworkStream::SendExchangeAcceptPacket() { - TPacketCGExchange p{}; - p.header = HEADER_CG_EXCHANGE; - p.subheader = EXCHANGE_SUBHEADER_CG_ACCEPT; + if (!main_actor_can_act(m_dwMainActorVID)) return true; + auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_ACCEPT); Send(&p, sizeof(p)); return true; } bool PythonNetworkStream::SendExchangeExitPacket() { - TPacketCGExchange p{}; - p.header = HEADER_CG_EXCHANGE; - p.subheader = EXCHANGE_SUBHEADER_CG_CANCEL; + if (!main_actor_can_act(m_dwMainActorVID)) return true; + auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_CANCEL); Send(&p, sizeof(p)); return true; } @@ -1206,6 +1523,7 @@ bool PythonNetworkStream::RecvMallDelPacket() { } bool PythonNetworkStream::SendSafeBoxCheckinPacket(uint8_t window, uint16_t cell, uint8_t safeboxPos) { + PlayItemDropSound(GetPlayerItemData(window,cell).vnum); TPacketCGSafeboxCheckin p{}; p.header = HEADER_CG_SAFEBOX_CHECKIN; p.bSafeBoxPos = safeboxPos; @@ -1216,6 +1534,7 @@ bool PythonNetworkStream::SendSafeBoxCheckinPacket(uint8_t window, uint16_t cell } bool PythonNetworkStream::SendSafeBoxCheckoutPacket(uint8_t safeboxPos, uint8_t window, uint16_t cell) { + uint32_t vnum;if(CPythonSafeBox::Instance().GetSlotItemID(safeboxPos,&vnum))PlayItemDropSound(vnum); TPacketCGSafeboxCheckout p{}; p.header = HEADER_CG_SAFEBOX_CHECKOUT; p.bSafeBoxPos = safeboxPos; @@ -1225,13 +1544,12 @@ bool PythonNetworkStream::SendSafeBoxCheckoutPacket(uint8_t safeboxPos, uint8_t return true; } -bool PythonNetworkStream::SendSafeBoxItemMovePacket(uint8_t srcPos, uint8_t dstPos, uint8_t count) { - TPacketCGSafeboxItemMove p{}; - p.header = HEADER_CG_SAFEBOX_ITEM_MOVE; - p.bSourcePos = srcPos; - p.bTargetPos = dstPos; - p.bCount = count; - Send(&p, sizeof(p)); +bool PythonNetworkStream::SendSafeBoxItemMovePacket(uint8_t srcPos, uint8_t dstPos, uint32_t count) { + uint32_t vnum;if(CPythonSafeBox::Instance().GetSlotItemID(srcPos,&vnum))PlayItemDropSound(vnum); + // Windows sends TPacketCGItemMove {header, pos, change_pos, DWORD num} under HEADER_CG_SAFEBOX_ITEM_MOVE. + std::vector bytes{HEADER_CG_SAFEBOX_ITEM_MOVE,1,srcPos,0,1,dstPos,0}; + for(int shift=0;shift<32;shift+=8) bytes.push_back(static_cast(count>>shift)); + Send(bytes.data(), bytes.size()); return true; } @@ -1241,6 +1559,7 @@ bool PythonNetworkStream::SendSafeBoxMoneyPacket(uint8_t, uint32_t) { } bool PythonNetworkStream::SendMallCheckoutPacket(uint8_t safeboxPos, uint8_t window, uint16_t cell) { + uint32_t vnum;if(CPythonSafeBox::Instance().GetSlotMallItemID(safeboxPos,&vnum))PlayItemDropSound(vnum); TPacketCGSafeboxCheckout p{}; p.header = HEADER_CG_MALL_CHECKOUT; p.bSafeBoxPos = safeboxPos; @@ -1254,6 +1573,156 @@ namespace { void append16(std::vector& bytes,uint16_t value) { bytes.push_back(value);bytes.push_back(value>>8); } void append32(std::vector& bytes,uint32_t value) { for(int shift=0;shift<32;shift+=8) bytes.push_back(value>>shift); } } +namespace { +// strncpy(dst,src,n) into a zeroed fixed char field; bytes Windows leaves uninitialized are emitted as zero. +void append_text(std::vector& bytes,const char* text,size_t field,size_t copy) { + const size_t start=bytes.size();bytes.resize(start+field,0); + for(size_t i=0;i(text[i]); +} +std::vector guild_packet(uint8_t subheader) { return {HEADER_CG_GUILD,subheader}; } +} + +// ── Script / quest (AVA2 PythonNetworkStreamPhaseGame.cpp) ── +bool PythonNetworkStream::SendAnswerMakeGuildPacket(const char* name) { + std::vector bytes{HEADER_CG_ANSWER_MAKE_GUILD};append_text(bytes,name,GUILD_NAME_MAX_LEN+1,GUILD_NAME_MAX_LEN); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendQuestInputStringPacket(const char* text) { + std::vector bytes{HEADER_CG_QUEST_INPUT_STRING};append_text(bytes,text,QUEST_INPUT_STRING_MAX_NUM+1,QUEST_INPUT_STRING_MAX_NUM); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendQuestInputStringLongPacket(const char* text) { + std::vector bytes{HEADER_CG_QUEST_INPUT_LONG_STRING};append_text(bytes,text,QUEST_INPUT_STRING_LONG_MAX_NUM,QUEST_INPUT_STRING_LONG_MAX_NUM); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendQuestConfirmPacket(uint8_t answer,uint32_t pid) { + std::vector bytes{HEADER_CG_QUEST_CONFIRM,answer};append32(bytes,pid); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendSelectItemPacket(uint32_t itemPos) { + std::vector bytes{HEADER_CG_SCRIPT_SELECT_ITEM};append32(bytes,itemPos); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendTargetInfoLoadPacket(uint32_t vid) { + std::vector bytes{HEADER_CG_TARGET_INFO_LOAD};append32(bytes,vid); + Send(bytes.data(),bytes.size());return true; +} + +// ── Messenger ── +bool PythonNetworkStream::SendMessengerAddByVIDPacket(uint32_t vid) { + std::vector bytes{HEADER_CG_MESSENGER,MESSENGER_SUBHEADER_CG_ADD_BY_VID};append32(bytes,vid); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendMessengerAddByNamePacket(const char* name) { + std::vector bytes{HEADER_CG_MESSENGER,MESSENGER_SUBHEADER_CG_ADD_BY_NAME};append_text(bytes,name,CHARACTER_NAME_MAX_LEN,CHARACTER_NAME_MAX_LEN-1); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendMessengerRemovePacket(const char* key,const char* name) { + std::vector bytes{HEADER_CG_MESSENGER,MESSENGER_SUBHEADER_CG_REMOVE};append_text(bytes,key,CHARACTER_NAME_MAX_LEN,CHARACTER_NAME_MAX_LEN-1); + Send(bytes.data(),bytes.size()); + // __RefreshTargetBoardByName: PyCallClassMemberFunc skips a phase window without the method. + if(auto* game=m_phaseWindows[5]; game && PyObject_HasAttrString(game,"RefreshTargetBoardByName")) + inventory_callback(game,"RefreshTargetBoardByName",Py_BuildValue("(s)",name)); + return true; +} + +// ── Party ── +bool PythonNetworkStream::SendPartyInvitePacket(uint32_t vid) { + std::vector bytes{HEADER_CG_PARTY_INVITE};append32(bytes,vid); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendPartyInviteAnswerPacket(uint32_t leaderPID,uint8_t answer) { + std::vector bytes{HEADER_CG_PARTY_INVITE_ANSWER};append32(bytes,leaderPID);bytes.push_back(answer); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendPartyRemovePacket(uint32_t pid) { + if(m_phase!=PHASE_GAME) return false; + std::vector bytes{HEADER_CG_PARTY_REMOVE};append32(bytes,pid); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendPartySetStatePacket(uint32_t vid,uint8_t state,uint8_t flag) { + std::vector bytes{HEADER_CG_PARTY_SET_STATE};append32(bytes,vid);bytes.push_back(state);bytes.push_back(flag); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendPartyUseSkillPacket(uint8_t skillIndex,uint32_t vid) { + std::vector bytes{HEADER_CG_PARTY_USE_SKILL,skillIndex};append32(bytes,vid); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendPartyParameterPacket(uint8_t distributeMode) { + const uint8_t bytes[]={HEADER_CG_PARTY_PARAMETER,distributeMode}; + Send(bytes,sizeof(bytes));return true; +} + +// ── Guild: TPacketCGGuild {header, subheader} followed by the raw payload ── +bool PythonNetworkStream::SendGuildAddMemberPacket(uint32_t vid) { + auto bytes=guild_packet(GUILD_SUBHEADER_CG_ADD_MEMBER);append32(bytes,vid); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendGuildRemoveMemberPacket(uint32_t pid) { + auto bytes=guild_packet(GUILD_SUBHEADER_CG_REMOVE_MEMBER);append32(bytes,pid); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendGuildChangeGradeNamePacket(uint8_t grade,const char* name) { + auto bytes=guild_packet(GUILD_SUBHEADER_CG_CHANGE_GRADE_NAME);bytes.push_back(grade); + append_text(bytes,name,GUILD_GRADE_NAME_MAX_LEN+1,GUILD_GRADE_NAME_MAX_LEN); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendGuildChangeGradeAuthorityPacket(uint8_t grade,uint8_t authority) { + auto bytes=guild_packet(GUILD_SUBHEADER_CG_CHANGE_GRADE_AUTHORITY);bytes.push_back(grade);bytes.push_back(authority); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendGuildOfferPacket(uint32_t experience) { + auto bytes=guild_packet(GUILD_SUBHEADER_CG_OFFER);append32(bytes,experience); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendGuildPostCommentPacket(const char* message) { + // BYTE(strlen)+1 wraps like Windows; that many bytes of the message (terminator included) follow. + const uint8_t size=static_cast(static_cast(std::strlen(message))+1); + auto bytes=guild_packet(GUILD_SUBHEADER_CG_POST_COMMENT);bytes.push_back(size); + bytes.insert(bytes.end(),message,message+size); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendGuildDeleteCommentPacket(uint32_t index) { + auto bytes=guild_packet(GUILD_SUBHEADER_CG_DELETE_COMMENT);append32(bytes,index); + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendGuildRefreshCommentsPacket(uint32_t) { + // Windows throttles with a static timeGetTime() stamp: one request per 1000 ms, extra calls return true. + const auto now=std::chrono::steady_clock::now(); + if(m_lastGuildCommentRefresh && now-*m_lastGuildCommentRefresh(index)}; Send(bytes,sizeof(bytes));return true; @@ -1279,3 +1748,23 @@ bool PythonNetworkStream::SendScriptButtonPacket(int button) { } } // namespace ava2 + +namespace ava2 { +bool PythonNetworkStream::SendBuildOfflineShopPacket(const std::string& name,const std::vector& items,uint32_t vnum,uint8_t title) { + // Serialize the original Win32 packed layout. Original unused fields are zeroed. + std::vector bytes(53,0);bytes[0]=HEADER_CG_MY_OFFLINE_SHOP; + std::copy_n(name.begin(),std::min(size_t(45),name.size()),bytes.begin()+1); + bytes[47]=static_cast(items.size()); + for(unsigned i=0;i<4;++i)bytes[48+i]=uint8_t(vnum>>(8*i));bytes[52]=title; + auto put=[&](uint64_t value,unsigned width) {for(unsigned i=0;i>(8*i)));}; + for(const auto& item:items) {put(item.vnum,4);put(uint32_t(item.count),4);put(item.pos.window_type,1);put(item.pos.cell,2);put(uint64_t(item.price),8);put(item.display_pos,1);} + Send(bytes.data(),bytes.size());return true; +} +bool PythonNetworkStream::SendOfflineShopChangeDecoration(const std::string& sign,uint32_t vnum,uint32_t type) { + std::vector bytes(110,0);bytes[0]=57;bytes[1]=12; + std::copy_n(sign.begin(),std::min(size_t(45),sign.size()),bytes.begin()+58); + // Original owner_id is never assigned; deterministic zero avoids leaking memory. + bytes[108]=uint8_t(vnum);bytes[109]=uint8_t(type); + Send(bytes.data(),bytes.size());return true; +} +} diff --git a/src/eter_net/PythonNetworkStream.h b/src/eter_net/PythonNetworkStream.h index 87f8518a..5bf522a8 100644 --- a/src/eter_net/PythonNetworkStream.h +++ b/src/eter_net/PythonNetworkStream.h @@ -3,12 +3,15 @@ #include "Packet.h" #include "NetworkActorManager.h" #include +#include #include +#include #include #include #include #include #include +#include namespace ava2 { @@ -37,6 +40,8 @@ public: bool IsGamePhase() const { return m_phase == PHASE_GAME; } void StartGame(); void ResetConnection(); + void SetGuildID(uint32_t id); + uint32_t GetGuildID() const {return m_guildID;} void SetClientFilename(std::string name) { m_clientFilename=std::move(name); } // ── Main Actor Attributes ── @@ -53,11 +58,21 @@ public: void PushRecvData(const uint8_t* data, size_t len); void PushRecvData(const std::vector& bytes); bool ProcessRecvData(); + // Free bytes in the 128 KB game receive buffer (networkmodule.py SetTCPRecvBufferSize(128*1024)). + size_t RecvBufferSpace() const { return m_recvBuffer.size()>=128*1024?0:128*1024-m_recvBuffer.size(); } // ── Client-to-Server Sending API ── bool SendEnterGamePacket(); + bool SendPrivateShopSearchInfo(const TPacketCGShopSearch& data); + bool SendSwitchbotPacket(bool start,uint8_t slot); + bool SendDungeonInfoPacket(uint8_t subheader,int32_t index=0); + bool SendDropItemPacket(bool search,int32_t vnum=0); + bool SendBattlePassPacket(bool reward,int32_t index=0); + bool SendCubeRenewalPacket(bool close,uint32_t index=0,uint32_t count=0); bool SendShopPacket(uint8_t operation,uint8_t window=0,uint8_t slot=0,uint32_t count=0); bool SendOfflineShopPacket(bool buy,uint32_t owner=0,uint8_t position=0); + bool SendBuildOfflineShopPacket(const std::string& name,const std::vector& items,uint32_t vnum,uint8_t title); + bool SendOfflineShopChangeDecoration(const std::string& sign,uint32_t vnum,uint32_t type); bool SendOfflineShopManagement(uint8_t operation,uint8_t position=0,uint32_t owner=0); bool SendQuickSlotAddPacket(uint8_t index,uint8_t type,uint8_t pos); bool SendQuickSlotDelPacket(uint8_t index); @@ -86,7 +101,7 @@ public: // ── SafeBox & Mall Protocol ── bool SendSafeBoxCheckinPacket(uint8_t window, uint16_t cell, uint8_t safeboxPos); bool SendSafeBoxCheckoutPacket(uint8_t safeboxPos, uint8_t window, uint16_t cell); - bool SendSafeBoxItemMovePacket(uint8_t srcPos, uint8_t dstPos, uint8_t count); + bool SendSafeBoxItemMovePacket(uint8_t srcPos, uint8_t dstPos, uint32_t count); bool SendSafeBoxMoneyPacket(uint8_t state, uint32_t money); bool SendMallCheckoutPacket(uint8_t safeboxPos, uint8_t window, uint16_t cell); @@ -96,20 +111,77 @@ public: bool SendGiveItemPacket(uint32_t targetVID, uint8_t window, uint16_t cell, uint32_t count); bool SendScriptAnswerPacket(int answer); bool SendScriptButtonPacket(int button); + // CPythonNetworkStream::OnScriptEventStart: phase window OpenQuestWindow(skin, index). + void OnScriptEventStart(int iSkin, int iIndex); + bool SendAnswerMakeGuildPacket(const char* name); + bool SendQuestInputStringPacket(const char* text); + bool SendQuestInputStringLongPacket(const char* text); + bool SendQuestConfirmPacket(uint8_t answer, uint32_t pid); + bool SendSelectItemPacket(uint32_t itemPos); + bool SendTargetInfoLoadPacket(uint32_t vid); + + // ── Messenger / Party / Guild Protocol (AVA2 PythonNetworkStreamPhaseGame.cpp) ── + bool SendMessengerAddByVIDPacket(uint32_t vid); + bool SendMessengerAddByNamePacket(const char* name); + bool SendMessengerRemovePacket(const char* key, const char* name); + bool SendPartyInvitePacket(uint32_t vid); + bool SendPartyInviteAnswerPacket(uint32_t leaderPID, uint8_t answer); + bool SendPartyRemovePacket(uint32_t pid); + bool SendPartySetStatePacket(uint32_t vid, uint8_t state, uint8_t flag); + bool SendPartyUseSkillPacket(uint8_t skillIndex, uint32_t vid); + bool SendPartyParameterPacket(uint8_t distributeMode); + bool SendGuildAddMemberPacket(uint32_t vid); + bool SendGuildRemoveMemberPacket(uint32_t pid); + bool SendGuildChangeGradeNamePacket(uint8_t grade, const char* name); + bool SendGuildChangeGradeAuthorityPacket(uint8_t grade, uint8_t authority); + bool SendGuildOfferPacket(uint32_t experience); + bool SendGuildPostCommentPacket(const char* message); + bool SendGuildDeleteCommentPacket(uint32_t index); + bool SendGuildRefreshCommentsPacket(uint32_t highestIndex); + bool SendGuildChangeMemberGradePacket(uint32_t pid, uint8_t grade); + bool SendGuildUseSkillPacket(uint32_t skillID, uint32_t targetVID); + bool SendGuildChangeMemberGeneralPacket(uint32_t pid, uint8_t flag); + bool SendGuildInviteAnswerPacket(uint32_t guildID, uint8_t answer); + bool SendGuildChargeGSPPacket(uint32_t money); + bool SendGuildDepositMoneyPacket(uint32_t money); + bool SendGuildWithdrawMoneyPacket(uint32_t money); + void ResetGuildCommentRefreshThrottle() { m_lastGuildCommentRefresh.reset(); } // Raw outgoing bytes for network transport / unit test inspection const std::vector& GetSendQueue() const { return m_sendBuffer; } std::vector PopSendBytes(); void ClearSendQueue() { m_sendBuffer.clear();m_sendPackets.clear(); } std::vector> PopSendPackets(); + // Packets with whether the transport appends the sequence byte (SendSequence()). + std::vector,bool>> PopSendPacketsWithSequence(); + std::pair GetDungeonDestination() const { return m_dungeonDestination; } // Callback when damage occurs using DamageCallback = std::function; void SetDamageCallback(DamageCallback cb) { m_damageCallback = cb; } // Callback when chat is received - using ChatCallback = std::function; - void SetChatCallback(ChatCallback cb) { m_chatCallback = cb; } + + // ── Chat / ServerCommand (AVA2 PythonNetworkStreamPhaseGame.cpp, PythonNetworkStreamCommand.cpp) ── + void ServerCommand(const std::string& command); + void SetServerCommandParserWindow(PyObject* window) { m_poSerCommandParserWnd = window; } + void RegisterEmoticonString(const std::string& emoticon); + bool ParseEmoticon(const char* chatMsg, uint32_t* emoticon) const; + void SendEmoticon(unsigned emoticon); + void EnableChatInsultFilter(bool enable) { m_isEnableChatInsultFilter = enable; } + // CInsultChecker (AVA2 UserInterface/InsultChecker.cpp); text = already-read insult.txt. + bool LoadInsultList(const std::string& text); + bool IsChatInsultIn(const char* msg) const; + bool IsInsultIn(const char* msg) const; + void FilterInsult(char* line, size_t lineLen) const; + void SetEmpireLanguageMode(bool enable) { m_bEmpireLanguageEnable = enable; } + bool IsObserverMode() const { return m_isObserverMode; } + bool HasMobilePhoneNumber() const { return m_bMobileFlag; } + bool GetComboSkillFlag() const { return m_bComboSkillFlag; } + // Windows calls PostQuitMessage(0); the host loop polls this instead. + bool IsQuitRequested() const { return m_unknownPacketQuit; } + // GamePhase() headers Windows handles but this port skips (consumed, not dispatched). + const std::vector& GetUnportedPackets() const { return m_unportedPackets; } // Callback when whisper is received using WhisperCallback = std::function; @@ -124,7 +196,9 @@ public: void SetFlyCallback(FlyCallback cb) { m_flyCallback = cb; } private: - bool DispatchGamePhasePacket(uint8_t header); + bool CheckPacket(uint8_t* retHeader); + bool DispatchGamePhasePacket(uint8_t header,bool& ret); + bool DispatchPortedGamePhasePacket(uint8_t header); // Handlers matching CPythonNetworkStreamPhaseGame bool RecvPhasePacket(); @@ -157,7 +231,15 @@ private: bool m_startGameRequested=false; std::string m_clientFilename="ava2_client"; std::vector> m_sendPackets; - bool m_refreshInventory=false,m_refreshStatus=false; + bool m_refreshGuildInfo=false,m_refreshGuildBoard=false,m_refreshGuildMember=false; + bool m_refreshGuildCombo=false,m_refreshGuildSkill=false,m_refreshGuildGrade=false,m_refreshMessenger=false; + bool m_refreshShopSearch=false; + bool m_refreshInventory=false,m_refreshStatus=false,m_refreshCharacter=false; + std::vector m_sendSequence; + // Handshake/HandshakeOK/HybridCrypt return from GamePhase() before the refresh block. + bool m_stopGamePhase=false; + uint32_t m_changeServerTime=0,m_changeClientTime=0; // CPythonNetworkStream::m_kServerTimeSync + std::pair m_dungeonDestination{}; bool RecvItemSetPacket(); bool RecvItemSetPacket2(); bool RecvItemUpdatePacket(); @@ -172,6 +254,7 @@ private: bool RecvWarpPacket(); bool RecvExchangePacket(); bool RecvShopPacket(); + bool RecvOfflineShopPacket(); bool RecvSafeBoxSetPacket(); bool RecvSafeBoxDelPacket(); bool RecvSafeBoxWrongPasswordPacket(); @@ -181,31 +264,123 @@ private: bool RecvMallSetPacket(); bool RecvMallDelPacket(); + // Remaining GamePhase() handlers (PythonNetworkStreamPhaseGameRecv.cpp) + SNetworkActorData* MainInstance(); + void RefreshTargetBoardByVID(uint32_t vid); + bool RecvChangeSpeedPacket(); + bool RecvMotionPacket(); + bool RecvEventManager(); + bool RecvItemShop(); + bool RecvDuelStartPacket(); + bool RecvPVPPacket(); + bool RecvCharacterPositionPacket(); + bool RecvScriptPacket(); + bool RecvShopSearchSet(); + bool RecvCubeRenewalPacket(); + bool RecvMessenger(); + bool RecvGuild(); + bool RecvBattlePassPacket(); + bool RecvDropItemPacket(); + bool RecvDungeonInfoPacket(); + bool RecvSwitchbotPacket(); + bool RecvQuestInfoPacket(); + bool RecvQuestConfirmPacket(); + bool RecvOfflineShopSignPacket(); + bool RecvTargetInfoPacket(); + bool RecvMountPacket(); + bool RecvOwnerShipPacket(); + bool RecvTargetPacket(); + bool RecvChestDrop(); + bool RecvKillLOG(); + bool RecvFlyTargetingPacket(bool add); + bool RecvPartyInvite(); + bool RecvPartyAdd(); + bool RecvPartyUpdate(); + bool RecvPartyRemove(); + bool RecvRequestMakeGuild(); + bool RecvPartyParameter(); + bool RecvFishing(); + bool RecvPartyLink(); + bool RecvPartyUnlink(); + template void RefineInformation(const Packet& p,bool isNew); + static uint8_t RefineType(const TPacketGCRefineInformation&); + static uint8_t RefineType(const TPacketGCRefineInformationNew& p); + bool RecvRefineInformationPacket(); + bool RecvRefineInformationPacketNew(); + bool RecvViewEquipPacket(); + bool RecvDungeon(); + bool RecvWalkModePacket(); + bool RecvChangeSkillGroupPacket(); + bool RecvNPCList(); + bool RecvChannelPacket(); + bool RecvTargetUpdatePacket(); + bool RecvTargetDeletePacket(); + bool RecvTargetCreatePacketNew(); + bool RecvLandPacket(); + bool RecvLoverInfoPacket(); + bool RecvLovePointUpdatePacket(); + bool RecvDigMotionPacket(); + bool RecvAccountBankPacket(); + bool RecvHybridCryptPacket(); + bool RecvHSCheckRequest(); + bool RecvXTrapVerifyRequest(); + bool RecvSpecificEffect(); + bool RecvSpecialEffect(); + bool RecvDragonSoulRefine(); + bool RecvUnk213(); + bool RecvCalendarSystem(); + bool RecvCalendarSystemADM(); + bool RecvSashPacket(); + bool RecvKingdomsWarPacket(); + bool RecvSungmaAttrUpdatePacket(); + bool RecvExchangeLog(); + bool RecvMiniGameCatchKingPacket(); + bool Recv67AttrOpenPacket(); + bool RecvCheatBlacklist(); + bool RecvHandshakePacket(); + bool RecvHandshakeOKPacket(); + bool Peek(size_t size, void* outBuf); bool Read(size_t size, void* outBuf); void Send(const void* data, size_t size); + // Windows Send() without SendSequence() (XTrap ACK). + void SendUnsequenced(const void* data, size_t size); private: EPhase m_phase = PHASE_OFFLINE; PyObject* m_poHandler = nullptr; PyObject* m_phaseWindows[7] = {nullptr}; + uint32_t m_guildID=0; uint32_t m_dwMainActorVID = 0; uint16_t m_wMainActorRace = 0; uint8_t m_byMainActorEmpire = 0; + std::optional m_lastGuildCommentRefresh; uint8_t m_byMainActorSkillGroup = 0; std::string m_strMainActorName; std::string m_strFieldMusicFileName; float m_fFieldMusicVolume = 0.02f; std::vector m_recvBuffer; + uint8_t m_lastPacket[2] {}; + bool m_dispatchUnported = false; + bool m_unknownPacketQuit = false; + std::vector m_unportedPackets; + PyObject* m_poSerCommandParserWnd = nullptr; + std::vector m_emoticonStrings; + std::string m_strLastCommand; + bool m_isEnableChatInsultFilter = false; + std::vector m_insults; // CInsultChecker::m_kList_stInsult + bool m_bEmpireLanguageEnable = true; // gs_bEmpireLanuageEnable + bool m_isObserverMode = false; + bool m_bMobileFlag = false; + bool m_bComboSkillFlag = false; std::vector m_sendBuffer; // Temporary pending actor data when CharacterAdd arrives before CharacterAdditionalInfo SNetworkActorData m_pendingActorData; DamageCallback m_damageCallback; - ChatCallback m_chatCallback; WhisperCallback m_whisperCallback; GroundItemCallback m_groundItemCallback; FlyCallback m_flyCallback; diff --git a/src/eter_net/PythonNetworkStreamCommand.cpp b/src/eter_net/PythonNetworkStreamCommand.cpp new file mode 100644 index 00000000..2febafdc --- /dev/null +++ b/src/eter_net/PythonNetworkStreamCommand.cpp @@ -0,0 +1,287 @@ +// Port of AVA2 UserInterface/PythonNetworkStreamCommand.cpp (ServerCommand / SplitToken) +// and the emoticon helpers from PythonNetworkStreamPhaseGame.cpp / PythonNetworkStream.cpp. +// Commands that only forward to the game window are 1:1; commands that need actor/effect +// state the port does not have yet (emotions, StoneDetect, stamina) are TraceError'd and +// listed in docs/WINDOWS-PARITY.md. +#include "PythonNetworkStream.h" +#include "ava2_text_file.h" +#include "shared/common/PythonUtils.h" +#include +#include +#include +#include + +namespace ava2 { +namespace { + +using CTokenVector = std::vector; + +bool SplitToken(const char* c_szLine, CTokenVector* pstTokenVector, const char* c_szDelimeter = " ") { + pstTokenVector->reserve(10); + pstTokenVector->clear(); + + std::string strLine = c_szLine; + size_t basePos = 0; + do { + size_t beginPos = strLine.find_first_not_of(c_szDelimeter, basePos); + if (beginPos == std::string::npos) + return false; + + size_t endPos; + if (strLine[beginPos] == '"') { + ++beginPos; + endPos = strLine.find_first_of("\"", beginPos); + if (endPos == std::string::npos) + return false; + basePos = endPos + 1; + } else { + endPos = strLine.find_first_of(c_szDelimeter, beginPos); + basePos = endPos; + } + + pstTokenVector->push_back(strLine.substr(beginPos, endPos == std::string::npos ? std::string::npos : endPos - beginPos)); + + if (strLine.find_first_not_of(c_szDelimeter, basePos) == std::string::npos) + break; + } while (basePos < strLine.length()); + + return true; +} + +void TraceError(const std::string& text) { std::cerr << "[AVA2 TraceError] " << text << std::endl; } + +} // namespace + +void PythonNetworkStream::ServerCommand(const std::string& command) { + const char* c_szCommand = command.c_str(); + // #0000811: [M2EU] + if (strcasecmp(c_szCommand, "ConsoleEnable") == 0) + return; + + PyObject* gameWnd = m_phaseWindows[5]; // PHASE_WINDOW_GAME + if (gameWnd) { + bool isTrue; + if (PyCallClassMemberFunc(gameWnd, "BINARY_ServerCommand_Run", Py_BuildValue("(s)", c_szCommand), &isTrue) && isTrue) + return; + } else if (m_poSerCommandParserWnd) { + bool isTrue; + if (PyCallClassMemberFunc(m_poSerCommandParserWnd, "BINARY_ServerCommand_Run", Py_BuildValue("(s)", c_szCommand), &isTrue) && isTrue) + return; + } + + CTokenVector TokenVector; + if (!SplitToken(c_szCommand, &TokenVector)) + return; + if (TokenVector.empty()) + return; + + // Windows indexes TokenVector without a bound check for several commands; a + // missing token reads as "" (atoi -> 0) here instead of undefined behaviour. + auto arg = [&](size_t i) { return i < TokenVector.size() ? TokenVector[i].c_str() : ""; }; + auto strangeCount = [&] { TraceError("CPythonNetworkStream::ServerCommand(c_szCommand=" + command + ") - Strange Parameter Count"); }; + auto call = [&](const char* func, PyObject* args) { PyCallClassMemberFunc(gameWnd, func, args); }; + const char* szCmd = TokenVector[0].c_str(); + + if (!strcasecmp(szCmd, "quit")) { + m_unknownPacketQuit = true; // PostQuitMessage(0) + } else if (!strcasecmp(szCmd, "BettingMoney")) { + if (2 != TokenVector.size()) { strangeCount(); return; } + } else if (!strcasecmp(szCmd, "gift")) { + call("Gift_Show", Py_BuildValue("()")); + } else if (!strcasecmp(szCmd, "cube")) { + if (TokenVector.size() < 2) { strangeCount(); return; } + const std::string& sub = TokenVector[1]; + if ("open" == sub) { + if (3 > TokenVector.size()) { strangeCount(); return; } + call("BINARY_Cube_Open", Py_BuildValue("(i)", atoi(arg(2)))); + } else if ("close" == sub) { + call("BINARY_Cube_Close", Py_BuildValue("()")); + } else if ("info" == sub) { + if (5 != TokenVector.size()) { strangeCount(); return; } + call("BINARY_Cube_UpdateInfo", Py_BuildValue("(iii)", atoi(arg(2)), atoi(arg(3)), atoi(arg(4)))); + } else if ("success" == sub) { + if (4 != TokenVector.size()) { strangeCount(); return; } + call("BINARY_Cube_Succeed", Py_BuildValue("(ii)", atoi(arg(2)), atoi(arg(3)))); + } else if ("fail" == sub) { + call("BINARY_Cube_Failed", Py_BuildValue("()")); + } else if ("r_list" == sub) { + if (5 != TokenVector.size()) { strangeCount(); return; } + call("BINARY_Cube_ResultList", Py_BuildValue("(is)", atoi(arg(2)), arg(4))); + } else if ("m_info" == sub) { + if (5 != TokenVector.size()) { strangeCount(); return; } + call("BINARY_Cube_MaterialInfo", Py_BuildValue("(iis)", atoi(arg(2)), atoi(arg(3)), arg(4))); + } + } else if (!strcasecmp(szCmd, "ObserverCount")) { + if (2 != TokenVector.size()) { strangeCount(); return; } + call("BINARY_BettingGuildWar_UpdateObserverCount", Py_BuildValue("(i)", atoi(arg(1)))); + } else if (!strcasecmp(szCmd, "ObserverMode")) { + if (2 != TokenVector.size()) { strangeCount(); return; } + const int uMode = atoi(arg(1)); + m_isObserverMode = uMode != 0; // IAbstractPlayer::SetObserverMode + call("BINARY_BettingGuildWar_SetObserverMode", Py_BuildValue("(i)", uMode)); + } else if (!strcasecmp(szCmd, "OfflineShopSetFlag")) { + // ENABLE_OFFLINESHOP_SYSTEM: CPythonShop::SetShopFlag is not ported; the window refresh is. + call("RefreshOfflineShop", Py_BuildValue("()")); + } else if (!strcasecmp(szCmd, "ObserverTeamInfo")) { + } else if (!strcasecmp(szCmd, "cards")) { + if (TokenVector.size() < 2) { strangeCount(); return; } + const std::string& sub = TokenVector[1]; + if ("open" == sub) { + call("BINARY_Cards_Open", Py_BuildValue("(i)", atoi(arg(2)))); + } else if ("info" == sub) { + if (14 != TokenVector.size()) { strangeCount(); return; } + call("BINARY_Cards_UpdateInfo", Py_BuildValue("(iiiiiiiiiiii)", atoi(arg(2)), atoi(arg(3)), atoi(arg(4)), atoi(arg(5)), + atoi(arg(6)), atoi(arg(7)), atoi(arg(8)), atoi(arg(9)), atoi(arg(10)), atoi(arg(11)), atoi(arg(12)), atoi(arg(13)))); + } else if ("finfo" == sub || "reward" == sub) { + if (9 != TokenVector.size()) { strangeCount(); return; } + call("finfo" == sub ? "BINARY_Cards_FieldUpdateInfo" : "BINARY_Cards_PutReward", + Py_BuildValue("(iiiiiii)", atoi(arg(2)), atoi(arg(3)), atoi(arg(4)), atoi(arg(5)), atoi(arg(6)), atoi(arg(7)), atoi(arg(8)))); + } else if ("icon" == sub) { + if (2 != TokenVector.size()) { strangeCount(); return; } + call("BINARY_Cards_ShowIcon", Py_BuildValue("()")); + } + } + // ENABLE_ZODIAC_MISSION + else if (!strcasecmp(szCmd, "ZodiacDayorNight")) { + call("ZodiacDayorNight", Py_BuildValue("()")); + } else if (!strcasecmp(szCmd, "ZodiacJumpButtonClose")) { + call("ZodiacJumpButtonClose", Py_BuildValue("()")); + } else if (!strcasecmp(szCmd, "ZodiacJumpButtonShow")) { + call("ZodiacJumpButtonShow", Py_BuildValue("()")); + } else if (!strcasecmp(szCmd, "ZodiacInfo")) { + // BYTE time/floor/nextfloor + call("Refresh12ziTimer", Py_BuildValue("(iii)", uint8_t(atoi(arg(1))), uint8_t(atoi(arg(2))), uint8_t(atoi(arg(3))))); + } else if (!strcasecmp(szCmd, "OpenUI12zi")) { + call("OpenUI12zi", Py_BuildValue("(iiii)", atoi(arg(1)), atoi(arg(2)), atoi(arg(3)), atoi(arg(4)))); + } else if (!strcasecmp(szCmd, "OpenReviveDialog")) { + call("OpenReviveDialog", Py_BuildValue("(i)", atoi(arg(1)))); + } else if (!strcasecmp(szCmd, "OpenReviveDialog_me")) { + call("OpenReviveDialog_me", Py_BuildValue("(i)", atoi(arg(1)))); + } else if (!strcasecmp(szCmd, "SetBeadCount")) { + call("SetBeadCount", Py_BuildValue("(i)", atoi(arg(1)))); + } else if (!strcasecmp(szCmd, "NextBeadUpdateTime")) { + call("NextBeadUpdateTime", Py_BuildValue("(i)", atoi(arg(1)))); + } else if (!strcasecmp(szCmd, "GetMissionInformation")) { + call("GetMissionInformation", Py_BuildValue("(ii)", atoi(arg(1)), atoi(arg(2)))); + } else if (!strcasecmp(szCmd, "StoneDetect")) { + if (4 != TokenVector.size()) { strangeCount(); return; } + // Needs CInstanceBase pixel position + CEffectManager compass effects. + TraceError("ServerCommand StoneDetect not ported (effect): " + command); + } else if (!strcasecmp(szCmd, "StartStaminaConsume")) { + if (3 != TokenVector.size()) { strangeCount(); return; } + TraceError("ServerCommand StartStaminaConsume not ported (player stamina): " + command); + } else if (!strcasecmp(szCmd, "StopStaminaConsume")) { + if (2 != TokenVector.size()) { strangeCount(); return; } + TraceError("ServerCommand StopStaminaConsume not ported (player stamina): " + command); + } else if (!strcasecmp(szCmd, "sms")) { + m_bMobileFlag = true; + } else if (!strcasecmp(szCmd, "nosms")) { + m_bMobileFlag = false; + } else if (!strcasecmp(szCmd, "mobile_auth")) { + call("OnMobileAuthority", Py_BuildValue("()")); + } else if (!strcasecmp(szCmd, "messenger_auth")) { + call("OnMessengerAddFriendQuestion", Py_BuildValue("(s)", arg(1))); + } else if (!strcasecmp(szCmd, "combo")) { + // IAbstractPlayer::SetComboSkillFlag (skill slot level) is not ported; the stream flag is. + m_bComboSkillFlag = atoi(arg(1)) != 0; + } else if (!strcasecmp(szCmd, "setblockmode")) { + call("OnBlockMode", Py_BuildValue("(i)", atoi(arg(1)))); + } else { + // french_kiss..dig_motion are strcmpi branches; the rest is s_emotionDict (case sensitive). + static const char* const namedEmotions[] = { + "french_kiss", "kiss", "slap", "clap", "cheer1", "cheer2", "dance1", "dance2", "dig_motion", + }; + static const char* const dictEmotions[] = { + "dance3", "dance4", "dance5", "dance6", "congratulation", "forgive", "angry", "attractive", + "sad", "shy", "cheerup", "banter", "joy", + }; + bool isEmotion = false; + for (const char* emotion : namedEmotions) isEmotion = isEmotion || !strcasecmp(szCmd, emotion); + for (const char* emotion : dictEmotions) isEmotion = isEmotion || TokenVector[0] == emotion; + if (isEmotion) + TraceError("ServerCommand emotion not ported (CInstanceBase::ActEmotion): " + command); + else + TraceError("Unknown Server Command " + command + " | " + TokenVector[0]); + } +} + +void PythonNetworkStream::RegisterEmoticonString(const std::string& emoticon) { + if (m_emoticonStrings.size() >= 128) { // CInstanceBase::EMOTICON_NUM + TraceError("Can't register emoticon std::string... vector is full (size:" + std::to_string(m_emoticonStrings.size()) + ")"); + return; + } + m_emoticonStrings.push_back(emoticon); +} + +// CPythonNetworkStream::LoadInsultList + CInsultChecker (AVA2 PythonNetworkStreamPhaseLoading.cpp, +// InsultChecker.cpp). Non-Japan LocaleService: lead byte = high bit, compare = strnicmp. +bool PythonNetworkStream::LoadInsultList(const std::string& text) { + m_insults.clear(); + for (const std::string& line : ava2TextLines(text)) + if (line.length() > 0) + m_insults.push_back(line); + return true; +} + +namespace { +bool GetInsultLength(const std::vector& insults, const char* word, size_t* len) { + for (const std::string& insult : insults) { + if (0 == strncasecmp(word, insult.c_str(), insult.length())) { + *len = insult.length(); + return true; + } + } + return false; +} +} + +void PythonNetworkStream::FilterInsult(char* szLine, size_t uLineLen) const { + for (size_t uPos = 0; uPos < uLineLen;) { + uint8_t bChr = uint8_t(szLine[uPos]); + size_t uInsultLen; + if (GetInsultLength(m_insults, szLine + uPos, &uInsultLen)) { + memset(szLine + uPos, '*', uInsultLen); + uPos += uInsultLen; + } else { + uPos += (bChr & 0x80) ? 2 : 1; + } + } +} + +bool PythonNetworkStream::IsInsultIn(const char* c_szLine) const { + const size_t uLineLen = strlen(c_szLine); + size_t len; + for (size_t uPos = 0; uPos < uLineLen;) { + uint8_t bChr = uint8_t(c_szLine[uPos]); + if (GetInsultLength(m_insults, c_szLine + uPos, &len)) + return true; + uPos += (bChr & 0x80) ? 2 : 1; + } + return false; +} + +// Windows returns false while the filter is *enabled* (original inverted check kept). +bool PythonNetworkStream::IsChatInsultIn(const char* c_szMsg) const { + if (m_isEnableChatInsultFilter) + return false; + return IsInsultIn(c_szMsg); +} + +bool PythonNetworkStream::ParseEmoticon(const char* pChatMsg, uint32_t* pdwEmoticon) const { + for (uint32_t index = 0; index < m_emoticonStrings.size(); ++index) { + if (strlen(pChatMsg) > m_emoticonStrings[index].size()) + continue; + if (strstr(pChatMsg, m_emoticonStrings[index].c_str()) != pChatMsg) + continue; + *pdwEmoticon = index; + return true; + } + return false; +} + +void PythonNetworkStream::SendEmoticon(unsigned emoticon) { + if (emoticon < m_emoticonStrings.size()) + SendChatPacket(m_emoticonStrings[emoticon]); +} + +} // namespace ava2 diff --git a/src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp b/src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp new file mode 100644 index 00000000..39b84579 --- /dev/null +++ b/src/eter_net/PythonNetworkStreamPhaseGameRecv.cpp @@ -0,0 +1,1355 @@ +// Port of the remaining AVA2 GamePhase() receive handlers from +// upstream/ava2-client/UserInterface/PythonNetworkStreamPhaseGame.cpp, +// PythonNetworkStreamPhaseGameItem.cpp, PythonNetworkStreamPhaseGameActor.cpp and +// PythonNetworkStreamPhaseHandShake.cpp (Locale_inc.h feature set: ELEMENT_TARGET, +// ENABLE_HIDE_COSTUME_SYSTEM, ENABLE_MULTI_REFINE_WORLDARD, ENABLE_MULTILANGUAGE_SYSTEM, +// ENABLE_CHANNEL_CHANGE, ENABLE_ANTI_EXP, ENABLE_SASH_SYSTEM, ENABLE_KINGDOMS_WAR, +// ENABLE_MINI_GAME_CATCH_KING, ENABLE_DEFENSAWESHIP; no LOCALE_SERVICE_GLOBAL, no XTrap). +// Wire reads, Python callbacks and player/party state are 1:1. Work that needs systems the +// port does not have yet (minimap/atlas marks, background target effects, fly targets, +// motion queues, guild symbols, hybrid-crypt packs, anticheat, sash/bank/chest-drop native +// stores) is consumed and listed in docs/WINDOWS-PARITY.md. +#include "PythonNetworkStream.h" +#include "shared/common/PythonUtils.h" +#include "python_app.h" +#include "quest_state.h" +#include "guild_state.h" +#include "battlepass_state.h" +#include "drop_item_state.h" +#include "dungeon_info_state.h" +#include "switchbot_state.h" +#include "messenger_state.h" +#include "cube_renewal_state.h" +#include "shop_search_state.h" +#include "offline_shop_state.h" +#include "python_gameplay_modules.h" +#include "python_native_modules.h" +#include "python_minimap.h" +#include "nonplayer_data.h" +#include "python_event_manager.h" +#include "item_sound.h" +#include "NetworkActorManager.h" +#include +#include + +namespace ava2 { +namespace { + +void trace_error(const std::string& text) { std::cerr<<"[AVA2 TraceError] "< std::string text(const char (&field)[N]) { return std::string(field,strnlen(field,N)); } + +// CActorInstance type checks on the port's m_bType (0 enemy, 1 NPC, 2 stone, 3 warp, +// 4 door, 5 building, 6 PC). +bool is_enemy(const SNetworkActorData& d) { return d.m_bType==0; } +bool is_stone(const SNetworkActorData& d) { return d.m_bType==2; } +bool is_building(const SNetworkActorData& d) { return d.m_bType==5; } +bool is_pc(const SNetworkActorData& d) { return d.m_bType==6; } +bool is_dead(const SNetworkActorData& d) { return d.m_pActorInstance && d.m_pActorInstance->IsDead(); } +bool is_shop(const SNetworkActorData& d) { return d.m_dwRace>=30000 && d.m_dwRace<=30020; } +// CInstanceBase::IsWoodenDoor +bool is_wooden_door(const SNetworkActorData& d) { + return d.m_bType==4 && (d.m_dwRace==13000 || (d.m_dwRace>=30111 && d.m_dwRace<=30119)); +} +// CInstanceBase::CanViewTargetHP (+ ENABLE_DEFENSAWESHIP IsHydraNPC) +bool can_view_target_hp(const SNetworkActorData& d) { + return is_stone(d) || is_wooden_door(d) || is_enemy(d) || is_pc(d) || d.m_dwRace==6801; +} + +} + +SNetworkActorData* PythonNetworkStream::MainInstance() { + return m_dwMainActorVID ? NetworkActorManager::Instance().GetActorData(m_dwMainActorVID) : nullptr; +} + +void PythonNetworkStream::RefreshTargetBoardByVID(uint32_t vid) { + PyCallClassMemberFunc(m_phaseWindows[5],"RefreshTargetBoardByVID",Py_BuildValue("(i)",vid)); +} + +bool PythonNetworkStream::RecvChangeSpeedPacket() { + TPacketGCChangeSpeed p; + if(!Read(sizeof(p),&p)) return false; + return true; // SetWalkSpeed/SetRunSpeed are commented out in Windows. +} + +bool PythonNetworkStream::RecvMotionPacket() { + TPacketGCMotion p; + if(!Read(sizeof(p),&p)) return false; + return NetworkActorManager::Instance().GetActorData(p.vid)!=nullptr; +} + +// AVA2 RecvItemShop routes data directly to Python, without a parallel native store. +bool PythonNetworkStream::RecvItemShop() { + TPacketGCItemShop p;if(!Read(sizeof(p),&p)||p.sizeremaining||!Read(size,out))return false;remaining-=size;return true;}; + auto* game=m_phaseWindows[5];uint8_t sub;if(!get(1,&sub))return false; + auto log=[&](const TIShopLogData& r) { + PyCallClassMemberFunc(game,"ItemShopAppendLog",Py_BuildValue("(sissiiL)",text(r.buyDate).c_str(),r.buyTime,text(r.playerName).c_str(),text(r.ipAdress).c_str(), + int32_t(r.itemVnum),r.itemCount,static_cast(r.itemPrice))); + }; + switch(sub) { + case ITEMSHOP_DRAGONCOIN: { + int64_t coin;uint8_t open;if(!get(8,&coin)||!get(1,&open))return false; + if(open) {TIShopLogData r;if(!get(sizeof(r),&r))return false;log(r);} + PyCallClassMemberFunc(game,"ItemShopSetDragonCoin",Py_BuildValue("(L)",static_cast(coin)));break; + } + case ITEMSHOP_LOG: { + int32_t count;if(!get(4,&count))return false; + PyCallClassMemberFunc(game,"ItemShopHideLoading",Py_BuildValue("()")); + PyCallClassMemberFunc(game,"ItemShopLogClear",Py_BuildValue("()")); + if(count<0 || size_t(count)>remaining/sizeof(TIShopLogData))return false; + // Original receives the complete array before invoking its first append callback. + std::vector logs(size_t(count),TIShopLogData{}); + if(count && !get(sizeof(TIShopLogData)*size_t(count),logs.data()))return false; + for(const auto& r:logs)log(r); + PyCallClassMemberFunc(game,"ItemShopPurchasesWindow",Py_BuildValue("()"));break; + } + case ITEMSHOP_UPDATE_ITEM: { + TIShopData r;if(!get(sizeof(r),&r))return false; + PyCallClassMemberFunc(game,"ItemShopUpdateItem",Py_BuildValue("(iiLiiiiLi)",int32_t(r.id),int32_t(r.itemVnum),static_cast(r.itemPrice),int(r.discount),r.offerTime,r.topSellingIndex,r.addedTime,static_cast(r.sellCount),r.maxSellCount));break; + } + case ITEMSHOP_LOAD: { + int64_t coin;int32_t updateTime;if(!get(8,&coin)||!get(4,&updateTime))return false; + PyCallClassMemberFunc(game,"ItemShopSetDragonCoin",Py_BuildValue("(L)",static_cast(coin))); + PyCallClassMemberFunc(game,"ItemShopHideLoading",Py_BuildValue("()")); + PyCallClassMemberFunc(game,"ItemShopClear",Py_BuildValue("(i)",updateTime)); + int32_t count;if(!get(4,&count))return false; + if(count==9999) {PyCallClassMemberFunc(game,"ItemShopOpenMainPage",Py_BuildValue("()"));return true;} + if(count<0 || size_t(count)>remaining/2)return false; + for(int32_t j=0;j(r.itemPrice),int(r.discount),r.offerTime,r.topSellingIndex,r.addedTime,static_cast(r.sellCount),r.maxSellCount)); + } + } + PyCallClassMemberFunc(game,"ItemShopOpenMainPage",Py_BuildValue("()")); + } + break; + } + } + return true; // Original BUY/RELOAD/LOG_ADD/unknown subheaders leave payload unconsumed. +} + +bool PythonNetworkStream::RecvEventManager() { + TPacketGCEventManager p; + if(!Read(sizeof(p),&p)) return false; + uint8_t subIndex; + if(!Read(1,&subIndex)) return false; + PyObject* game=m_phaseWindows[5]; + if(subIndex==EVENT_MANAGER_LOAD) { + uint8_t dayCount; + if(!Read(1,&dayCount)) return false; + int32_t serverTime; + if(!Read(4,&serverTime)) return false; + PyCallClassMemberFunc(game,"ClearEventManager",Py_BuildValue("()")); + for(uint8_t j=0;j0) { + std::vector events(dayEventCount); + if(!Read(dayEventCount*sizeof(TEventManagerData),events.data())) return false; + for(const auto& e:events) + PyCallClassMemberFunc(game,"AppendEvent",Py_BuildValue("(iiissiiiiiiiii)",int(dayIndex),int(e.eventID),int(e.eventIndex), + text(e.startRealTime).c_str(),text(e.endRealTime).c_str(),int(e.empireFlag),int(e.channelFlag), + int(e.value[0]),int(e.value[1]),int(e.value[2]),int(e.value[3]), + e.startTime-serverTime,e.endTime==0?0:e.endTime-serverTime,int(e.eventStatus))); + } + } + PyCallClassMemberFunc(game,"RefreshEventManager",Py_BuildValue("()")); + } else if(subIndex==EVENT_MANAGER_EVENT_STATUS) { + uint16_t eventID;uint8_t eventStatus;int32_t endTime;char endTimeText[25];int32_t serverTime; + if(!Read(2,&eventID) || !Read(1,&eventStatus) || !Read(4,&endTime) || !Read(sizeof(endTimeText),endTimeText) || !Read(4,&serverTime)) + return false; + PyCallClassMemberFunc(game,"RefreshEventStatus",Py_BuildValue("(iiis)",int(eventID),int(eventStatus!=0), + endTime==0?0:endTime-serverTime,text(endTimeText).c_str())); + } + return true; +} + +bool PythonNetworkStream::RecvDuelStartPacket() { + TPacketGCDuelStart p; + if(!Read(sizeof(p),&p)) return false; + const uint32_t count=(uint32_t(p.wSize)-sizeof(p))/sizeof(uint32_t); + auto* main=MainInstance(); + if(!main) { + trace_error("CPythonNetworkStream::RecvDuelStartPacket - MainCharacter is NULL"); + return false; + } + auto& mgr=NetworkActorManager::Instance(); + for(uint32_t i=0;im_duelMode=count==0?DUEL_CANNOTATTACK:DUEL_START; + PyCallClassMemberFunc(m_phaseWindows[5],"CloseTargetBoard",Py_BuildValue("()")); + mgr.RefreshAllPCTextTail(); + return true; +} + +bool PythonNetworkStream::RecvPVPPacket() { + TPacketGCPVP p; + if(!Read(sizeof(p),&p)) return false; + auto& mgr=NetworkActorManager::Instance(); + const auto isMain=[this](uint32_t vid){ return vid==m_dwMainActorVID; }; + switch(p.bMode) { + case PVP_MODE_AGREE: + mgr.RemovePVPKey(p.dwVIDSrc,p.dwVIDDst); + if(isMain(p.dwVIDDst)) RememberChallengeInstance(p.dwVIDSrc); + if(isMain(p.dwVIDSrc)) RememberCantFightInstance(p.dwVIDDst); + break; + case PVP_MODE_REVENGE: + mgr.RemovePVPKey(p.dwVIDSrc,p.dwVIDDst); + if(isMain(p.dwVIDDst)) RememberRevengeInstance(p.dwVIDSrc); + if(isMain(p.dwVIDSrc)) RememberCantFightInstance(p.dwVIDDst); + break; + case PVP_MODE_FIGHT: + mgr.InsertPVPKey(p.dwVIDSrc,p.dwVIDDst); + ForgetInstance(p.dwVIDSrc);ForgetInstance(p.dwVIDDst); + break; + case PVP_MODE_NONE: + mgr.RemovePVPKey(p.dwVIDSrc,p.dwVIDDst); + ForgetInstance(p.dwVIDSrc);ForgetInstance(p.dwVIDDst); + break; + } + // CPythonCharacterManager::Insert/RemovePVPKey refresh both instances' text tails. + mgr.RefreshTextTail(p.dwVIDSrc); + mgr.RefreshTextTail(p.dwVIDDst); + RefreshTargetBoardByVID(p.dwVIDSrc); + RefreshTargetBoardByVID(p.dwVIDDst); + return true; +} + +bool PythonNetworkStream::RecvCharacterPositionPacket() { + TPacketGCPosition p; + if(!Read(sizeof(p),&p)) return false; + return true; // UpdatePosition is commented out in Windows. +} + +bool PythonNetworkStream::RecvScriptPacket() { + TPacketGCScript p; + if(!Read(sizeof(p),&p)) { trace_error("RecvScriptPacket_RecvError");return false; } + if(p.size items(count); + if(bytes && !Read(bytes,items.data()))return false; + auto& records=GetShopSearchItems();records.insert(records.end(),items.begin(),items.end()); + m_refreshShopSearch=true;return true; +} + +bool PythonNetworkStream::RecvCubeRenewalPacket() { + TPacketGCCubeRenewalReceive p;if(!Read(sizeof(p),&p))return false; + auto& cube=GetCubeRenewalState(); + switch(p.subheader) { + case CUBE_RENEWAL_SUB_HEADER_OPEN_RECEIVE: + PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_CUBE_RENEWAL_OPEN",Py_BuildValue("()"));break; + case CUBE_RENEWAL_SUB_HEADER_CLEAR_DATES_RECEIVE:cube.records.clear();break; + case CUBE_RENEWAL_SUB_HEADER_DATES_RECEIVE:cube.records.push_back(p.date_cube_renewal);break; + case CUBE_RENEWAL_SUB_HEADER_DATES_LOADING:cube.LoadingList();break; + default:break; + } + return true; +} + +bool PythonNetworkStream::RecvSwitchbotPacket() { + TPacketGCSwitchbot p;if(!Read(sizeof(p),&p)||p.size=sizeof(TSwitchbotAttributeTable)) { + TSwitchbotAttributeTable entry;if(!Read(sizeof(entry),&entry))return false; + state.attributes[entry.attribute_set][uint8_t(entry.apply_num)]=entry.max_value;size-=sizeof(entry); + } + } + return true; // Original unknown subheaders/trailing attribute bytes remain in the stream. +} + +bool PythonNetworkStream::RecvDungeonInfoPacket() { + TPacketGCDungeonInfoReceive p;if(!Read(sizeof(p),&p))return false; + auto& state=GetDungeonInfoState(); + switch(p.bSubType) { + case DUNGEON_INFO_SUB_HEADER_OPEN_SEND:PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_TABLE_DUNGEON_INFO_OPEN",Py_BuildValue("()"));break; + case DUNGEON_INFO_SUB_HEADER_DATES_CLEAR:state.Clear();break; + case DUNGEON_INFO_SUB_HEADER_DATES_MISION_CLEAR:state.missions.clear();break; + case DUNGEON_INFO_SUB_HEADER_DATES_SEND:state.info.push_back(p.dateinfo);break; + case DUNGEON_INFO_SUB_HEADER_DATES_MISION_SEND: + state.missions.push_back(p.dateinfom); + // AVA2 has no break here: mission receipt clears ranking. + [[fallthrough]]; + case DUNGEON_INFO_SUB_HEADER_DATES_RANKING_CLEAR:state.ranking.clear();break; + case DUNGEON_INFO_SUB_HEADER_DATES_RANKING_SEND:state.ranking.push_back(p.dateinfo_ranking);break; + case DUNGEON_INFO_SUB_HEADER_DATES_RANKING_LOAD:PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_TABLE_DUNGEON_RANKING_LOAD",Py_BuildValue("()"));break; + case DUNGEON_INFO_SUB_HEADER_DATES_MISION_LOAD:PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_TABLE_DUNGEON_MISION_LOAD",Py_BuildValue("()"));break; + } + return true; +} + +bool PythonNetworkStream::RecvDropItemPacket() { + TPacketGCDropItemReceive p;if(!Read(sizeof(p),&p))return false; + auto& state=GetDropItemState(); + switch(p.subheader) { + case DROP_ITEM_SUB_HEADER_OPEN_RECEIVE:PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_DROP_ITEM_OPEN",Py_BuildValue("()"));break; + case DROP_ITEM_SUB_HEADER_DATES_RECEIVE:state.records.push_back(p.info_drop);break; + case DROP_ITEM_SUB_HEADER_DATES_CLEAR_RECEIVE:state.Clear();break; + case DROP_ITEM_SUB_HEADER_DATES_LOADING:state.Loading();break; + } + return true; +} + +bool PythonNetworkStream::RecvBattlePassPacket() { + TPacketGCBattlePass p;if(!Read(sizeof(p),&p))return false; + auto& state=GetBattlePassState(); + switch(p.subheader) { + case BATTLEPASS_SUB_HEADER_OPEN:PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_BATTLEPASS_OPEN",Py_BuildValue("()"));break; + case BATTLEPASS_SUB_HEADER_MP:PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_BATTLEPASS_MP",Py_BuildValue("()"));break; + case BATTLEPASS_SUB_HEADER_INFO_EXTRA:state.time=p.time;break; + case BATTLEPASS_SUB_HEADER_INFO:state.info.push_back(p.data);break; + case BATTLEPASS_SUB_HEADER_UPDATE:state.progress.push_back(p.data);break; + case BATTLEPASS_SUB_HEADER_LOADING: + case BATTLEPASS_SUB_HEADER_UPDATE_LOADING:state.Loading(p.subheader);break; + case BATTLEPASS_SUB_HEADER_CLEAR: + case BATTLEPASS_SUB_HEADER_UPDATE_CLEAR:state.Clear(p.subheader);break; + } + return true; +} + +// AVA2 RecvGuild: bounded Win32 reads; callback order and refresh coalescing +// follow PythonNetworkStreamPhaseGame.cpp. No added subheader for GC_ADD. +bool PythonNetworkStream::RecvGuild() { + TPacketGCGuild p;if(!Read(sizeof(p),&p)||p.sizeremaining||!Read(size,out))return false;remaining-=size;return true;}; + auto& guild=GetGuildState();auto& messenger=GetMessengerState();auto* game=m_phaseWindows[5]; + auto target=[&](const std::string& name) {PyCallClassMemberFunc(game,"RefreshTargetBoardByName",Py_BuildValue("(s)",name.c_str()));}; + switch(p.subheader) { + case GUILD_SUBHEADER_GC_LOGIN: + case GUILD_SUBHEADER_GC_LOGOUT: { + uint32_t pid;if(!get(4,&pid))return false; + if(auto* member=guild.ByPID(pid);member && member->name!=GetMainCharacterName()) { + // Copy before invoking Python; the handler may mutate guild state. + const auto name=member->name; + if(p.subheader==GUILD_SUBHEADER_GC_LOGIN)messenger.LoginGuildMember(name); + else messenger.LogoutGuildMember(name); + } + break; + } + case GUILD_SUBHEADER_GC_REMOVE: { + uint32_t pid;if(!get(4,&pid))return false; + auto* member=guild.ByPID(pid);const std::string name=member?member->name:""; + if(member && name==GetMainCharacterName()) { + guild.Destroy();PyCallClassMemberFunc(game,"DeleteGuild",Py_BuildValue("()")); + messenger.RemoveAllGuildMember();SetGuildID(0); + m_refreshMessenger=true; + PyCallClassMemberFunc(game,"RefreshTargetBoard",Py_BuildValue("()")); + m_refreshCharacter=true; + } else { + if(member)messenger.RemoveGuildMember(name); + guild.RemoveMember(pid);target(name);m_refreshGuildMember=true; + } + break; + } + case GUILD_SUBHEADER_GC_LIST: + while(remaining) { + TPacketGCGuildSubMember m;if(!get(sizeof(m),&m))return false; + std::string name; + if(m.byNameFlag) {char raw[25];if(!get(sizeof(raw),raw))return false;name=text(raw);} + else if(auto* old=guild.ByPID(m.pid))name=old->name; + guild.RegisterMember({m.pid,name,m.byGrade,m.byJob,m.byLevel,m.byIsGeneral,m.dwOffer}); + if(name!=GetMainCharacterName())messenger.AppendGuildMember(name); + target(name); + } + m_refreshGuildInfo=m_refreshGuildMember=m_refreshMessenger=m_refreshCharacter=true; + break; + case GUILD_SUBHEADER_GC_GRADE: { + uint8_t count;if(!get(1,&count))return false; + for(unsigned i=0;isecond.name=text(name); + PyCallClassMemberFunc(game,"RefreshGuildGrade",Py_BuildValue("()")); + m_refreshGuildGrade=m_refreshGuildCombo=true;break; + } + case GUILD_SUBHEADER_GC_GRADE_AUTH: { + uint8_t grade,auth;if(!get(1,&grade)||!get(1,&auth))return false; + if(auto it=guild.grades.find(grade);it!=guild.grades.end())it->second.authority=auth; + PyCallClassMemberFunc(game,"RefreshGuildGrade",Py_BuildValue("()"));m_refreshGuildGrade=true;break; + } + case GUILD_SUBHEADER_GC_INFO: { + TPacketGCGuildInfo info;if(!get(sizeof(info),&info))return false; + guild.enabled=true;guild.info={info.guild_id,info.master_pid,info.level,info.exp,info.member_count,info.max_member_count,info.gold,std::string(info.name,strnlen(info.name,12)),info.hasLand}; + m_refreshGuildInfo=true;break; + } + case GUILD_SUBHEADER_GC_COMMENTS: { + uint8_t count;if(!get(1,&count))return false;guild.comments.clear(); + for(unsigned i=0;igrade=value; + else member->general=value; + } + m_refreshGuildMember=true;break; + } + case GUILD_SUBHEADER_GC_SKILL_INFO: + if(!get(1,&guild.skill.points)||!get(12,guild.skill.levels.data())||!get(2,&guild.skill.power)||!get(2,&guild.skill.maxPower))return false; + m_refreshGuildSkill=true;break; + case GUILD_SUBHEADER_GC_GUILD_INVITE: { + uint32_t id;char name[12];if(!get(4,&id)||!get(sizeof(name),name))return false; + PyCallClassMemberFunc(game,"RecvGuildInviteQuestion",Py_BuildValue("(is)",int32_t(id),text(name).c_str()));break; + } + case GUILD_SUBHEADER_GC_WAR: { + TPacketGCGuildWar war;if(!get(sizeof(war),&war))return false; + switch(war.bWarState) { + case GUILD_WAR_SEND_DECLARE:PyCallClassMemberFunc(game,"BINARY_GuildWar_OnSendDeclare",Py_BuildValue("(i)",int32_t(war.dwGuildOpp)));break; + case GUILD_WAR_RECV_DECLARE:PyCallClassMemberFunc(game,"BINARY_GuildWar_OnRecvDeclare",Py_BuildValue("(ii)",int32_t(war.dwGuildOpp),int(war.bType)));break; + case GUILD_WAR_ON_WAR:PyCallClassMemberFunc(game,"BINARY_GuildWar_OnStart",Py_BuildValue("(ii)",int32_t(war.dwGuildSelf),int32_t(war.dwGuildOpp)));guild.StartWar(war.dwGuildOpp);break; + case GUILD_WAR_END:PyCallClassMemberFunc(game,"BINARY_GuildWar_OnEnd",Py_BuildValue("(ii)",int32_t(war.dwGuildSelf),int32_t(war.dwGuildOpp)));guild.EndWar(war.dwGuildOpp);break; + } + break; + } + case GUILD_SUBHEADER_GC_GUILD_NAME: + if(remaining%16)return false; + while(remaining) {uint32_t id;char name[12];if(!get(4,&id)||!get(sizeof(name),name))return false;guild.names.insert({id,text(name)});} + break; + case GUILD_SUBHEADER_GC_GUILD_WAR_LIST: + case GUILD_SUBHEADER_GC_GUILD_WAR_END_LIST: + if(remaining%8)return false; + while(remaining) { + uint32_t src,dst;if(!get(4,&src)||!get(4,&dst))return false; + auto& actors=NetworkActorManager::Instance(); + if(p.subheader==GUILD_SUBHEADER_GC_GUILD_WAR_LIST)actors.InsertGVGKey(src,dst); + else actors.RemoveGVGKey(src,dst); + actors.ChangeGVG(src,dst); + } + break; + case GUILD_SUBHEADER_GC_WAR_POINT: { + TPacketGuildWarPoint point;if(!get(sizeof(point),&point))return false; + PyCallClassMemberFunc(game,"BINARY_GuildWar_OnRecvPoint",Py_BuildValue("(iii)",int32_t(point.dwGainGuildID),int32_t(point.dwOpponentGuildID),point.lPoint));break; + } + case GUILD_SUBHEADER_GC_MONEY_CHANGE: + if(!get(4,&guild.info.money))return false;m_refreshGuildInfo=true;break; + } + return true; // Unknown/ADD subheaders leave their bytes for Windows' dispatcher. +} + +// AVA2 RecvMessenger: retain membership on logout and emit mobile after online state. +bool PythonNetworkStream::RecvMessenger() { + TPacketGCMessenger p;if(!Read(sizeof(p),&p)||p.sizeremaining || !Read(count,dst))return false; + remaining-=count;return true; + }; + auto name=[&](uint8_t length,std::string& result) { + // The original writes to char[25] without bounds checks. Reject oversized names. + if(length>24)return false; + char bytes[25]{};if(!get(length,bytes))return false; + result=bytes;return true; + }; + auto& messenger=GetMessengerState(); + switch(p.subheader) { + case MESSENGER_SUBHEADER_GC_LIST: + while(remaining) { + TPacketGCMessengerListOnline entry;std::string key; + if(!get(sizeof(entry),&entry)||!name(entry.length,key))return false; + if(entry.connected&MESSENGER_CONNECTED_STATE_ONLINE)messenger.FriendLogin(key); + else messenger.FriendLogout(key); + if(entry.connected&MESSENGER_CONNECTED_STATE_MOBILE)messenger.SetMobile(key,1); + } + break; + case MESSENGER_SUBHEADER_GC_LOGIN: + case MESSENGER_SUBHEADER_GC_LOGOUT: { + uint8_t length;std::string key;if(!get(1,&length)||!name(length,key))return false; + if(p.subheader==MESSENGER_SUBHEADER_GC_LOGIN) { + messenger.FriendLogin(key); + PyCallClassMemberFunc(m_phaseWindows[5],"RefreshTargetBoardByName",Py_BuildValue("(s)",key.c_str())); + } else messenger.FriendLogout(key); + break; + } + case MESSENGER_SUBHEADER_GC_MOBILE: { + uint8_t state,length;std::string key; + if(!get(1,&state)||!get(1,&length)||!name(length,key))return false; + messenger.SetMobile(key,state);break; + } + // INVITE and unknown subheaders are ignored by Windows, without discarding payload. + default:break; + } + return true; +} + +// AVA2 RecvQuestInfoPacket: six-byte Win32 header and flag-ordered fields. +bool PythonNetworkStream::RecvQuestInfoPacket() { + uint8_t header,flags;uint16_t size,id; + if(!Read(1,&header)||!Read(2,&size)||!Read(2,&id)||!Read(1,&flags))return false; + // Reject a declared payload shorter than its flag-selected fields before a + // read can consume the next packet. Windows assumes trusted server lengths. + const size_t required=6+bool(flags&QUEST_SEND_IS_BEGIN)+31*bool(flags&QUEST_SEND_TITLE)+ + 17*bool(flags&QUEST_SEND_CLOCK_NAME)+4*bool(flags&QUEST_SEND_CLOCK_VALUE)+ + 17*bool(flags&QUEST_SEND_COUNTER_NAME)+4*bool(flags&QUEST_SEND_COUNTER_VALUE)+25*bool(flags&QUEST_SEND_ICON_FILE); + if(size0) { + for(uint32_t j=0;jm_stName.c_str())); + return true; +} + +bool PythonNetworkStream::RecvPartyAdd() { + TPacketGCPartyAdd p; + if(!Read(sizeof(p),&p)) return false; + const std::string name=text(p.name); + AppendPartyMember(p.pid,name); + PyCallClassMemberFunc(m_phaseWindows[5],"AddPartyMember",Py_BuildValue("(is)",int(p.pid),name.c_str())); + return true; +} + +bool PythonNetworkStream::RecvPartyUpdate() { + TPacketGCPartyUpdate p; + if(!Read(sizeof(p),&p)) return false; + uint8_t oldState; + if(!GetPartyMemberState(p.pid,&oldState)) return true; + UpdatePartyMemberInfo(p.pid,p.state,p.percent_hp); + for(uint8_t i=0;im_isFishing=true;break; + case FISHING_SUBHEADER_GC_STOP: if(inst->m_isFishing) inst->m_isFishing=false;break; + case FISHING_SUBHEADER_GC_REACT: break; + case FISHING_SUBHEADER_GC_SUCCESS: inst->m_isFishing=false;break; + case FISHING_SUBHEADER_GC_FAIL: + inst->m_isFishing=false; + if(inst==MainInstance()) PyCallClassMemberFunc(game,"OnFishingFailure",Py_BuildValue("()")); + break; + case FISHING_SUBHEADER_GC_FISH: { + if(p.info==0) { PyCallClassMemberFunc(game,"OnFishingNotifyUnknown",Py_BuildValue("()"));return true; } + std::string name;int type=0; + if(!GetItemNameAndType(p.info,&name,&type)) return true; + auto* main=MainInstance(); + if(!main) return true; + constexpr int ITEM_TYPE_FISH=12; + PyCallClassMemberFunc(game,main->m_isFishing?"OnFishingNotify":"OnFishingSuccess",Py_BuildValue("(is)",int(type==ITEM_TYPE_FISH),name.c_str())); + break; + } + } + return true; +} + +bool PythonNetworkStream::RecvPartyLink() { + TPacketGCPartyLink p; + if(!Read(sizeof(p),&p)) return false; + LinkPartyMember(p.pid,p.vid); + PyCallClassMemberFunc(m_phaseWindows[5],"LinkPartyMember",Py_BuildValue("(ii)",int(p.pid),int(p.vid))); + return true; +} + +bool PythonNetworkStream::RecvPartyUnlink() { + TPacketGCPartyUnlink p; + if(!Read(sizeof(p),&p)) return false; + UnlinkPartyMember(p.pid); + if(p.vid==m_dwMainActorVID) PyCallClassMemberFunc(m_phaseWindows[5],"UnlinkAllPartyMember",Py_BuildValue("()")); + else PyCallClassMemberFunc(m_phaseWindows[5],"UnlinkPartyMember",Py_BuildValue("(i)",int(p.pid))); + return true; +} + +// ENABLE_MULTI_REFINE_WORLDARD variants of RecvRefineInformationPacket(New). +template void PythonNetworkStream::RefineInformation(const Packet& p,bool isNew) { + const TRefineTable& t=p.refine_table; + PyObject* game=m_phaseWindows[5]; + switch(t.bSubType) { + case MULTIREFINE_CLEAR_INFO: PyCallClassMemberFunc(game,"BINARY_MULTI_REFINE_CLEAR_INFO",Py_BuildValue("()"));break; + case MULTIREFINE_ADD_INFO: + if(isNew) { + PyCallClassMemberFunc(game,"BINARY_MULTI_REFINE_ADD_INFO",Py_BuildValue("(iiiiiii)",t.index,int(p.pos),int(t.result_vnum),t.cost,t.prob, + int(t.special_storage),int(RefineType(p)))); + for(int i=0;im_walkMode=p.mode==0?0:1; // WALKMODE_RUN=0 + return true; +} + +bool PythonNetworkStream::RecvChangeSkillGroupPacket() { + TPacketGCChangeSkillGroup p; + if(!Read(sizeof(p),&p)) return false; + m_byMainActorSkillGroup=p.skill_group; + NEW_ClearSkillData(false); + m_refreshCharacter=true; // __RefreshCharacterWindow + return true; +} + +bool PythonNetworkStream::RecvNPCList() { + TPacketGCNPCPosition p; + if(!Read(sizeof(p),&p)) return false; + CPythonMiniMap::Instance().ClearAtlasMarkInfo(); + for(int i=0;i0;size-=int(sizeof(TLandPacketElement))) { + TLandPacketElement e; + if(!Read(sizeof(e),&e)) return false; + CPythonMiniMap::Instance().RegisterGuildArea(e.dwID,e.dwGuildID,e.x,e.y,e.width,e.height); + } + return true; +} + +bool PythonNetworkStream::RecvLoverInfoPacket() { + TPacketGCLoverInfo p; + if(!Read(sizeof(p),&p)) return false; + PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_LoverInfo",Py_BuildValue("(si)",text(p.name).c_str(),int(p.love_point))); + return true; +} + +bool PythonNetworkStream::RecvLovePointUpdatePacket() { + TPacketGCLovePointUpdate p; + if(!Read(sizeof(p),&p)) return false; + PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_UpdateLovePoint",Py_BuildValue("(i)",int(p.love_point))); + return true; +} + +bool PythonNetworkStream::RecvDigMotionPacket() { + TPacketGCDigMotion p; + if(!Read(sizeof(p),&p)) return false; + return true; // NEW_LookAtDestInstance + PushOnceMotion(NAME_DIG): motion queue not ported. +} + +bool PythonNetworkStream::RecvAccountBankPacket() { + TPacketGCBank p; + if(!Read(sizeof(p),&p)) return false; + // CPythonManagerBank::Append: the bank log store is not ported. + PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_Account_Bank_Logs",Py_BuildValue("()")); + return true; +} + +bool PythonNetworkStream::RecvHybridCryptPacket() { + TPacketGCHybridCryptKeys p; + if(!Read(sizeof(p),&p)) return false; + if(p.iKeyStreamLen<0 || m_recvBuffer.size()0?3:2);break; + default: + trace_error("CPythonNetworkStream::RecvKingdomsWarPacket: unknown subheader "+std::to_string(p.bSubHeader)+"\n."); + break; + } + return true; +} + +bool PythonNetworkStream::RecvSungmaAttrUpdatePacket() { + TPacketGCSungmaAttrUpdate p; + if(!Read(sizeof(p),&p)) return false; + PyCallClassMemberFunc(m_phaseWindows[5],"BINARY_SungMaAttr",Py_BuildValue("(iiii)",int(p.bSTR),int(p.bHP),int(p.bMOVE),int(p.bINMUNE))); + return true; +} + +bool PythonNetworkStream::RecvExchangeLog() { + TPacketGCExchangeLog p; + if(!Read(sizeof(p),&p)) return false; + uint8_t subIndex; + if(!Read(1,&subIndex)) return false; + PyObject* game=m_phaseWindows[5]; + if(subIndex==SUB_EXCHANGELOG_LOAD) { + char playerCode[19];uint8_t isNeedClean;uint16_t logCount; + if(!Read(sizeof(playerCode),playerCode) || !Read(1,&isNeedClean) || !Read(2,&logCount)) return false; + if(isNeedClean) PyCallClassMemberFunc(game,"ExchangeLogClear",Py_BuildValue("(s)",text(playerCode).c_str())); + for(uint32_t j=0;j items(itemCount); + if(!Read(itemCount*sizeof(TExchangeLogItem),items.data())) return false; + for(const auto& item:items) { + PyObject* sockets=PyList_New(0); + for(int32_t socket:item.alSockets) { PyObject* v=PyInt_FromLong(socket);PyList_Append(sockets,v);Py_DECREF(v); } + PyObject* attrType=PyList_New(0); + PyObject* attrValue=PyList_New(0); + for(const auto& attr:item.aAttr) { + PyObject* t=PyInt_FromLong(attr.bType);PyList_Append(attrType,t);Py_DECREF(t); + PyObject* v=PyInt_FromLong(attr.sValue);PyList_Append(attrValue,v);Py_DECREF(v); + } + PyCallClassMemberFunc(game,"ExchangeLogItemAppend",Py_BuildValue("(iiiiOOOi)",int(logID),int(item.pos),int(item.vnum),int(item.count), + sockets,attrType,attrValue,int(item.isOwner))); + Py_DECREF(sockets);Py_DECREF(attrType);Py_DECREF(attrValue); + } + } + PyCallClassMemberFunc(game,"ExchangeLogRefresh",Py_BuildValue("(i)",int(logID))); + } + return true; +} + +bool PythonNetworkStream::RecvMiniGameCatchKingPacket() { + TPacketGCMiniGameCatchKing p; + if(!Read(sizeof(p),&p)) return false; + const int packetSize=int(p.wSize)-int(sizeof(p)); + PyObject* game=m_phaseWindows[5]; + const auto fail=[&](int code){ + trace_error(" RecvMiniGamePacket Error 0x040"+std::to_string(p.bSubheader)+"BEBC"+std::to_string(code)); + }; + switch(p.bSubheader) { + case SUBHEADER_GC_CATCH_KING_EVENT_INFO: { + if(packetSize<=0) { fail(1);break; } + uint8_t isEnable; + if(!Read(1,&isEnable)) return false; + PyCallClassMemberFunc(game,"MiniGameCatchKingEvent",Py_BuildValue("(b)",int(isEnable))); + break; + } + case SUBHEADER_GC_CATCH_KING_START: { + if(packetSize<=0) { fail(2);break; } + uint32_t bigScore; + if(!Read(4,&bigScore)) return false; + PyCallClassMemberFunc(game,"MiniGameCatchKingEventStart",Py_BuildValue("(i)",int(bigScore))); + break; + } + case SUBHEADER_GC_CATCH_KING_SET_CARD: { + if(packetSize<=0) { fail(3);break; } + uint8_t card; + if(!Read(1,&card)) return false; + PyCallClassMemberFunc(game,"MiniGameCatchKingSetHandCard",Py_BuildValue("(i)",int(card))); + break; + } + case SUBHEADER_GC_CATCH_KING_RESULT_FIELD: { + if(packetSize<=0) { fail(4);break; } + TSubPacketGCCatchKingResult r; + if(!Read(sizeof(r),&r)) return false; + PyCallClassMemberFunc(game,"MiniGameCatchKingResultField",Py_BuildValue("(iiiibbbb)",int(r.dwPoints),int(r.bRowType),int(r.bCardPos),int(r.bCardValue), + int(r.bKeepFieldCard),int(r.bDestroyHandCard),int(r.bGetReward),int(r.bIsFiveNearBy))); + break; + } + case SUBHEADER_GC_CATCH_KING_SET_END_CARD: { + if(packetSize<=0) { fail(5);break; } + uint8_t card[2]; + if(!Read(2,card)) return false; + PyCallClassMemberFunc(game,"MiniGameCatchKingSetEndCard",Py_BuildValue("(ii)",int(card[0]),int(card[1]))); + break; + } + case SUBHEADER_GC_CATCH_KING_REWARD: { + if(packetSize<=0) { fail(6);break; } + uint8_t code; + if(!Read(1,&code)) return false; + PyCallClassMemberFunc(game,"MiniGameCatchKingReward",Py_BuildValue("(i)",int(code))); + break; + } + } + return true; +} + +bool PythonNetworkStream::Recv67AttrOpenPacket() { + TPacketGCBlank p; + if(!Read(sizeof(p),&p)) return false; + PyCallClassMemberFunc(m_phaseWindows[5],"OpenAttr67AddDlg",Py_BuildValue("()")); + return true; +} + +bool PythonNetworkStream::RecvCheatBlacklist() { + TPacketGCCheatBlacklist p; + if(!Read(sizeof(p),&p)) return false; + return true; // CAnticheatManager::ParseCheatBlacklist: anticheat is not ported. +} + +// PythonNetworkStreamPhaseHandShake.cpp +bool PythonNetworkStream::RecvHandshakePacket() { + TPacketGCHandshake p; + if(!Read(sizeof(p),&p)) return false; + m_changeServerTime=p.dwTime+uint32_t(p.lDelta); + m_changeClientTime=GetLocalMSec(); + p.dwTime=p.dwTime+uint32_t(p.lDelta)+uint32_t(p.lDelta); + p.lDelta=0; + p.bHeader=HEADER_CG_TIME_SYNC; + Send(&p,sizeof(p)); // + SendSequence + return true; +} + +bool PythonNetworkStream::RecvHandshakeOKPacket() { + TPacketGCBlank p; + if(!Read(sizeof(p),&p)) return false; + const uint32_t delta=GetLocalMSec()-m_changeClientTime; + SetServerMSec(m_changeServerTime+delta); + return true; +} + +} // namespace ava2 + +namespace ava2 { +bool PythonNetworkStream::RecvOfflineShopPacket() { + TPacketGCShop header;if(!Read(sizeof(header),&header)||header.sizeremaining||!Read(size,data))return false;remaining-=size;return true;}; + auto& state=GetOfflineShopState(); + auto call=[&](const char* method,PyObject* args) {PyCallClassMemberFunc(m_phaseWindows[5],method,args);}; + auto log=[&](const char* method,const TShopLog& entry) { + if(entry.price)call(method,Py_BuildValue("(ssiiL)",text(entry.name).c_str(),text(entry.date).c_str(),int32_t(entry.itemVnum),int32_t(entry.itemCount),static_cast(entry.price))); + }; + // AVA2 reads these six scalar payloads directly; all other cases consume the declared payload first. + switch(header.subheader) { + case SHOP_SUBHEADER_GC_REFRESH_MONEY: + if(!read(&state.money,8))return false;break; + case SHOP_SUBHEADER_GC_CHECK_RESULT: { + uint8_t has;if(!read(&has,1))return false;state.hasShop=has==1;return true; + } + case SHOP_SUBHEADER_GC_REFRESH_DISPLAY_COUNT: + if(!read(&state.displayed,4))return false;break; + case SHOP_SUBHEADER_GC_REALWATCHER_COUNT: + if(!read(&state.watchers,4))return false;break; + case SHOP_SUBHEADER_GC_REFRESH_COUNT: { + uint32_t counts[2];if(!read(counts,8))return false;state.displayed=counts[0];state.watchers=counts[1];break; + } + case SHOP_SUBHEADER_GC_CHANGE_TITLE: { + char sign[46];if(!read(sign,sizeof(sign)))return false;state.sign=text(sign);break; + } + default: { + std::vector payload(remaining);if(remaining&&!read(payload.data(),remaining))return false; + switch(header.subheader) { + case SHOP_SUBHEADER_GC_START: { + TPacketGCOfflineShopStart packet;if(payload.size()=0;--i)log("AppendShopLog",packet.log[i]); + call("StartOfflineShop",Py_BuildValue("(ii)",int32_t(packet.owner_vid),packet.IsOwner!=0));return true; + } + case SHOP_SUBHEADER_GC_END: + ClearShopState();call("ClearOfflineShopLog",Py_BuildValue("()"));call("EndOfflineShop",Py_BuildValue("()"));return true; + case SHOP_SUBHEADER_GC_UPDATE_ITEM: { + TPacketGCOfflineShopUpdateItem packet;if(payload.size() #include #include @@ -21,9 +23,186 @@ std::string ActorInstance::ResolvePath(const std::string& path) const { if (std::filesystem::exists(clean)) return clean; if (std::filesystem::exists("build/dev/" + clean)) return "build/dev/" + clean; if (std::filesystem::exists("../" + clean)) return "../" + clean; + // Pack paths ("d:/ymir work/...", mixed case) go through the CResourceManager candidates. + std::error_code error; + for (const auto& candidate : CResourceManager::GetCandidatePaths(CResourceManager::NormalizePath(path.c_str()))) + if (std::filesystem::is_regular_file(candidate, error)) return candidate; return clean; } +std::shared_ptr ActorInstance::LoadPartModel(const std::string& path) const { + if (path.empty()) return nullptr; + std::string resolved = ResolvePath(path); + std::error_code error; + if (!std::filesystem::is_regular_file(resolved, error)) { + std::cerr << "ActorInstance: model not found: " << path << std::endl; + return nullptr; + } + return std::shared_ptr(Gr2ModelInstance::Load(resolved)); +} + +void ActorInstance::SetMainModel(std::shared_ptr model, const std::string& path) { + m_model = std::move(model); + m_modelPath = m_model ? path : std::string(); + RebindParts(); + // A new PART_MAIN instance restarts the current motion on it. + if (m_model) { + auto it = m_motionPaths.find(m_currentMotion); + if (it != m_motionPaths.end()) { + std::string resolved = ResolvePath(it->second); + if (m_model->LoadExternalAnimation(resolved)) + m_motionDuration = std::max(0.1f, m_model->GetAnimationDuration()); + } + } +} + +// Re-attaches the part slots to PART_MAIN: hair deforms with the main skeleton, the others follow +// their attaching bone; PART_SASH also takes the ENABLE_OBJ_SCALLING scale matrix. +void ActorInstance::RebindParts() { + if (!m_model) return; + m_model->DetachAll(); + for (uint32_t part = 1; part < kPartCount; ++part) { + const auto& slot = m_parts[part]; + if (!slot.model) continue; + if (slot.bone.empty()) { + m_model->AttachPart(slot.model); + continue; + } + m_model->AttachModel(slot.bone, slot.model); + if (part == RaceData::PART_SASH) { + m_model->SetAttachmentAnimated(slot.bone, true); + if (m_hasSashScale) m_model->SetAttachmentScale(slot.bone, m_sashScale[0], m_sashScale[1], m_sashScale[2]); + } + } +} + +bool ActorInstance::SetRace(uint32_t race) { + RaceData* raceData = RaceManager::Instance().GetRaceDataPointer(race); + if (!raceData) { + m_race = 0; + m_raceData = nullptr; + return false; + } + m_race = race; + m_raceData = raceData; + + // memset(m_adwPartItemID) + CGraphicThingInstance::Clear(): every part model is dropped. + std::fill(std::begin(m_partItemID), std::end(m_partItemID), 0u); + for (auto& slot : m_parts) slot = SPartSlot{}; + m_model.reset(); + m_modelPath.clear(); + m_shapeFile.clear(); + + // SetMotionIndex(eRace): the race's GENERAL motion set (motlist.txt for NPC races, the + // chrmgr.RegisterMotionData calls for races built from Python). + m_motionPaths.clear(); + m_motionQueue.clear(); + { + static const RaceData::EMotion kNames[] = { + RaceData::NAME_WAIT, RaceData::NAME_WALK, RaceData::NAME_RUN, RaceData::NAME_CHANGE_WEAPON, + RaceData::NAME_DAMAGE, RaceData::NAME_DEAD, RaceData::NAME_NORMAL_ATTACK, + RaceData::NAME_COMBO_ATTACK_1, RaceData::NAME_COMBO_ATTACK_2, RaceData::NAME_COMBO_ATTACK_3, + }; + for (auto name : kNames) { + const auto* motions = raceData->GetMotions(name); + if (!motions || motions->empty()) continue; + // The percent-weighted random pick of CActorInstance is not ported: the first entry plays. + std::string gr2 = ReadMotionFileName(motions->front().fileName); + if (!gr2.empty()) RegisterMotion(static_cast(name), gr2); + } + } + return true; +} + +void ActorInstance::SetShape(uint32_t shape, float specular) { + (void)specular; // SMaterialData specular / sphere map: not rendered by the port yet. + m_shape = shape; + RaceData* raceData = RaceManager::Instance().GetRaceDataPointer(m_race); + if (!raceData) return; + + const RaceData::Shape* pkShape = raceData->FindShape(shape); + if (pkShape) { + const std::string& file = pkShape->model.empty() ? raceData->GetBaseModelFileName() : pkShape->model; + // The _lod_01.._03 LOD things are not ported: LOD 0 always draws. + auto model = LoadPartModel(file); + if (model) { + for (const auto& skin : pkShape->skins) model->SetSkin(skin.srcFileName, skin.dstFileName); + } + m_shapeFile = file; + SetMainModel(std::move(model), file); + } else if (raceData->IsTree()) { + // __CreateTree (SpeedTree actors) is not ported. + m_shapeFile.clear(); + SetMainModel(nullptr, std::string()); + } else { + const std::string& file = raceData->GetBaseModelFileName(); + m_shapeFile = file; + SetMainModel(LoadPartModel(file), file); + } +} + +void ActorInstance::SetHair(uint32_t hair) { + m_hair = hair; + RaceData* raceData = RaceManager::Instance().GetRaceDataPointer(m_race); + if (!raceData) return; + const RaceData::Shape* pkHair = raceData->FindHair(hair); + if (!pkHair) return; // the previous hair instance stays + if (!pkHair->model.empty()) { + m_parts[RaceData::PART_HAIR].model = LoadPartModel(pkHair->model); + m_parts[RaceData::PART_HAIR].file = pkHair->model; + m_parts[RaceData::PART_HAIR].bone.clear(); + } + if (auto& model = m_parts[RaceData::PART_HAIR].model) + for (const auto& skin : pkHair->skins) model->SetSkin(skin.srcFileName, skin.dstFileName); + RebindParts(); +} + +void ActorInstance::AttachWeaponPart(uint32_t part, const SPartItem& item) { + std::string bone; + if (!m_raceData || !m_raceData->GetAttachingBoneName(part, &bone)) return; + // PART_WEAPON_LEFT registers GetSubModelThing(), which is the same model file. + m_parts[part].model = LoadPartModel(item.model); + m_parts[part].file = item.model; + m_parts[part].bone = bone; + // USE_WEAPON_SPECULAR sphere map and CWeaponTrace are not ported. +} + +void ActorInstance::AttachWeapon(uint32_t itemIndex, const SPartItem* item, bool isMountingHorse) { + enum { WEAPON_DAGGER = 1, WEAPON_BOW = 2, WEAPON_FAN = 5 }; + m_partItemID[RaceData::PART_WEAPON] = itemIndex; + if (!item) { + m_parts[RaceData::PART_WEAPON] = SPartSlot{}; + m_parts[RaceData::PART_WEAPON_LEFT] = SPartSlot{}; + RebindParts(); + return; + } + const uint32_t type = item->weaponType; + const bool dual = type == WEAPON_DAGGER || (type == WEAPON_FAN && isMountingHorse); + // __IsRightHandWeapon / __IsLeftHandWeapon. A slot that is not re-attached keeps its old model + // (e.g. a dagger's left blade stays after switching to a sword), as on Windows. + if (dual || type != WEAPON_BOW) AttachWeaponPart(RaceData::PART_WEAPON, *item); + if (dual || type == WEAPON_BOW) AttachWeaponPart(RaceData::PART_WEAPON_LEFT, *item); + RebindParts(); +} + +void ActorInstance::AttachSash(const SPartItem* item, float specular) { + (void)specular; // sphere-map specular not rendered. + if (!item) { + m_parts[RaceData::PART_SASH] = SPartSlot{}; + } else { + m_parts[RaceData::PART_SASH].model = LoadPartModel(item->model); + m_parts[RaceData::PART_SASH].file = item->model; + m_parts[RaceData::PART_SASH].bone = "Bip01 Spine2"; + } + RebindParts(); +} + +void ActorInstance::SetSashScale(float sx, float sy, float sz) { + m_hasSashScale = true; + m_sashScale[0] = sx; m_sashScale[1] = sy; m_sashScale[2] = sz; + RebindParts(); +} + bool ActorInstance::SetModel(const std::string& modelPath) { std::string resolved = ResolvePath(modelPath); if (!std::filesystem::exists(resolved)) { @@ -101,12 +280,44 @@ bool ActorInstance::PlayMotion(MotionType type, bool loop) { return true; } +bool ActorInstance::PlayMotionIndex(uint32_t index, bool loop) { + uint16_t keyMode; + if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false; + const auto* motions = m_raceData->GetMotions(keyMode, index); + if (!motions || motions->empty()) return false; + const std::string gr2 = ReadMotionFileName(motions->front().fileName); + if (gr2.empty()) return false; + RegisterMotion(static_cast(index), gr2); + return PlayMotion(static_cast(index), loop); +} + +bool ActorInstance::SetLoopMotionIndex(uint32_t index) { + uint16_t keyMode; + if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false; + m_motionQueue.clear(); // __ClearMotion + return PlayMotionIndex(index, true); +} + +bool ActorInstance::InterceptMotionIndex(uint32_t index, bool loop) { + uint16_t keyMode; + if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false; + m_motionQueue.clear(); // __ClearMotion + return PlayMotionIndex(index, loop); +} + +bool ActorInstance::PushMotionIndex(uint32_t index, bool loop) { + uint16_t keyMode; + if (!m_raceData || !m_raceData->GetMotionKey(uint16_t(m_motionMode), uint16_t(index), &keyMode)) return false; + m_motionQueue.emplace_back(index, loop); + return true; +} + bool ActorInstance::IsMotionFinished() const { if (m_loopMotion) return false; return m_animTime >= m_motionDuration; } -void ActorInstance::MoveInDirection(float moveYaw, float dt, const TerrainHeightmap* terrain, const MapObjectManager* mapObjects) { +void ActorInstance::MoveInDirection(float moveYaw, float dt, const TerrainHeightSource* terrain, const MapObjectManager* mapObjects) { if (dt <= 0.0f) return; float rad = moveYaw * DEG_TO_RAD; m_yaw = moveYaw; @@ -170,7 +381,7 @@ void ActorInstance::StopMoving() { } } -void ActorInstance::Update(float dt, const TerrainHeightmap* terrain, const MapObjectManager* mapObjects) { +void ActorInstance::Update(float dt, const TerrainHeightSource* terrain, const MapObjectManager* mapObjects) { if (dt <= 0.0f) return; // 0. Click-to-Move destination pathing (aligned with 40250 CPythonPlayer) @@ -231,7 +442,12 @@ void ActorInstance::Update(float dt, const TerrainHeightmap* terrain, const MapO // Advance animation time m_animTime += dt; - if (m_loopMotion) { + if (!m_motionQueue.empty() && m_animTime >= m_motionDuration) { + // ReservingMotionProcess: the next pushed motion takes over when the current one ends. + const auto next = m_motionQueue.front(); + m_motionQueue.pop_front(); + PlayMotionIndex(next.first, next.second); + } else if (m_loopMotion) { if (m_motionDuration > 0.001f && m_animTime >= m_motionDuration) { m_animTime = std::fmod(m_animTime, m_motionDuration); } diff --git a/src/eter_render/ActorInstance.h b/src/eter_render/ActorInstance.h index 544e06e2..16a100a8 100644 --- a/src/eter_render/ActorInstance.h +++ b/src/eter_render/ActorInstance.h @@ -2,6 +2,7 @@ #include "Gr2ModelRenderer.h" #include "TerrainHeightmap.h" +#include #include #include #include @@ -9,6 +10,8 @@ namespace ava2 { +class RaceData; + // Metin2 standard motion types (aligned with 40250 CRaceMotionData::EName) enum class MotionType { None = 0, @@ -44,6 +47,33 @@ public: // Attach skinned hair / armor parts bool AttachPart(const std::string& partPath); + // CActorInstance race/part API (GameLib ActorInstanceData.cpp / ActorInstanceAttach.cpp) driven by + // CRaceManager .msm data. Parts live in CRaceData::EParts slots and are re-bound onto the main model. + struct SPartItem { + std::string model; // CItemData::GetModelThing file (item_list column 4) + uint32_t weaponType = 0; // CItemData::GetWeaponType + }; + // SetRace: clears every part and, for races > 8 (LoadAllMotions), registers the GENERAL motions. + bool SetRace(uint32_t race); + uint32_t GetRace() const { return m_race; } + // SetShape(eShape, fSpecular): .msm ShapeData model + skins, else the base model. + void SetShape(uint32_t shape, float specular = 0.0f); + uint32_t GetShape() const { return m_shape; } + // SetHair: .msm HairData model on PART_HAIR (skinned to PART_MAIN) + its skins. + void SetHair(uint32_t hair); + // AttachWeapon(dwItemIndex): item == nullptr is a failed GetItemDataPointer. + void AttachWeapon(uint32_t itemIndex, const SPartItem* item, bool isMountingHorse); + // AttachSash(pItemData, fSpecular): "Bip01 Spine2", the sash plays its own motion 0. + void AttachSash(const SPartItem* item, float specular); + // ENABLE_OBJ_SCALLING SetScale(x, y, z, true): only PART_SASH is deformed with m_TransformMatrix. + void SetSashScale(float sx, float sy, float sz); + uint32_t GetPartItemID(uint32_t part) const { return part < kPartCount ? m_partItemID[part] : 0; } + // Inspection helpers (tests): the requested PART_MAIN / part model file (a CGraphicThing handle on + // Windows exists even when the gr2 fails to load) and the bone the part is attached to. + const std::string& GetShapeModelFile() const { return m_shapeFile; } + std::string GetPartModelPath(uint32_t part) const { return part < kPartCount ? m_parts[part].file : std::string(); } + std::string GetPartBone(uint32_t part) const { return part < kPartCount ? m_parts[part].bone : std::string(); } + void SetScale(float s) { m_scale = s; } float GetScale() const { return m_scale; } @@ -59,6 +89,17 @@ public: float GetAnimTime() const { return m_animTime; } bool IsAttacking() const { return m_isAttacking; } + // CActorInstance::SetMotionMode / GetMotionMode (m_wcurMotionMode; polymorphs stay GENERAL). + void SetMotionMode(int mode) { m_motionMode = m_isPolymorph ? 1 : mode; } + int GetMotionMode() const { return m_motionMode; } + // CActorInstance::SetLoopMotion / InterceptMotion / PushOnceMotion / PushLoopMotion: the motion + // index resolves through CRaceData::GetMotionKey(m_wcurMotionMode, index). Blend times, speed + // ratios and the percent-weighted random pick are not ported (the first registered motion plays); + // a pushed motion starts when the current one ends (a loop at its cycle end). + bool SetLoopMotionIndex(uint32_t index); + bool InterceptMotionIndex(uint32_t index, bool loop); + bool PushMotionIndex(uint32_t index, bool loop); + // World transform void SetPosition(float x, float y, float z) { m_posX = x; m_posY = y; m_posZ = z; } void GetPosition(float& x, float& y, float& z) const { x = m_posX; y = m_posY; z = m_posZ; } @@ -90,9 +131,9 @@ public: bool HitTestScreen(float clickX, float clickY, const Gr2SceneRenderer& renderer, float tolerancePx = 40.0f) const; // Smooth movement and continuous animation update - void MoveInDirection(float moveYaw, float dt, const TerrainHeightmap* terrain = nullptr, const class MapObjectManager* mapObjects = nullptr); + void MoveInDirection(float moveYaw, float dt, const TerrainHeightSource* terrain = nullptr, const class MapObjectManager* mapObjects = nullptr); void StopMoving(); - void Update(float dt, const TerrainHeightmap* terrain = nullptr, const class MapObjectManager* mapObjects = nullptr); + void Update(float dt, const TerrainHeightSource* terrain = nullptr, const class MapObjectManager* mapObjects = nullptr); // Polymorph System (变身系统) bool SetPolymorph(uint32_t mobVnum); @@ -120,6 +161,9 @@ public: void SetSleep(bool value) { m_sleep=value; } void SetParalysis(bool value) { m_paralysis=value; } void SetFaint(bool value) { m_faint=value; } + bool IsFaint() const { return m_faint; } + // CActorInstance::Revive: clears the sleep/paralysis/faint/dead/stun states (HP back to max). + void Revive() { m_sleep=m_paralysis=m_faint=m_stunned=false; m_curHP=m_maxHP; } bool CanAct() const { return !IsDead() && !m_stunned && !m_paralysis && !m_faint && !m_sleep; } bool IsDead() const { return m_curHP <= 0; } @@ -163,6 +207,26 @@ public: private: std::string ResolvePath(const std::string& path) const; + std::shared_ptr LoadPartModel(const std::string& path) const; + void SetMainModel(std::shared_ptr model, const std::string& path); + void AttachWeaponPart(uint32_t part, const SPartItem& item); + void RebindParts(); + + static constexpr uint32_t kPartCount = 7; // CRaceData::PART_MAX_NUM + struct SPartSlot { + std::shared_ptr model; + std::string bone; // empty: skinned to PART_MAIN (hair) + std::string file; // the requested model thing (kept even if the gr2 fails to load) + }; + std::string m_shapeFile; + uint32_t m_race = 0; + uint32_t m_shape = 0; + uint32_t m_hair = 0; + RaceData* m_raceData = nullptr; + SPartSlot m_parts[kPartCount]; + uint32_t m_partItemID[kPartCount] = {}; + bool m_hasSashScale = false; + float m_sashScale[3] = {1.0f, 1.0f, 1.0f}; std::shared_ptr m_model; std::string m_modelPath; @@ -172,6 +236,9 @@ private: float m_animTime = 0.0f; float m_motionDuration = 1.0f; bool m_loopMotion = true; + int m_motionMode = 1; // CRaceMotionData::MODE_GENERAL + std::deque> m_motionQueue; // m_MotionDeque (index, loop) + bool PlayMotionIndex(uint32_t index, bool loop); bool m_isAttacking = false; int m_comboIndex = 0; std::unordered_map m_buffs; diff --git a/src/eter_render/EnvironmentData.cpp b/src/eter_render/EnvironmentData.cpp index cf8fb0fb..026cd1f0 100644 --- a/src/eter_render/EnvironmentData.cpp +++ b/src/eter_render/EnvironmentData.cpp @@ -170,6 +170,11 @@ bool EnvironmentData::LoadFromString(const std::string& content) { continue; } + if (current_scope.empty() && lower_token == "reserved") { + int v = 0; line_stream >> v; reserve = (v != 0); + continue; + } + // Directional Light scope if (current_scope == "directionallight") { if (lower_token == "direction") { diff --git a/src/eter_render/EnvironmentData.h b/src/eter_render/EnvironmentData.h index ef01f00b..7e15b5d3 100644 --- a/src/eter_render/EnvironmentData.h +++ b/src/eter_render/EnvironmentData.h @@ -71,6 +71,7 @@ struct LensFlareData { struct EnvironmentData { std::string name; + bool reserve = false; // MapUtil.cpp Environment_Load "reserved" (bReserve) DirectionalLight dir_light; MaterialData material; FogData fog; diff --git a/src/eter_render/Gr2ModelRenderer.cpp b/src/eter_render/Gr2ModelRenderer.cpp index 6db4659e..e4e0cbeb 100644 --- a/src/eter_render/Gr2ModelRenderer.cpp +++ b/src/eter_render/Gr2ModelRenderer.cpp @@ -148,6 +148,51 @@ void Gr2ModelInstance::AttachPart(std::shared_ptr part) { if (part) m_attached_parts.push_back(part); } +void Gr2ModelInstance::DetachModel(const std::string& bone_name) { + m_attached_models.erase(std::remove_if(m_attached_models.begin(), m_attached_models.end(), + [&](const AttachedModel& am) { return am.bone_name == bone_name; }), m_attached_models.end()); +} + +void Gr2ModelInstance::DetachPart(const std::shared_ptr& part) { + m_attached_parts.erase(std::remove(m_attached_parts.begin(), m_attached_parts.end(), part), m_attached_parts.end()); +} + +void Gr2ModelInstance::SetAttachmentAnimated(const std::string& bone_name, bool animated) { + for (auto& am : m_attached_models) + if (am.bone_name == bone_name) am.animated = animated; +} + +void Gr2ModelInstance::SetAttachmentScale(const std::string& bone_name, float sx, float sy, float sz) { + for (auto& am : m_attached_models) { + if (am.bone_name != bone_name) continue; + am.scaled = true; + am.scale[0] = sx; am.scale[1] = sy; am.scale[2] = sz; + } +} + +namespace { +// CFileNameHelper::StringPath (lower case, '\\' -> '/'), the form CGrannyMaterial::IsIn compares. +std::string SkinKey(std::string path) { + for (auto& c : path) { + if (c == '\\') c = '/'; + else if (static_cast(c) < 128) c = static_cast(std::tolower(static_cast(c))); + } + return path; +} +} // namespace + +void Gr2ModelInstance::SetSkin(const std::string& src_file_name, const std::string& dst_file_name) { + m_skins[SkinKey(src_file_name)] = dst_file_name; +} + +void Gr2ModelInstance::ApplySkins(std::vector& draws, size_t first) const { + if (m_skins.empty()) return; + for (size_t i = first; i < draws.size(); ++i) { + auto it = m_skins.find(SkinKey(draws[i].texture0)); + if (it != m_skins.end()) draws[i].texture0 = it->second; + } +} + void Gr2ModelInstance::DetachAll() { m_attached_models.clear(); m_attached_parts.clear(); @@ -306,6 +351,7 @@ std::vector Gr2ModelInstance::BuildDrawCommandsWithPalette(const s } } } + ApplySkins(draws, 0); return draws; } @@ -435,6 +481,8 @@ std::vector Gr2ModelInstance::BuildDrawCommands(float animation_ti } } + ApplySkins(draws, 0); + // 2. Build attached skinning parts (e.g. hair, armor) using current skin matrices for (const auto& part : m_attached_parts) { if (!part) continue; @@ -461,6 +509,10 @@ std::vector Gr2ModelInstance::BuildDrawCommands(float animation_ti const auto& B = world_pose[bone_idx]; float attached_local[16]; MultiplyMat4(am.offset, B.data(), attached_local); + if (am.scaled) { + const float S[16] = {am.scale[0], 0, 0, 0, 0, am.scale[1], 0, 0, 0, 0, am.scale[2], 0, 0, 0, 0, 1}; + MultiplyMat4(attached_local, S, attached_local); + } float attached_engine[16]; MultiplyMat4(attached_local, R_GRANNY_TO_ENGINE, attached_engine); float final_world[16]; @@ -470,7 +522,12 @@ std::vector Gr2ModelInstance::BuildDrawCommands(float animation_ti std::copy(attached_engine, attached_engine + 16, final_world); } - auto attach_draws = am.model->BuildDrawCommands(-1.0f, nullptr); + float attach_time = -1.0f; + if (am.animated && animation_time >= 0.0f) { + float duration = am.model->GetAnimationDuration(); + attach_time = duration > 0.0f ? std::fmod(animation_time, duration) : 0.0f; + } + auto attach_draws = am.model->BuildDrawCommands(attach_time, nullptr); for (auto& ad : attach_draws) { std::copy(final_world, final_world + 16, ad.world); draws.push_back(std::move(ad)); @@ -630,6 +687,16 @@ void Gr2SceneRenderer::SetCameraLookAt(float eyeX, float eyeY, float eyeZ, m_view[15]= 1.0f; } +void Gr2SceneRenderer::SetCameraLookAtRH(float eyeX, float eyeY, float eyeZ, + float targetX, float targetY, float targetZ, + float upX, float upY, float upZ) { + SetCameraLookAt(eyeX, eyeY, eyeZ, targetX, targetY, targetZ, upX, upY, upZ); + m_view[0] = -m_view[0]; + m_view[4] = -m_view[4]; + m_view[8] = -m_view[8]; + m_view[12] = -m_view[12]; +} + void Gr2SceneRenderer::SetPerspective(float fovYDegrees, float aspect, float zNear, float zFar) { float fovRad = fovYDegrees * 3.1415926535f / 180.0f; float h = 1.0f / std::tan(fovRad * 0.5f); @@ -710,9 +777,11 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw } if (i * 3 + 2 < draw.normals.size()) { - xverts[i].nx = draw.normals[i * 3 + 0]; - xverts[i].ny = draw.normals[i * 3 + 1]; - xverts[i].nz = draw.normals[i * 3 + 2]; + // Lit normals are transformed by the world 3x3 (D3DTS_WORLD) before N.L. + float on0 = draw.normals[i * 3 + 0], on1 = draw.normals[i * 3 + 1], on2 = draw.normals[i * 3 + 2]; + xverts[i].nx = on0 * draw.world[0] + on1 * draw.world[4] + on2 * draw.world[8]; + xverts[i].ny = on0 * draw.world[1] + on1 * draw.world[5] + on2 * draw.world[9]; + xverts[i].nz = on0 * draw.world[2] + on1 * draw.world[6] + on2 * draw.world[10]; } else { xverts[i].nx = 0.0f; xverts[i].ny = 1.0f; xverts[i].nz = 0.0f; } @@ -750,11 +819,6 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw } std::size_t num_tris = draw.indices.size() / 3; - for (std::size_t t = 0; t < num_tris; ++t) { - uint32_t i0 = draw.indices[t * 3 + 0]; - uint32_t i1 = draw.indices[t * 3 + 1]; - uint32_t i2 = draw.indices[t * 3 + 2]; - if (i0 >= num_verts || i1 >= num_verts || i2 >= num_verts) continue; auto make_screen_vertex = [&](TransformedVertex& v) { if (v.w_clip > 1e-5f) { @@ -865,7 +929,6 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw if (nlen > 1e-5f) { nx /= nlen; ny /= nlen; nz /= nlen; } float ndotl = std::max(0.0f, nx * lx + ny * ly + nz * lz); - float light_intensity = 0.52f + 0.58f * ndotl; float pr = 255.0f, pg = 255.0f, pb = 255.0f; float frag_alpha = 255.0f; @@ -897,9 +960,13 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw float vb = (b0 * (d0 & 0xFF) + b1 * (d1 & 0xFF) + b2 * (d2 & 0xFF)) / 255.0f; float va = (b0 * ((d0 >> 24) & 0xFF) + b1 * ((d1 >> 24) & 0xFF) + b2 * ((d2 >> 24) & 0xFF)) / 255.0f; if (draw.lighting) { - pr = std::clamp(pr * vr * 1.4f, 0.0f, 255.0f); - pg = std::clamp(pg * vg * 1.4f, 0.0f, 255.0f); - pb = std::clamp(pb * vb * 1.4f, 0.0f, 255.0f); + // D3D8 fixed-function: Emissive + MatAmb*LightAmb + Diffuse*LightDiff*N.L. + float lr = std::clamp(draw.material_emissive[0] + draw.material_ambient[0] * draw.light_ambient[0] + vr * draw.light_diffuse[0] * ndotl, 0.0f, 1.0f); + float lg = std::clamp(draw.material_emissive[1] + draw.material_ambient[1] * draw.light_ambient[1] + vg * draw.light_diffuse[1] * ndotl, 0.0f, 1.0f); + float lb = std::clamp(draw.material_emissive[2] + draw.material_ambient[2] * draw.light_ambient[2] + vb * draw.light_diffuse[2] * ndotl, 0.0f, 1.0f); + pr = std::clamp(pr * lr, 0.0f, 255.0f); + pg = std::clamp(pg * lg, 0.0f, 255.0f); + pb = std::clamp(pb * lb, 0.0f, 255.0f); } else { pr = std::clamp(pr * vr, 0.0f, 255.0f); pg = std::clamp(pg * vg, 0.0f, 255.0f); @@ -913,12 +980,11 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw pg = b0 * ((d0 >> 8) & 0xFF) + b1 * ((d1 >> 8) & 0xFF) + b2 * ((d2 >> 8) & 0xFF); pb = b0 * (d0 & 0xFF) + b1 * (d1 & 0xFF) + b2 * (d2 & 0xFF); frag_alpha = b0 * ((d0 >> 24) & 0xFF) + b1 * ((d1 >> 24) & 0xFF) + b2 * ((d2 >> 24) & 0xFF); - } - - if (draw.lighting) { - pr = std::clamp(pr * light_intensity, 0.0f, 255.0f); - pg = std::clamp(pg * light_intensity, 0.0f, 255.0f); - pb = std::clamp(pb * light_intensity, 0.0f, 255.0f); + if (draw.lighting) { + pr = 255.0f * std::clamp(draw.material_emissive[0] + draw.material_ambient[0] * draw.light_ambient[0] + pr / 255.0f * draw.light_diffuse[0] * ndotl, 0.0f, 1.0f); + pg = 255.0f * std::clamp(draw.material_emissive[1] + draw.material_ambient[1] * draw.light_ambient[1] + pg / 255.0f * draw.light_diffuse[1] * ndotl, 0.0f, 1.0f); + pb = 255.0f * std::clamp(draw.material_emissive[2] + draw.material_ambient[2] * draw.light_ambient[2] + pb / 255.0f * draw.light_diffuse[2] * ndotl, 0.0f, 1.0f); + } } if (m_fog_enabled && draw.fog) { @@ -1012,7 +1078,6 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw rasterize_triangle(*vin2, vnew2, vnew1); } } - } } void Gr2SceneRenderer::RenderScene(SDL_Surface* targetSurface, const std::vector& draws) { @@ -1199,15 +1264,20 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector< va *= ((d >> 24) & 0xFF) / 255.0f; } + // D3D8 fixed-function vertex lighting with one directional light (D3DRS_AMBIENT 0): + // Emissive + Material.Ambient*Light.Ambient + Diffuse*Light.Diffuse*max(0, N.L), clamped. + // Normals go through the world matrix like D3DTS_WORLD does for lit vertices. if (draw.lighting && i * 3 + 2 < draw.normals.size()) { - float nx = draw.normals[i * 3 + 0]; - float ny = draw.normals[i * 3 + 1]; - float nz = draw.normals[i * 3 + 2]; + float on[3] = {draw.normals[i * 3 + 0], draw.normals[i * 3 + 1], draw.normals[i * 3 + 2]}; + float nx = on[0] * draw.world[0] + on[1] * draw.world[4] + on[2] * draw.world[8]; + float ny = on[0] * draw.world[1] + on[1] * draw.world[5] + on[2] * draw.world[9]; + float nz = on[0] * draw.world[2] + on[1] * draw.world[6] + on[2] * draw.world[10]; + float nlen = std::sqrt(nx * nx + ny * ny + nz * nz); + if (nlen > 1e-5f) { nx /= nlen; ny /= nlen; nz /= nlen; } float ndotl = std::max(0.0f, nx * lx + ny * ly + nz * lz); - float light_intensity = 0.52f + 0.58f * ndotl; - vr = std::clamp(vr * light_intensity, 0.0f, 1.0f); - vg = std::clamp(vg * light_intensity, 0.0f, 1.0f); - vb = std::clamp(vb * light_intensity, 0.0f, 1.0f); + vr = std::clamp(draw.material_emissive[0] + draw.material_ambient[0] * draw.light_ambient[0] + vr * draw.light_diffuse[0] * ndotl, 0.0f, 1.0f); + vg = std::clamp(draw.material_emissive[1] + draw.material_ambient[1] * draw.light_ambient[1] + vg * draw.light_diffuse[1] * ndotl, 0.0f, 1.0f); + vb = std::clamp(draw.material_emissive[2] + draw.material_ambient[2] * draw.light_ambient[2] + vb * draw.light_diffuse[2] * ndotl, 0.0f, 1.0f); } if (m_fog_enabled && draw.fog && clip[3] > 0.0f) { diff --git a/src/eter_render/Gr2ModelRenderer.h b/src/eter_render/Gr2ModelRenderer.h index 25503766..02af4e58 100644 --- a/src/eter_render/Gr2ModelRenderer.h +++ b/src/eter_render/Gr2ModelRenderer.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -22,6 +23,16 @@ public: void AttachModel(const std::string& bone_name, std::shared_ptr attachment, const float* offset_matrix = nullptr); void AttachPart(std::shared_ptr part); void DetachAll(); + void DetachModel(const std::string& bone_name); + void DetachPart(const std::shared_ptr& part); + // CActorInstance::AttachSash: the attached instance plays its own motion 0 on the parent's clock. + void SetAttachmentAnimated(const std::string& bone_name, bool animated); + // ENABLE_OBJ_SCALLING: the attachment is scaled about the parent origin in Granny (Z-up) space. + void SetAttachmentScale(const std::string& bone_name, float sx, float sy, float sz); + // CGrannyModelInstance::SetMaterialImagePointer: textures whose StringPath matches src are drawn with dst. + void SetSkin(const std::string& src_file_name, const std::string& dst_file_name); + void ClearSkins() { m_skins.clear(); } + const std::string& GetFilePath() const { return m_filepath; } // Build 3D draw commands for this model and all attached components (weapons, hair, armor parts) std::vector BuildDrawCommands(float animation_time = -1.0f, const float* world_matrix = nullptr); @@ -41,7 +52,11 @@ private: std::string bone_name; std::shared_ptr model; float offset[16]; + bool animated = false; + bool scaled = false; + float scale[3] = {1.0f, 1.0f, 1.0f}; }; + void ApplySkins(std::vector& draws, size_t first) const; std::unique_ptr m_file; std::string m_filepath; @@ -50,6 +65,7 @@ private: std::vector m_attached_models; std::vector> m_attached_parts; + std::unordered_map m_skins; }; // 3D Scene and Model Renderer (modeled after 40250 pipeline architecture) @@ -61,6 +77,11 @@ public: void SetCameraLookAt(float eyeX, float eyeY, float eyeZ, float targetX, float targetY, float targetZ, float upX, float upY, float upZ); + // D3DXMatrixLookAtRH as used by the original CCamera::SetViewMatrix, expressed for this + // renderer's LH projection: LookAtLH with the x axis negated (RH view x RH proj == this view x LH proj). + void SetCameraLookAtRH(float eyeX, float eyeY, float eyeZ, + float targetX, float targetY, float targetZ, + float upX, float upY, float upZ); void SetPerspective(float fovYDegrees, float aspect, float zNear, float zFar); diff --git a/src/eter_render/RaceData.cpp b/src/eter_render/RaceData.cpp new file mode 100644 index 00000000..64cf70af --- /dev/null +++ b/src/eter_render/RaceData.cpp @@ -0,0 +1,455 @@ +#include "RaceData.h" +#include "src/ava2_text_file.h" +#include "src/ava2_text_file_loader.h" +#include "src/eter_resource/ResourceManager.h" +#include +#include +#include +#include +#include +#include + +namespace ava2 { + +namespace { +void TraceError(const std::string& text) { std::cerr << "[AVA2 TraceError] " << text << std::endl; } + +// CFileNameHelper::StringPath: lower case + '\\' -> '/'. ChangeDosPath goes the other way, but the +// skin match (CGrannyMaterial::IsIn) compares StringPath forms, so the skin key is kept in that form. +std::string StringPath(std::string path) { + for (auto& c : path) { + if (c == '\\') c = '/'; + else if (static_cast(c) < 128) c = static_cast(std::tolower(static_cast(c))); + } + return path; +} + +bool IsGuildRace(unsigned race) { return (race >= 14000 && race < 15000) || race == 20043; } +bool IsNPCRace(unsigned race) { return race > 9000; } +bool IsNewPetRace(unsigned race) { return race >= 34001 && race <= 34150; } // NEW_PET_SYSTEM +bool IsNewMountRace(unsigned race) { return race >= 32000 && race <= 32100; } +} // namespace + +bool ReadRaceResourceFile(const std::string& fileName, std::string* text) { + for (const auto& candidate : CResourceManager::GetCandidatePaths(CResourceManager::NormalizePath(fileName.c_str()))) { + std::ifstream in(candidate, std::ios::binary); + if (!in) continue; + std::ostringstream ss; ss << in.rdbuf(); + *text = ss.str(); + return true; + } + return false; +} + +std::string ReadMotionFileName(const std::string& msaFileName) { + std::string text; + if (!ReadRaceResourceFile(msaFileName, &text)) return {}; + TextFileLoader loader; + if (!loader.load(text)) return {}; + std::string motion; + if (!loader.tokenString("motionfilename", &motion)) return {}; + return motion; +} + +bool RaceData::LoadRaceData(const std::string& fileName) { + std::string text; + if (!ReadRaceResourceFile(fileName, &text)) return false; + TextFileLoader loader; + loader.load(text); + loader.setTop(); + loader.tokenString("basemodelfilename", &m_baseModelFileName); + loader.tokenString("treefilename", &m_treeFileName); + loader.tokenString("attributefilename", &m_attributeFileName); + loader.tokenString("smokebonename", &m_smokeBoneName); + loader.tokenString("motionlistfilename", &m_motionListFileName); + if (!m_treeFileName.empty()) m_treeFileName = StringPath(m_treeFileName); + if (auto* smoke = loader.tokenVector("smokefilename")) { + if (smoke->size() % 2 != 0) { + TraceError("SmokeFileName ArgCount[" + std::to_string(smoke->size()) + "]%2==0"); + return false; + } + // Smoke effects (CEffectManager::RegisterEffect2) are not ported. + } + + // The original `continue`s below skip SetParentNode(), so a ShapeDataNN without ShapeIndex (or + // without Model/Local_Model) leaves the cursor inside that child; kept as-is. + if (loader.setChildNode("shapedata")) { + std::string pathName; + int count = 0; + if (loader.tokenString("pathname", &pathName) && loader.tokenInteger("shapedatacount", &count)) { + for (unsigned i = 0; i < static_cast(count); ++i) { + if (!loader.setChildNode("shapedata", i)) continue; + loader.tokenString("specialpath", &pathName); + int shapeIndex = 0; + if (!loader.tokenInteger("shapeindex", &shapeIndex)) continue; + std::string model; + if (loader.tokenString("model", &model)) { + SetShapeModel(shapeIndex, pathName + model); + } else { + if (!loader.tokenString("local_model", &model)) continue; + SetShapeModel(shapeIndex, model); + } + std::string src, dst; + if (loader.tokenString("local_sourceskin", &src) && loader.tokenString("local_targetskin", &dst)) + AppendShapeSkin(shapeIndex, 0, src, dst); + if (loader.tokenString("sourceskin", &src) && loader.tokenString("targetskin", &dst)) + AppendShapeSkin(shapeIndex, 0, pathName + src, pathName + dst); + // ENABLE_SKIN_EXTENDED + for (unsigned n = 2; n <= 9; ++n) { + if (loader.tokenString("sourceskin" + std::to_string(n), &src) && + loader.tokenString("targetskin" + std::to_string(n), &dst)) + AppendShapeSkin(shapeIndex, 0, pathName + src, pathName + dst); + } + loader.setParent(); + } + } + loader.setParent(); + } + + if (loader.setChildNode("hairdata")) { + std::string pathName; + int count = 0; + if (loader.tokenString("pathname", &pathName) && loader.tokenInteger("hairdatacount", &count)) { + for (unsigned i = 0; i < static_cast(count); ++i) { + if (!loader.setChildNode("hairdata", i)) continue; + loader.tokenString("specialpath", &pathName); + int hairIndex = 0; + if (!loader.tokenInteger("hairindex", &hairIndex)) continue; + std::string model, src, dst; + if (loader.tokenString("model", &model) && loader.tokenString("sourceskin", &src) && + loader.tokenString("targetskin", &dst)) + SetHairSkin(hairIndex, 0, pathName + model, pathName + src, pathName + dst); + loader.setParent(); + } + } + loader.setParent(); + } + // AttachingData (collision spheres, attached effects) is not ported. + return true; +} + +void RaceData::SetShapeModel(uint32_t index, const std::string& model) { m_shapes[index].model = model; } + +void RaceData::AppendShapeSkin(uint32_t index, uint32_t, const std::string& src, const std::string& dst) { + m_shapes[index].skins.push_back({StringPath(src), dst}); +} + +void RaceData::SetHairSkin(uint32_t index, uint32_t, const std::string& model, const std::string& src, const std::string& dst) { + auto& hair = m_hairs[index]; + hair.skins.push_back({StringPath(src), dst}); + hair.model = model; +} + +const RaceData::Shape* RaceData::FindShape(uint32_t index) const { + auto it = m_shapes.find(index); + return it == m_shapes.end() ? nullptr : &it->second; +} + +const RaceData::Shape* RaceData::FindHair(uint32_t index) const { + auto it = m_hairs.find(index); + if (it == m_hairs.end()) { + if (index != 0) TraceError("Hair number " + std::to_string(index) + " is not exist."); + return nullptr; + } + return &it->second; +} + +bool RaceData::GetAttachingBoneName(uint32_t part, std::string* bone) const { + auto it = m_attachingBoneNames.find(part); + if (it == m_attachingBoneNames.end()) return false; + *bone = it->second; + return true; +} + +bool RaceData::RegisterMotion(uint16_t mode, uint16_t name, const std::string& fileName, int percent) { + auto it = m_motionModes.find(mode); + if (it == m_motionModes.end()) { + TraceError("Failed getting motion mode data!"); + return false; + } + it->second[name].push_back({fileName, percent}); + return true; +} + +const RaceData::MotionVectorMap* RaceData::GetMotionMode(uint16_t mode) const { + auto it = m_motionModes.find(mode); + return it == m_motionModes.end() ? nullptr : &it->second; +} + +const std::vector* RaceData::GetMotions(uint16_t mode, uint32_t name) const { + const MotionVectorMap* motions = GetMotionMode(mode); + if (!motions) return nullptr; + auto it = motions->find(name); + return it == motions->end() ? nullptr : &it->second; +} + +bool RaceData::GetMotionKey(uint16_t mode, uint16_t name, uint16_t* keyMode) const { + const MotionVectorMap* motions = GetMotionMode(mode); + if (!motions) return false; + if (motions->count(name)) { *keyMode = mode; return true; } + // MODE_HORSE_ONEHAND_SWORD..MODE_HORSE_BELL (10..15) fall back to MODE_HORSE (9). + const uint16_t generalMode = (mode >= 10 && mode <= 15) ? 9 : MODE_GENERAL; + const MotionVectorMap* general = GetMotionMode(generalMode); + if (!general || !general->count(name)) return false; + *keyMode = generalMode; + return true; +} + +bool RaceData::SetMotionRandomWeight(uint16_t mode, uint16_t name, uint16_t subIndex, uint8_t percent) { + auto mit = m_motionModes.find(mode); + if (mit == m_motionModes.end()) return false; + auto it = mit->second.find(name); + if (it == mit->second.end()) { + // The original prints wMotionModeIndex where it means the motion index. + TraceError("CRaceData::SetMotionRandomWeight(wMotionModeIndex=" + std::to_string(mode) + ", wMotionIndex=" + + std::to_string(name) + ", wMotionSubIndex=" + std::to_string(subIndex) + ", byPercentage=" + + std::to_string(percent) + ") - Find Motion(wMotionIndex=" + std::to_string(mode) + ") FAILED"); + return false; + } + if (subIndex >= it->second.size()) return false; + it->second[subIndex].percent = percent; + return true; +} + +bool RaceData::GetNormalAttackIndex(uint16_t mode, uint16_t* motion) const { + auto it = m_normalAttack.find(mode); + if (it == m_normalAttack.end()) return false; + *motion = uint16_t(it->second); // stored in a DWORD map, returned as WORD + return true; +} + +void RaceData::ReserveComboAttack(uint16_t mode, uint16_t comboType, uint32_t count) { + m_comboAttack.insert({(uint32_t(mode) << 16) | comboType, std::vector(count)}); +} + +void RaceData::RegisterComboAttack(uint16_t mode, uint16_t comboType, uint32_t comboIndex, uint16_t motion) { + auto it = m_comboAttack.find((uint32_t(mode) << 16) | comboType); + if (it == m_comboAttack.end()) return; + if (comboIndex >= it->second.size()) { + TraceError("CRaceData::RegisterCombo - Strange combo index!"); + return; + } + it->second[comboIndex] = motion; +} + +const std::vector* RaceData::GetComboData(uint16_t mode, uint16_t comboType) const { + auto it = m_comboAttack.find((uint32_t(mode) << 16) | comboType); + return it == m_comboAttack.end() ? nullptr : &it->second; +} + +RaceManager& RaceManager::Instance() { + static RaceManager instance; + return instance; +} + +RaceData* RaceManager::CreateRace(uint32_t race) { + if (m_races.count(race)) { + TraceError("RaceManager::CreateRace : Race " + std::to_string(race) + " already created"); + return nullptr; + } + auto data = std::make_unique(race); + RaceData* raw = data.get(); + m_races.emplace(race, std::move(data)); + return raw; +} + +RaceData* RaceManager::GetRaceDataPointer(uint32_t race) { + auto it = m_races.find(race); + if (it != m_races.end()) return it->second.get(); + RaceData* loaded = LoadRace(race); + if (!loaded) { + TraceError("CRaceManager::GetRaceDataPointer: cannot load data by dwRaceIndex " + std::to_string(race)); + return nullptr; + } + return loaded; +} + +void RaceManager::SelectRace(uint32_t race) { + auto it = m_races.find(race); + if (it == m_races.end()) return; // assert(!"Failed to select race data!") + m_selected = it->second.get(); +} + +float RaceManager::GetRaceHeight(int race) const { + auto it = m_raceHeights.find(race); + return it == m_raceHeights.end() ? 0.0f : it->second; +} + +std::string RaceManager::GetFullPathFileName(const std::string& name) const { + if (!name.empty() && name[0] == '.') return name; + return m_pathName + name; +} + +void RaceManager::Destroy() { m_races.clear(); m_selected = nullptr; } + +void RaceManager::GetRaceResourcePathes(uint32_t race, std::vector* paths) { + auto push = [paths](std::initializer_list names) { for (auto* n : names) paths->push_back(std::string("d:/ymir work/") + n + "/"); }; + if (IsGuildRace(race)) { + push({"guild", "npc", "npc2", "npc_pet", "monster", "monster2"}); + } else if (IsNPCRace(race)) { + if (race >= 30000) { + if (race == 34028 || race == 34029) push({"npc_pet", "npc2"}); + else push({"npc2", "npc_pet"}); + if (IsNewPetRace(race)) push({"npc_pet"}); + if (IsNewMountRace(race)) push({"npc_mount"}); + push({"npc", "monster", "monster2", "guild"}); + } else { + push({"npc", "npc2", "npc_pet", "monster", "monster2", "guild"}); + } + } else if (race == 8507 || race == 8510) { + push({"monster2", "monster", "npc", "npc2", "npc_pet", "guild"}); + } else if (race > 8000) { + push({"monster", "monster2", "npc", "npc2", "npc_pet", "guild"}); + } else if (race > 2000 || (race >= 1400 && race <= 1700)) { + push({"monster2", "monster", "npc", "npc2", "npc_pet", "guild"}); + } else { + push({"monster", "monster2", "npc", "npc2", "npc_pet", "guild"}); + } +} + +RaceData* RaceManager::LoadRace(uint32_t race) { + auto nameIt = m_raceNames.find(race); + if (nameIt == m_raceNames.end() || nameIt->second.empty()) return nullptr; + const std::string& raceName = nameIt->second; + + // LOAD_LOCAL_RESOURCE + if (raceName[0] == '#') { + std::string pathName = raceName.substr(1); + auto data = std::make_unique(race); + if (!data->LoadRaceData(pathName + "shape.msm")) { + TraceError("CRaceManager::RegisterRacePath(race=" + std::to_string(race) + ").LoadRaceData(" + pathName + "shape.msm)"); + return nullptr; + } + LoadRaceMotionList(*data, pathName, pathName + "motlist.txt"); + RaceData* raw = data.get(); + m_races.emplace(race, std::move(data)); + return raw; + } + + std::vector paths; + GetRaceResourcePathes(race, &paths); + auto data = std::make_unique(race); + for (size_t i = 0; i < paths.size(); ++i) { + std::string fullPath = paths[i]; + auto src = m_raceSrcNames.find(raceName); + fullPath += src == m_raceSrcNames.end() ? raceName : src->second; + fullPath += "/"; + std::string msm = fullPath + raceName + ".msm"; + if (!data->LoadRaceData(msm)) { + if (i != paths.size() - 1) continue; // Tracenf "Will Find Another Path." + TraceError("CRaceManager::RegisterRacePath : RACE[" + std::to_string(race) + "] LOAD MSMFILE[" + msm + "] ERROR"); + return nullptr; + } + LoadRaceMotionList(*data, fullPath, fullPath + data->GetMotionListFileName()); + RaceData* raw = data.get(); + m_races.emplace(race, std::move(data)); + return raw; + } + TraceError("CRaceManager::RegisterRacePath : RACE[" + std::to_string(race) + "] HAVE NO PATH ERROR"); + return nullptr; +} + +bool RaceManager::LoadRaceMotionList(RaceData& race, const std::string& pathName, const std::string& motionListFileName) { + static const std::map kTypes = { + {"SPAWN", RaceData::NAME_SPAWN}, + {"WAIT", RaceData::NAME_WAIT}, {"WAIT1", RaceData::NAME_WAIT}, {"WAIT2", RaceData::NAME_WAIT}, + {"WALK", RaceData::NAME_WALK}, {"WALK1", RaceData::NAME_WALK}, {"WALK2", RaceData::NAME_WALK}, + {"RUN", RaceData::NAME_RUN}, {"RUN1", RaceData::NAME_RUN}, {"RUN2", RaceData::NAME_RUN}, + {"STOP", RaceData::NAME_STOP}, {"DEAD", RaceData::NAME_DEAD}, + {"COMBO_ATTACK", RaceData::NAME_COMBO_ATTACK_1}, {"COMBO_ATTACK1", RaceData::NAME_COMBO_ATTACK_2}, + {"COMBO_ATTACK2", RaceData::NAME_COMBO_ATTACK_3}, + {"NORMAL_ATTACK", RaceData::NAME_NORMAL_ATTACK}, {"NORMAL_ATTACK1", RaceData::NAME_NORMAL_ATTACK}, + {"NORMAL_ATTACK2", RaceData::NAME_NORMAL_ATTACK}, + {"FRONT_DAMAGE", RaceData::NAME_DAMAGE}, {"FRONT_DAMAGE1", RaceData::NAME_DAMAGE}, + {"FRONT_DAMAGE2", RaceData::NAME_DAMAGE}, {"FRONT_DAMAGE3", RaceData::NAME_DAMAGE}, + {"FRONT_DEAD", RaceData::NAME_DEAD}, {"FRONT_DEAD1", RaceData::NAME_DEAD}, {"FRONT_DEAD2", RaceData::NAME_DEAD}, + {"FRONT_KNOCKDOWN", RaceData::NAME_DAMAGE_FLYING}, {"FRONT_KNOCKDOWN1", RaceData::NAME_DAMAGE_FLYING}, + {"FRONT_STANDUP", RaceData::NAME_STAND_UP}, {"FRONT_STANDUP1", RaceData::NAME_STAND_UP}, + {"BACK_DAMAGE", RaceData::NAME_DAMAGE_BACK}, {"BACK_DAMAGE1", RaceData::NAME_DAMAGE_BACK}, + {"BACK_DEAD", RaceData::NAME_DEAD_BACK}, {"BACK_DEAD1", RaceData::NAME_DEAD_BACK}, {"BACK_DEAD2", RaceData::NAME_DEAD_BACK}, + {"BACK_KNOCKDOWN", RaceData::NAME_DAMAGE_FLYING_BACK}, {"BACK_KNOCKDOWN1", RaceData::NAME_DAMAGE_FLYING_BACK}, + {"BACK_STANDUP", RaceData::NAME_STAND_UP_BACK}, {"BACK_STANDUP1", RaceData::NAME_STAND_UP_BACK}, + {"SPECIAL", RaceData::NAME_SPECIAL_1}, {"SPECIAL1", RaceData::NAME_SPECIAL_2}, {"SPECIAL2", RaceData::NAME_SPECIAL_3}, + {"SPECIAL3", RaceData::NAME_SPECIAL_4}, {"SPECIAL4", RaceData::NAME_SPECIAL_5}, {"SPECIAL5", RaceData::NAME_SPECIAL_6}, + {"SKILL1", RaceData::NAME_SKILL + 121}, {"SKILL2", RaceData::NAME_SKILL + 122}, {"SKILL3", RaceData::NAME_SKILL + 123}, + {"SKILL4", RaceData::NAME_SKILL + 124}, {"SKILL5", RaceData::NAME_SKILL + 125}, + }; + std::string text; + if (!ReadRaceResourceFile(motionListFileName, &text)) return false; + + // sscanf("%s %s %s %d") leaves the buffers untouched on a blank line, so such a line repeats the + // previous registration exactly like the original. + char mode[256] = "", type[256] = "", file[256] = ""; + int percent = 0; + bool isSpawn = false; + std::string spawnFile, motionFile; + for (const auto& line : ava2TextLines(text)) { + std::sscanf(line.c_str(), "%255s %255s %255s %d", mode, type, file, &percent); + auto it = kTypes.find(type); + if (it == kTypes.end()) { + // WAIT4 / WAIT20 style names fall back to the name with 1..2 trailing characters cut. + const size_t cutLimit = 2; + bool found = false; + size_t len = std::strlen(type); + if (cutLimit < len + 1) { + for (size_t i = 1; i <= cutLimit; ++i) { + it = kTypes.find(std::string(type).substr(0, len - i)); + if (it != kTypes.end()) { found = true; break; } + } + } + if (!found) continue; + } + motionFile = pathName + file; + race.RegisterMotionData(it->second, motionFile, percent); + if (it->second == RaceData::NAME_SPAWN) isSpawn = true; + else if (it->second == RaceData::NAME_DAMAGE) spawnFile = motionFile; + } + if (!isSpawn && !spawnFile.empty()) race.RegisterMotionData(RaceData::NAME_SPAWN, spawnFile, percent); + return true; +} + +bool RaceManager::LoadGameNPC(const std::string& fileName) { + std::string text; + if (!ReadRaceResourceFile(fileName, &text)) return false; + auto strip = [](std::string s) { + size_t b = s.find_first_not_of(" \t"), e = s.find_last_not_of(" \t"); + return b == std::string::npos ? std::string() : s.substr(b, e - b + 1); + }; + for (const auto& line : ava2TextLines(text)) { + auto tokens = ava2TabTokens(line, false); + if (tokens.size() < 2) continue; + uint32_t vnum = static_cast(std::strtoul(tokens[0].c_str(), nullptr, 10)); + if (vnum) RegisterRaceName(vnum, strip(tokens[1])); + else if (tokens.size() >= 3) RegisterRaceSrcName(strip(tokens[1]), strip(tokens[2])); + } + return true; +} + +void RaceManager::LoadPlayerRaces() { + // CPythonPlayerSettingsModule m_vecRaceData. + static const struct { const char* msm; const char* path; } kRaces[] = { + {"warrior_m.msm", "d:/ymir work/pc/warrior/"}, {"assassin_w.msm", "d:/ymir work/pc/assassin/"}, + {"sura_m.msm", "d:/ymir work/pc/sura/"}, {"shaman_w.msm", "d:/ymir work/pc/shaman/"}, + {"warrior_w.msm", "d:/ymir work/pc2/warrior/"}, {"assassin_m.msm", "d:/ymir work/pc2/assassin/"}, + {"sura_w.msm", "d:/ymir work/pc2/sura/"}, {"shaman_m.msm", "d:/ymir work/pc2/shaman/"}, + }; + for (uint32_t i = 0; i < sizeof(kRaces) / sizeof(kRaces[0]); ++i) { + if (m_races.count(i)) continue; + RaceData* race = CreateRace(i); + if (!race) continue; + // The LoadRaceData result is ignored by CPythonPlayerSettingsModule::Load. + race->LoadRaceData(kRaces[i].msm); + // __LoadGameRace attaching bones (RaceToJob: race % 4 here). + switch (i % 4) { + case 0: race->RegisterAttachingBoneName(RaceData::PART_WEAPON, "equip_right_hand"); break; + case 1: case 3: + race->RegisterAttachingBoneName(RaceData::PART_WEAPON, "equip_right"); + race->RegisterAttachingBoneName(RaceData::PART_WEAPON_LEFT, "equip_left"); + break; + case 2: race->RegisterAttachingBoneName(RaceData::PART_WEAPON, "equip_right"); break; + } + race->RegisterAttachingBoneName(RaceData::PART_SASH, "Bip01 Spine2"); // ENABLE_SASH_SYSTEM + } +} + +} // namespace ava2 diff --git a/src/eter_render/RaceData.h b/src/eter_render/RaceData.h new file mode 100644 index 00000000..a54c27c1 --- /dev/null +++ b/src/eter_render/RaceData.h @@ -0,0 +1,135 @@ +#pragma once +// Port of AVA2 GameLib CRaceData (RaceData.h/.cpp, RaceDataFile.cpp LoadRaceData) and CRaceManager +// (RaceManager.cpp): .msm shape/hair tables, attaching bone names, the npclist race-name registry, +// the per-race resource path search and the motlist.txt GENERAL motion list. +// Not ported: smoke effects, AttachingData (collision spheres / attached effects), the CRaceMotionData +// .msa event payload (only MotionFileName is read), motion modes other than GENERAL. +#include +#include +#include +#include +#include + +namespace ava2 { + +class RaceData { +public: + enum EParts { PART_MAIN, PART_WEAPON, PART_HEAD, PART_WEAPON_LEFT, PART_HAIR, PART_SASH, PART_ARROW_TYPE, PART_MAX_NUM }; + // CRaceMotionData::EName (GENERAL mode indices). + enum EMotion { + NAME_NONE, NAME_WAIT, NAME_WALK, NAME_RUN, NAME_CHANGE_WEAPON, NAME_DAMAGE, NAME_DAMAGE_FLYING, NAME_STAND_UP, + NAME_DAMAGE_BACK, NAME_DAMAGE_FLYING_BACK, NAME_STAND_UP_BACK, NAME_DEAD, NAME_DEAD_BACK, NAME_NORMAL_ATTACK, + NAME_COMBO_ATTACK_1, NAME_COMBO_ATTACK_2, NAME_COMBO_ATTACK_3, NAME_COMBO_ATTACK_4, NAME_COMBO_ATTACK_5, + NAME_COMBO_ATTACK_6, NAME_COMBO_ATTACK_7, NAME_COMBO_ATTACK_8, NAME_INTRO_WAIT, NAME_INTRO_SELECTED, + NAME_INTRO_NOT_SELECTED, NAME_SPAWN, NAME_FISHING_THROW, NAME_FISHING_WAIT, NAME_FISHING_STOP, + NAME_FISHING_REACT, NAME_FISHING_CATCH, NAME_FISHING_FAIL, NAME_STOP, NAME_SPECIAL_1, NAME_SPECIAL_2, + NAME_SPECIAL_3, NAME_SPECIAL_4, NAME_SPECIAL_5, NAME_SPECIAL_6, NAME_SKILL = 50, + }; + struct Skin { std::string srcFileName, dstFileName; }; + struct Shape { std::string model; std::vector skins; }; + struct Motion { std::string fileName; int percent = 0; }; + + explicit RaceData(uint32_t race = 0) : m_race(race) {} + // RaceDataFile.cpp LoadRaceData. + bool LoadRaceData(const std::string& fileName); + + uint32_t GetRace() const { return m_race; } + void SetShapeModel(uint32_t index, const std::string& model); + void AppendShapeSkin(uint32_t index, uint32_t level, const std::string& src, const std::string& dst); + void SetHairSkin(uint32_t index, uint32_t level, const std::string& model, const std::string& src, const std::string& dst); + const Shape* FindShape(uint32_t index) const; + const Shape* FindHair(uint32_t index) const; + + void RegisterAttachingBoneName(uint32_t part, const std::string& bone) { m_attachingBoneNames.insert({part, bone}); } + bool GetAttachingBoneName(uint32_t part, std::string* bone) const; + + const std::string& GetBaseModelFileName() const { return m_baseModelFileName; } + const std::string& GetTreeFileName() const { return m_treeFileName; } + bool IsTree() const { return !m_treeFileName.empty(); } + const std::string& GetMotionListFileName() const { return m_motionListFileName; } + + enum { MODE_GENERAL = 1 }; // CRaceMotionData::MODE_GENERAL + typedef std::map> MotionVectorMap; + // CRaceData::RegisterMotionMode: std::map insert, so a second registration keeps the first mode. + void RegisterMotionMode(uint16_t mode) { m_motionModes.insert({mode, MotionVectorMap()}); } + bool HasMotionMode(uint16_t mode) const { return m_motionModes.count(mode) != 0; } + // CRaceData::NEW_RegisterMotion: appended to the mode's motion vector; false ("Failed getting motion + // mode data!") when the mode was never registered. The .msa path is stored, the gr2 is resolved on use. + bool RegisterMotion(uint16_t mode, uint16_t name, const std::string& fileName, int percent); + // __LoadRaceMotionList path: RegisterMotionMode(MODE_GENERAL) + RegisterMotionData(MODE_GENERAL, ...). + void RegisterMotionData(uint32_t name, const std::string& fileName, int percent) { + RegisterMotionMode(MODE_GENERAL); + RegisterMotion(MODE_GENERAL, uint16_t(name), fileName, percent); + } + const std::vector* GetMotions(uint32_t name) const { return GetMotions(MODE_GENERAL, name); } + const std::vector* GetMotions(uint16_t mode, uint32_t name) const; + const MotionVectorMap* GetMotionMode(uint16_t mode) const; + // CRaceData::GetMotionKey: the motion in the given mode, else in MODE_HORSE (horse weapon modes) + // or MODE_GENERAL; *keyMode receives the mode of MAKE_MOTION_KEY. + bool GetMotionKey(uint16_t mode, uint16_t name, uint16_t* keyMode) const; + bool SetMotionRandomWeight(uint16_t mode, uint16_t name, uint16_t subIndex, uint8_t percent); + + // Normal attack / combo tables (CRaceData m_NormalAttackIndexMap / m_ComboAttackDataMap). + void RegisterNormalAttack(uint16_t mode, uint16_t motion) { m_normalAttack.insert({mode, motion}); } + bool GetNormalAttackIndex(uint16_t mode, uint16_t* motion) const; + void ReserveComboAttack(uint16_t mode, uint16_t comboType, uint32_t count); + void RegisterComboAttack(uint16_t mode, uint16_t comboType, uint32_t comboIndex, uint16_t motion); + const std::vector* GetComboData(uint16_t mode, uint16_t comboType) const; + +private: + uint32_t m_race = 0; + std::string m_baseModelFileName, m_treeFileName, m_attributeFileName, m_smokeBoneName; + std::string m_motionListFileName = "motlist.txt"; + std::map m_shapes, m_hairs; + std::map m_attachingBoneNames; + std::map m_motionModes; + std::map m_normalAttack; + std::map> m_comboAttack; // key MAKE_COMBO_KEY(mode, type) = mode<<16 | type +}; + +class RaceManager { +public: + static RaceManager& Instance(); + + // CRaceManager::RegisterRaceName / RegisterRaceSrcName (std::map insert: the first registration wins). + void RegisterRaceName(uint32_t race, const std::string& name) { m_raceNames.insert({race, name}); } + void RegisterRaceSrcName(const std::string& name, const std::string& srcName) { m_raceSrcNames.insert({name, srcName}); } + // CRaceManager::CreateRace: PC races built by CPythonPlayerSettingsModule. + RaceData* CreateRace(uint32_t race); + // CRaceManager::GetRaceDataPointer: loads unknown races from the registered name; failures are not cached. + RaceData* GetRaceDataPointer(uint32_t race); + // CRaceManager::SelectRace: an uncreated race leaves the previous selection (assert only). + void SelectRace(uint32_t race); + RaceData* GetSelectedRaceDataPointer() const { return m_selected; } + // RACE_HEIGHT: std::map insert, the first height of a race wins; 0 when unset. + void SetRaceHeight(int race, float height) { m_raceHeights.insert({race, height}); } + float GetRaceHeight(int race) const; + void SetPathName(const std::string& path) { m_pathName = path; } + std::string GetFullPathFileName(const std::string& name) const; + void Destroy(); + + // CPythonPlayerSettingsModule __LoadGameNPC("npclist.txt") (closed resource.dll lib; classic + // vnum/name and 0/name/srcName rows). + bool LoadGameNPC(const std::string& fileName); + // CPythonPlayerSettingsModule::Load race table: CreateRace + LoadRaceData + __LoadGameRace bones. + void LoadPlayerRaces(); + + static void GetRaceResourcePathes(uint32_t race, std::vector* paths); + static bool LoadRaceMotionList(RaceData& race, const std::string& pathName, const std::string& motionListFileName); + +private: + RaceData* LoadRace(uint32_t race); + std::map> m_races; + std::map m_raceNames; + std::map m_raceSrcNames; + std::string m_pathName; + RaceData* m_selected = nullptr; + std::map m_raceHeights; +}; + +// Reads a pack file through the CResourceManager candidate paths (d:/ymir work prefix stripping). +bool ReadRaceResourceFile(const std::string& fileName, std::string* text); +// .msa "MotionFileName" (CRaceMotionData::LoadMotionData); returns the gr2 path or "" on failure. +std::string ReadMotionFileName(const std::string& msaFileName); + +} // namespace ava2 diff --git a/src/eter_render/TerrainHeightmap.cpp b/src/eter_render/TerrainHeightmap.cpp index c6804d48..0ac2b96e 100644 --- a/src/eter_render/TerrainHeightmap.cpp +++ b/src/eter_render/TerrainHeightmap.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include namespace ava2 { @@ -221,7 +222,13 @@ bool TerrainHeightmap::LoadTextureSet(const std::string& textureset_path) { std::cerr << "TerrainHeightmap::LoadTextureSet failed to open: " << textureset_path << std::endl; return false; } + std::stringstream buffer; + buffer << file.rdbuf(); + return LoadTextureSetFromString(buffer.str()); +} +bool TerrainHeightmap::LoadTextureSetFromString(const std::string& content) { + std::istringstream file(content); std::string line; int current_id = 0; bool in_texture = false; @@ -299,10 +306,19 @@ void TerrainHeightmap::GenerateProcedural(int width, int height, float cell_scal void TerrainHeightmap::UpdateBounds() { float total_w = static_cast(m_width - 1) * m_cell_scale; float total_h = static_cast(m_height - 1) * m_cell_scale; - m_world_min_x = -total_w * 0.5f; - m_world_max_x = total_w * 0.5f; - m_world_min_z = -total_h * 0.5f; - m_world_max_z = total_h * 0.5f; + m_world_min_x = m_has_origin ? m_origin_x : -total_w * 0.5f; + m_world_max_x = m_world_min_x + total_w; + m_world_min_z = m_has_origin ? m_origin_z : -total_h * 0.5f; + m_world_max_z = m_world_min_z + total_h; +} + +void TerrainHeightmap::SetWorldOrigin(float min_x, float min_z) { + m_has_origin = true; + m_origin_x = min_x; + m_origin_z = min_z; + if (m_heights.empty()) return; + UpdateBounds(); + BuildPatchesAndQuadtree(); } void TerrainHeightmap::CalculateNormals() { @@ -667,11 +683,8 @@ Render3DDraw TerrainHeightmap::BuildPatchDraw(int patch_x, int patch_y, int step draw.uv0.push_back(u); draw.uv0.push_back(v); - float lx = 0.577f, ly = 0.577f, lz = 0.577f; - float dot = std::max(0.25f, nx * lx + ny * ly + nz * lz); - uint8_t c = static_cast(std::clamp(dot * 255.0f, 0.0f, 255.0f)); - uint32_t color = (0xFF << 24) | (c << 16) | (c << 8) | c; - draw.diffuse.push_back(color); + // CTerrain vertices carry no baked shade; the D3D light on the terrain material does it. + draw.diffuse.push_back(0xFFFFFFFFu); } } @@ -739,11 +752,8 @@ Render3DDraw TerrainHeightmap::BuildDrawCommand(const float world[16], int step) draw.uv0.push_back(u); draw.uv0.push_back(v); - float lx = 0.577f, ly = 0.577f, lz = 0.577f; - float dot = std::max(0.25f, nx * lx + ny * ly + nz * lz); - uint8_t c = static_cast(std::clamp(dot * 255.0f, 0.0f, 255.0f)); - uint32_t color = (0xFF << 24) | (c << 16) | (c << 8) | c; - draw.diffuse.push_back(color); + // CTerrain vertices carry no baked shade; the D3D light on the terrain material does it. + draw.diffuse.push_back(0xFFFFFFFFu); } } diff --git a/src/eter_render/TerrainHeightmap.h b/src/eter_render/TerrainHeightmap.h index ea19d230..96ea240c 100644 --- a/src/eter_render/TerrainHeightmap.h +++ b/src/eter_render/TerrainHeightmap.h @@ -33,6 +33,16 @@ struct TerrainQuadNode { std::unique_ptr children[4]; }; +// Height/attribute query surface shared by a single TerrainHeightmap and the +// 3x3 CMapOutdoor block set (game_scene.cpp) so actors walk on whichever is active. +class TerrainHeightSource { +public: + virtual ~TerrainHeightSource() = default; + virtual float GetHeightAtWorld(float world_x, float world_z) const = 0; + virtual bool HasAttrMap() const = 0; + virtual bool IsAttrOn(float world_x, float world_z, uint8_t flag) const = 0; +}; + /** * TerrainHeightmap: * Parses Metin2 terrain heightmap data (such as height.raw: 131x131 uint16_t), @@ -41,7 +51,7 @@ struct TerrainQuadNode { * and textureset configuration (metin2_map1.txt). * Implements 8x8 patch subdivision and QuadTree frustum culling. */ -class TerrainHeightmap { +class TerrainHeightmap : public TerrainHeightSource { public: static constexpr int RAW_XSIZE = 131; static constexpr int RAW_YSIZE = 131; @@ -62,7 +72,7 @@ public: static constexpr uint8_t ATTR_FLAG_BANPK = ATTR_BANPK; TerrainHeightmap(); - ~TerrainHeightmap() = default; + ~TerrainHeightmap() override = default; // Load from Metin2 height.raw file (131x131 uint16_t, 34322 bytes) bool LoadRaw(const std::string& raw_path, float height_scale = DEFAULT_HEIGHT_SCALE, float cell_scale = DEFAULT_CELL_SCALE); @@ -78,13 +88,14 @@ public: // Load TextureSet file (e.g. textureset/metin2_map1.txt) bool LoadTextureSet(const std::string& textureset_path); + bool LoadTextureSetFromString(const std::string& content); // Procedural terrain generation for testing void GenerateProcedural(int width = 64, int height = 64, float cell_scale = 100.0f, float hill_amplitude = 80.0f); // Query height at grid or world coordinates (continuous bilinear interpolation) float GetHeightAtGrid(int x, int y) const; - float GetHeightAtWorld(float world_x, float world_z) const; + float GetHeightAtWorld(float world_x, float world_z) const override; // Query normal at world space coordinates (normalized, Y-up) void GetNormalAtWorld(float world_x, float world_z, float out_normal[3]) const; @@ -95,10 +106,14 @@ public: std::string GetTexturePathForTile(uint8_t tile_id) const; // Query attribute flag (ATTR_BLOCK, ATTR_WATER, ATTR_BANPK) - bool HasAttrMap() const { return !m_attr.empty(); } + bool HasAttrMap() const override { return !m_attr.empty(); } uint8_t GetAttrAtGrid(int x, int y) const; uint8_t GetAttrAtWorld(float world_x, float world_z) const; - bool IsAttrOn(float world_x, float world_z, uint8_t flag) const; + bool IsAttrOn(float world_x, float world_z, uint8_t flag) const override; + + // CTerrain block placement: raw index 0 sits one cell before the block's pixel origin + // (coordX * TERRAIN_XSIZE - cell). Default (unset) keeps the centred layout. + void SetWorldOrigin(float min_x, float min_z); // Build single full-mesh 3D draw command Render3DDraw BuildDrawCommand(const float world[16] = nullptr, int step = 1) const; @@ -149,6 +164,10 @@ private: float m_min_height = 0.0f; float m_max_height = 0.0f; + bool m_has_origin = false; + float m_origin_x = 0.0f; + float m_origin_z = 0.0f; + std::vector m_heights; // m_width * m_height floats std::vector m_normals; // (m_width * m_height) * 3 floats diff --git a/src/eter_render/TextTailManager.h b/src/eter_render/TextTailManager.h index 3ac20c37..6a04270e 100644 --- a/src/eter_render/TextTailManager.h +++ b/src/eter_render/TextTailManager.h @@ -134,6 +134,7 @@ public: // Active renderer reference for Python bindings void SetCurrentSceneRenderer(const Gr2SceneRenderer* renderer) { m_currentSceneRenderer = renderer; } + const Gr2SceneRenderer* GetCurrentSceneRenderer() const { return m_currentSceneRenderer; } void SetCurrentRenderer(SDL_Renderer* renderer) { m_currentRenderer = renderer; } private: diff --git a/src/eter_resource/ResourceManager.h b/src/eter_resource/ResourceManager.h index 7e8fae86..b377f992 100644 --- a/src/eter_resource/ResourceManager.h +++ b/src/eter_resource/ResourceManager.h @@ -10,10 +10,12 @@ #include #include #include +#include class CResourceManager : public CSingleton { public: + static void SetResourceRoot(const std::filesystem::path& root) { s_resourceRoot=root; } CResourceManager() = default; virtual ~CResourceManager() { @@ -73,6 +75,12 @@ public: return pRes; } + static bool ResourceExists(const std::string& path) { + for(const auto& candidate:GetCandidatePaths(NormalizePath(path.c_str()))) { + std::error_code error;if(std::filesystem::is_regular_file(candidate,error))return true; + } + return false; + } static std::string NormalizePath(const char* c_szPath) { std::string path = c_szPath ? c_szPath : ""; @@ -108,6 +116,16 @@ public: candidates.push_back("ymir work/" + path); } + if(!s_resourceRoot.empty()) { + auto relative=candidates; + candidates.clear(); + for(const auto& candidate:relative) { + std::filesystem::path rel(candidate); + if(!rel.is_absolute()&&candidate.find(':')==std::string::npos) candidates.push_back((s_resourceRoot/rel).string()); + } + candidates.insert(candidates.end(),relative.begin(),relative.end()); + } + // Handle legacy CP949/Latin-1 raw bytes in filenames by generating UTF-8 candidates size_t initial_size = candidates.size(); for (size_t i = 0; i < initial_size; ++i) @@ -151,7 +169,7 @@ private: for (const auto& c : candidates) { auto* img = new CGraphicImage(path); - if (img->LoadFile(c.c_str())) + if (img->LoadFile(c.c_str(),path)) { return img; } @@ -230,5 +248,6 @@ private: return subImg; } + inline static std::filesystem::path s_resourceRoot; std::unordered_map m_resourceMap; }; diff --git a/src/eter_ui/PythonWindow.cpp b/src/eter_ui/PythonWindow.cpp index 76424057..bc975ed8 100644 --- a/src/eter_ui/PythonWindow.cpp +++ b/src/eter_ui/PythonWindow.cpp @@ -481,8 +481,50 @@ namespace UI return ret ? TRUE : FALSE; } - BOOL CWindow::OnMouseMiddleButtonDown() { return FALSE; } - BOOL CWindow::OnMouseMiddleButtonUp() { return FALSE; } + // EterPythonLib/PythonWindow.cpp CWindow::OnMouseMiddleButtonDown/Up, RunMouseWheelEvent, + // OnMouseWheel/OnMouseWheelScroll (ENABLE_MOUSEWHEEL_EVENT is on in AVA2 Locale_inc.h). + BOOL CWindow::OnMouseMiddleButtonDown() + { + if (!m_poHandler) return FALSE; + long ret = 0; + if (PyCallClassMemberFunc(m_poHandler, "OnMouseMiddleButtonDown", BuildEmptyTuple(), &ret) && ret) + return TRUE; + return FALSE; + } + + BOOL CWindow::OnMouseMiddleButtonUp() + { + if (!m_poHandler) return FALSE; + long ret = 0; + if (PyCallClassMemberFunc(m_poHandler, "OnMouseMiddleButtonUp", BuildEmptyTuple(), &ret) && ret) + return TRUE; + return FALSE; + } + + BOOL CWindow::RunMouseWheelEvent(long nLen) + { + if (!m_poHandler) return FALSE; + long ret = 0; + if (PyCallClassMemberFunc(m_poHandler, "OnRunMouseWheel", Py_BuildValue("(l)", nLen), &ret)) + return ret ? TRUE : FALSE; + return FALSE; + } + + BOOL CWindow::OnMouseWheel(int nLen) + { + if (!m_poHandler) return FALSE; + long ret = 0; + if (PyCallClassMemberFunc(m_poHandler, "OnMouseWheel", Py_BuildValue("(i)", nLen), &ret) && ret) + return TRUE; + return FALSE; + } + + BOOL CWindow::OnMouseWheelScroll(short wDelta) + { + if (m_poHandler) + PyCallClassMemberFunc(m_poHandler, "OnMouseWheelScroll", Py_BuildValue("(s)", wDelta > 0 ? "UP" : "DOWN")); + return m_bIsScrollable ? TRUE : FALSE; + } BOOL CWindow::OnKeyDown(int ikey) { diff --git a/src/eter_ui/PythonWindow.h b/src/eter_ui/PythonWindow.h index 7b1f391e..d8db8b3b 100644 --- a/src/eter_ui/PythonWindow.h +++ b/src/eter_ui/PythonWindow.h @@ -32,7 +32,19 @@ namespace UI void SetText(const char* text) { if (text) m_text = text; } const char* GetText() const { return m_text.c_str(); } void SetValue(const char* text) { SetText(text); } + void SetValueString(const std::string& text) { m_text = text; } void SetHorizonalAlign(int align) { m_hAlign = align; } + int GetHorizontalAlign() const { return m_hAlign; } + // EterLib CGraphicTextInstance::SetColor(r, g, b): alpha 1. + void SetColor(float r, float g, float b) { + auto c = [](float v) { return DWORD(std::clamp(v, 0.0f, 1.0f) * 255.0f + 0.5f); }; + m_color = 0xff000000 | (c(r) << 16) | (c(g) << 8) | c(b); + } + // EterLib CGraphicTextInstance::SetColor(const D3DXCOLOR&) / SetColor(DWORD): alpha kept. + void SetColor(const D3DXCOLOR& color) { m_color = DWORD(color); } + DWORD GetColor() const { return m_color; } + // EterLib CGraphicTextInstance::Destroy: back to an empty, left-aligned instance. + void Destroy() { *this = CGraphicTextInstance(); } void SetVerticalAlign(int align) { m_vAlign = align; } void SetMax(int max) { m_max = max; } void SetFontName(const char* name) { if (name) m_font = name; } @@ -57,6 +69,8 @@ namespace UI D3DXVECTOR2 GetPosition() const { return m_v2Position; } void Update() {} void Render(); + // Render(RECT* pClipRect): the clip rectangle is not applied by this text stand-in. + void Render(const RECT*) { Render(); } static const char* Hyperlink_GetText(const std::string&, int, int*) { return ""; } private: D3DXVECTOR2 m_v2Position = D3DXVECTOR2(0.0f, 0.0f); @@ -213,10 +227,10 @@ namespace UI virtual BOOL OnMouseRightButtonDoubleClick(); virtual BOOL OnMouseMiddleButtonDown(); virtual BOOL OnMouseMiddleButtonUp(); - virtual BOOL OnMouseWheelScroll(short wDelta) { return FALSE; } + virtual BOOL OnMouseWheelScroll(short wDelta); virtual void SetScrollable() { m_bIsScrollable = true; } - virtual BOOL OnMouseWheel(int nLen) { return FALSE; } - virtual BOOL RunMouseWheelEvent(long nLen) { return FALSE; } + virtual BOOL OnMouseWheel(int nLen); + virtual BOOL RunMouseWheelEvent(long nLen); virtual BOOL OnKeyDown(int ikey); virtual BOOL OnKeyUp(int ikey); diff --git a/src/eter_ui/PythonWindowManager.cpp b/src/eter_ui/PythonWindowManager.cpp index e6ad4753..7e4dc952 100644 --- a/src/eter_ui/PythonWindowManager.cpp +++ b/src/eter_ui/PythonWindowManager.cpp @@ -412,16 +412,74 @@ namespace UI if (m_pPointWindow) m_pPointWindow->OnMouseRightButtonDoubleClick(); } + // EterPythonLib/PythonWindowManager.cpp: the middle button captures the window it went + // down on; the wheel walks the point window's parents, then OnRunMouseWheel on it/its root. void CWindowManager::RunMouseMiddleButtonDown(long x, long y) { SetMousePosition(x, y); - if (m_pPointWindow) m_pPointWindow->OnMouseMiddleButtonDown(); + + CWindow * pWin = GetPointWindow(); + if (!pWin) + return; + + m_pMiddleCaptureWindow = pWin; + + pWin->OnMouseMiddleButtonDown(); } void CWindowManager::RunMouseMiddleButtonUp(long x, long y) { SetMousePosition(x, y); - if (m_pPointWindow) m_pPointWindow->OnMouseMiddleButtonUp(); + + if (m_pMiddleCaptureWindow) + { + if (m_pMiddleCaptureWindow->OnMouseMiddleButtonUp()) + { + m_pMiddleCaptureWindow = nullptr; + return; + } + } + + CWindow * pWin = GetPointWindow(); + if (!pWin) + return; + + pWin->OnMouseMiddleButtonUp(); + m_pMiddleCaptureWindow = nullptr; + } + + bool CWindowManager::RunMouseWheelScroll(long x, long y, short wDelta) + { + SetMousePosition(x, y); + CWindow * pWin = GetPointWindow(); + if (!pWin) + return false; + + return pWin->OnMouseWheelScroll(wDelta) == TRUE; + } + + bool CWindowManager::RunMouseWheelEvent(long nLen) + { + CWindow * pWin = GetPointWindow(); + while (pWin) + { + if (pWin->OnMouseWheel(nLen)) + return true; + pWin = pWin->GetParent(); + } + + pWin = GetPointWindow(); + if (pWin) + { + if (pWin->IsRendering() || pWin->IsShow()) + { + if (pWin->RunMouseWheelEvent(nLen)) + return true; + else if (pWin->GetRoot()->RunMouseWheelEvent(nLen)) + return true; + } + } + return false; } void CWindowManager::RunKeyDown(int vkey) diff --git a/src/eter_ui/PythonWindowManager.h b/src/eter_ui/PythonWindowManager.h index eb25de35..635d9011 100644 --- a/src/eter_ui/PythonWindowManager.h +++ b/src/eter_ui/PythonWindowManager.h @@ -116,6 +116,8 @@ namespace UI void RunMouseRightButtonDoubleClick(long x, long y); void RunMouseMiddleButtonDown(long x, long y); void RunMouseMiddleButtonUp(long x, long y); + bool RunMouseWheelScroll(long x, long y, short wDelta); + bool RunMouseWheelEvent(long nLen); void RunKeyDown(int vkey); void RunKeyUp(int vkey); diff --git a/src/game_type.cpp b/src/game_type.cpp new file mode 100644 index 00000000..6e9031ba --- /dev/null +++ b/src/game_type.cpp @@ -0,0 +1,74 @@ +// Provenance: AVA2 UserInterface/GameType.cpp (c_aSlotTypeToInvenType, aApplyInfo). The tables are +// the numeric values the Windows build compiles to (EWindows / EPointTypes from GameType.h and +// Packet.h under the Locale_inc.h defines listed in game_type.h). +#include "game_type.h" + +namespace ava2 { +namespace { + +enum +{ + SLOT_TYPE_MAX = 19, + MAX_APPLY_NUM = 150, // CItemData::MAX_APPLY_NUM + POINT_NONE = 0, +}; + +const uint8_t c_aSlotTypeToInvenType[SLOT_TYPE_MAX] = +{ + 0, // SLOT_TYPE_NONE RESERVED_WINDOW + 1, // SLOT_TYPE_INVENTORY INVENTORY + 0, // SLOT_TYPE_SKILL + 0, // SLOT_TYPE_EMOTION + 0, // SLOT_TYPE_SHOP + 0, // SLOT_TYPE_EXCHANGE_OWNER + 0, // SLOT_TYPE_EXCHANGE_TARGET + 0, // SLOT_TYPE_QUICK_SLOT + 0, // SLOT_TYPE_SAFEBOX (hard-coded legacy path) + 0, // SLOT_TYPE_PRIVATE_SHOP + 0, // SLOT_TYPE_MALL (hard-coded legacy path) + 5, // SLOT_TYPE_DRAGON_SOUL_INVENTORY DRAGON_SOUL_INVENTORY + 6, // SLOT_TYPE_UPGRADE_INVENTORY UPGRADE_INVENTORY + 7, // SLOT_TYPE_BOOK_INVENTORY BOOK_INVENTORY + 8, // SLOT_TYPE_STONE_INVENTORY STONE_INVENTORY + 9, // SLOT_TYPE_CHANGE_INVENTORY CHANGE_INVENTORY + 10, // SLOT_TYPE_COSTUME_INVENTORY COSTUME_INVENTORY + 11, // SLOT_TYPE_SWITCHBOT SWITCHBOT + 12, // SLOT_TYPE_CHANGE_EQUIP CHANGE_EQUIP +}; + +// aApplyInfo[].bPointType, APPLY_NONE.. in order; the entries past the initializer list are 0. +const uint8_t aApplyInfo[MAX_APPLY_NUM] = +{ + 0, 6, 8, 13, 15, 12, 14, 17, 19, 21, 32, 33, 37, 38, 39, 40, + 41, 43, 44, 45, 46, 47, 48, 63, 64, 65, 66, 67, 68, 69, 70, 71, + 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, + 88, 89, 90, 0, 34, 95, 96, 97, 98, 42, 10, 54, 55, 56, 57, 53, + 93, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 59, 60, + 61, 62, 128, 20, 176, 50, 51, 177, 178, 179, 40, 41, 0, 0, 0, 0, + 0, 0, 0, 220, 176, 50, 51, 177, 178, 179, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 207, 208, 209, 210, 182, 183, 184, 185, 186, + 187, 188, 189, 190, 191, 192, 193, 194, 52, 49, 0, 196, 197, 0, 0, 0, + 0, 0, 0, 0, 0, 0, +}; + +} // namespace + +uint8_t SlotTypeToInvenType(uint8_t bSlotType) +{ + if (bSlotType >= SLOT_TYPE_MAX) + return 0; // RESERVED_WINDOW + else + return c_aSlotTypeToInvenType[bSlotType]; +} + +uint8_t ApplyTypeToPointType(uint8_t bApplyType) +{ + // Windows reads aApplyInfo[176..179] past the 150-entry table (whatever .rdata follows it); + // those apply types resolve to POINT_NONE here. + if (bApplyType >= MAX_APPLY_NUM) + return POINT_NONE; + else + return aApplyInfo[bApplyType]; +} + +} // namespace ava2 diff --git a/src/game_type.h b/src/game_type.h new file mode 100644 index 00000000..8e0f1018 --- /dev/null +++ b/src/game_type.h @@ -0,0 +1,15 @@ +#pragma once +// Lookups from AVA2 UserInterface/GameType.cpp (Locale_inc.h defines as built: ENABLE_SPECIAL_STORAGE, +// ENABLE_SWITCHBOT, CHANGE_EQUIP_WORLDARD, ENABLE_NEW_BONUS_WORLDARD, ELEMENT_NEW_BONUSES, +// ENABLE_CONQUEROR_LEVEL, NEW_BONUS on; ENABLE_WOLFMAN_CHARACTER, ENABLE_ACCE_COSTUME_SYSTEM, +// ENABLE_MAGIC_REDUCTION_SYSTEM off). +#include + +namespace ava2 { + +// ESlotType -> EWindows; RESERVED_WINDOW (0) past SLOT_TYPE_MAX. +uint8_t SlotTypeToInvenType(uint8_t bSlotType); +// EApplyTypes -> EPointTypes; POINT_NONE (0) past CItemData::MAX_APPLY_NUM. +uint8_t ApplyTypeToPointType(uint8_t bApplyType); + +} // namespace ava2 diff --git a/src/guild_state.h b/src/guild_state.h new file mode 100644 index 00000000..41bc9761 --- /dev/null +++ b/src/guild_state.h @@ -0,0 +1,32 @@ +#pragma once +// State semantics ported from AVA2 UserInterface/PythonGuild.cpp. +#include +#include +#include +#include +#include +namespace ava2 { +struct GuildState { + struct Member { uint32_t pid;std::string name;uint8_t grade,job,level,general;uint32_t offer; }; + struct Grade { uint8_t authority;std::string name; }; + struct Comment { uint32_t id;std::string name,text; }; + struct Info { uint32_t id=0,master=0,level=0,exp=0,count=0,maxCount=0,money=0;std::string name;uint8_t hasLand=0; } info; + struct Skill { uint8_t points=0;std::array levels{};uint16_t power=0,maxPower=0; } skill; + bool enabled=false; + uint32_t levelSum=0,levelAverage=0,offerSum=0; + std::vector members; + std::vector comments; + std::map grades; + std::map names; + std::map skillSlots; + std::array enemies{}; + Member* ByPID(uint32_t pid); + Member* ByName(const std::string& name); + void RegisterMember(const Member& member); + void RemoveMember(uint32_t pid); + void StartWar(uint32_t enemy); + void EndWar(uint32_t enemy); + void Destroy(); // Windows intentionally retains comments, offer sum and slot mapping. +}; +GuildState& GetGuildState(); +} diff --git a/src/item_proto.h b/src/item_proto.h index a0cb1838..272a1abe 100644 --- a/src/item_proto.h +++ b/src/item_proto.h @@ -20,6 +20,7 @@ class ItemProto { public: std::map records; std::vector ranges; + std::vector recentRecords; const ItemProtoRecord* find(uint32_t id) const { auto exact=records.find(id);if(exact!=records.end())return &exact->second; for(auto base:ranges){auto it=records.find(base);if(it==records.end())continue;const auto& item=it->second; @@ -47,8 +48,8 @@ public: if(lzo1x_decompress_safe(packed.data(),packed.size(),raw.data(),&size,nullptr)!=LZO_E_OK||size!=real)return false; // AVA2's active ENABLE_PROTOSTRUCT_AUTODETECT leaves dwStride0 for MIPT. // TItemTableAll::Process has no case0, so every destination stays zeroed. - if(legacy){records[0]=ItemProtoRecord{};return true;} - std::map loaded;std::vector loadedRanges; + if(legacy){records[0]=ItemProtoRecord{};recentRecords.assign(count,ItemProtoRecord{});return true;} + std::map loaded;std::vector loadedRanges;std::vector ordered; for(uint32_t i=0;i(raw).subspan(size_t(i)*stride,stride);size_t shift=stride==172?0:4;ItemProtoRecord item; item.vnum=wire::read32(r,0);if(shift)item.range=wire::read32(r,4); const char* name=reinterpret_cast(r.data()+29+shift);item.name.assign(name,strnlen(name,25)); @@ -65,8 +66,9 @@ public: item.refined=wire::read32(r,163+shift);item.refineSet=uint16_t(r[167+shift])|(uint16_t(r[168+shift])<<8); item.alterToMagicPercent=r[169+shift];item.specular=r[170+shift];item.gainSocketPercent=r[171+shift]; if(item.range)loadedRanges.push_back(item.vnum); - loaded[item.vnum]=std::move(item); + ordered.push_back(item);loaded[item.vnum]=std::move(item); } + recentRecords=std::move(ordered); for(auto& [id,item]:loaded)records[id]=std::move(item); ranges.insert(ranges.end(),loadedRanges.begin(),loadedRanges.end()); return true; diff --git a/src/item_sound.cpp b/src/item_sound.cpp new file mode 100644 index 00000000..137899c6 --- /dev/null +++ b/src/item_sound.cpp @@ -0,0 +1,36 @@ +// AVA2 UserInterface/PythonItem.cpp sound selection and filename state. +#include "item_sound.h" +#include "python_gameplay_modules.h" +#include "eter_sound/SoundManager.h" +#include +namespace ava2 { +namespace { +std::array useSounds; +std::array dropSounds; +unsigned equipmentSound(int type,int subtype) { + // Shared shape: use enum starts one above drop enum. + if(type==1) {if(subtype==2)return DROPSOUND_BOW;if(subtype==6||subtype==9)return DROPSOUND_DEFAULT;return DROPSOUND_WEAPON;} + if(type==2) {if(subtype==5||subtype==6)return DROPSOUND_ACCESSORY;if(subtype==0)return DROPSOUND_ARMOR;} + return DROPSOUND_DEFAULT; +} +} +void SetItemUseSound(uint32_t type,const std::string& filename) {if(type GetItemUseSound(uint32_t vnum) { + int type,sub;if(!GetItemTypeAndSubType(vnum,&type,&sub))return std::nullopt; + if(type==3) { + if(sub==0)return std::nullopt; // Potion sound is server-triggered, never on client item use. + if(sub==7)return useSounds[USESOUND_POTION]; + if(sub==1)return useSounds[USESOUND_PORTAL]; + } + return useSounds[equipmentSound(type,sub)+1]; +} +std::optional GetItemDropSound(uint32_t vnum) { + int type,sub;if(!GetItemTypeAndSubType(vnum,&type,&sub))return std::nullopt; + return dropSounds[equipmentSound(type,sub)]; +} +const std::string& GetPotionSound() {return useSounds[USESOUND_POTION];} +void PlayItemUseSound(uint32_t vnum) {if(auto filename=GetItemUseSound(vnum))SoundManager::Instance().PlaySound2D(*filename);} +void PlayItemDropSound(uint32_t vnum) {if(auto filename=GetItemDropSound(vnum))SoundManager::Instance().PlaySound2D(*filename);} +void PlayUsePotionSound() {SoundManager::Instance().PlaySound2D(GetPotionSound());} +} diff --git a/src/item_sound.h b/src/item_sound.h new file mode 100644 index 00000000..2bb2eed4 --- /dev/null +++ b/src/item_sound.h @@ -0,0 +1,17 @@ +#pragma once +#include +#include +#include +namespace ava2 { +// AVA2 PythonItem sound categories (distinct from ItemData USE_* subtypes). +enum ItemUseSound {USESOUND_NONE,USESOUND_DEFAULT,USESOUND_ARMOR,USESOUND_WEAPON,USESOUND_BOW,USESOUND_ACCESSORY,USESOUND_POTION,USESOUND_PORTAL,USESOUND_NUM}; +enum ItemDropSound {DROPSOUND_DEFAULT,DROPSOUND_ARMOR,DROPSOUND_WEAPON,DROPSOUND_BOW,DROPSOUND_ACCESSORY,DROPSOUND_NUM}; +void SetItemUseSound(uint32_t type,const std::string& filename); +void SetItemDropSound(uint32_t type,const std::string& filename); +std::optional GetItemUseSound(uint32_t vnum); +std::optional GetItemDropSound(uint32_t vnum); +const std::string& GetPotionSound(); +void PlayItemUseSound(uint32_t vnum); +void PlayItemDropSound(uint32_t vnum); +void PlayUsePotionSound(); +} diff --git a/src/login_client.cpp b/src/login_client.cpp index 9be64f5d..1c7e5efd 100644 --- a/src/login_client.cpp +++ b/src/login_client.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -111,7 +112,9 @@ void LoginClient::pump() { } flush();if(status_==Status::Failed) return; for(int iteration=0;iteration<16;++iteration) { - std::uint8_t buffer[4096];auto n=recv(fd_,buffer,sizeof(buffer),0); + // CNetworkStream::__RecvInternalBuffer: no recv() while the 128 KB buffer is full; TCP back-pressure instead of an error. + std::size_t space=std::min(4096,session_->receive_space());if(!space) break; + std::uint8_t buffer[4096];auto n=recv(fd_,buffer,space,0); if(n<0 && errno==EINTR) continue; if(n<0 && (errno==EAGAIN || errno==EWOULDBLOCK)) break; if(n<=0) { fail("server disconnected");return; } @@ -131,10 +134,10 @@ void LoginClient::pump() { flush();if(status_==Status::Failed) return; } } -wire::Bytes LoginClient::take_game_input() { return session_?session_->take_game_input():wire::Bytes{}; } -void LoginClient::send_game_packet(wire::Bytes packet) { +wire::Bytes LoginClient::take_game_input(std::size_t max) { return session_?session_->take_game_input(max):wire::Bytes{}; } +void LoginClient::send_game_packet(wire::Bytes packet,bool sequence) { if(status_!=Status::Loading || !session_) throw std::logic_error("game transport is not ready"); - session_->send_game_packet(std::move(packet));enqueue();flush(); + session_->send_game_packet(std::move(packet),sequence);enqueue();flush(); } void LoginClient::direct_enter(std::uint8_t slot) { if(!session_ || status_!=Status::Selecting || slot>=session_->characters().size() || !session_->characters()[slot].id) diff --git a/src/login_client.h b/src/login_client.h index 252aadcf..6be2cdcc 100644 --- a/src/login_client.h +++ b/src/login_client.h @@ -18,10 +18,11 @@ public: void connect(Endpoint auth,Endpoint game,std::string account,std::string password); void cancel(); void pump(); // no blocking socket operation or DNS lookup on the caller thread + void update_player_guild(const std::string& player,uint32_t id,const std::string& name) {if(session_)session_->update_player_guild(player,id,name);} void select(std::uint8_t slot); void direct_enter(std::uint8_t slot); - wire::Bytes take_game_input(); - void send_game_packet(wire::Bytes packet); + wire::Bytes take_game_input(std::size_t max=LoginSession::kRecvBufferSize); + void send_game_packet(wire::Bytes packet,bool sequence=true); std::vector take_events(); Status status() const { return status_; } const LoginSession* session() const { return session_.get(); } diff --git a/src/login_session.cpp b/src/login_session.cpp index 78292cc7..a8aed3dd 100644 --- a/src/login_session.cpp +++ b/src/login_session.cpp @@ -39,7 +39,7 @@ void LoginSession::emit(Bytes bytes,bool sequence) { std::vector LoginSession::take_output() { auto out=std::move(output_); output_.clear(); return out; } void LoginSession::feed(std::span input) { if(state_==State::Failed) return; - if(input.size()>128*1024 || raw_.size()+plain_.size()+input.size()>128*1024) { fail("receive buffer limit exceeded"); return; } + if(input.size()>receive_space()) { fail("receive buffer limit exceeded"); return; } raw_.insert(raw_.end(),input.begin(),input.end()); while(!raw_.empty() && state_!=State::Failed) { std::size_t n=encrypted_?8:1; @@ -120,14 +120,15 @@ bool LoginSession::process_packet() { } return true; } -wire::Bytes LoginSession::take_game_input() { - if(state_!=State::Loading) return {}; - auto bytes=std::move(plain_);plain_.clear();return bytes; +wire::Bytes LoginSession::take_game_input(std::size_t max) { + if(state_!=State::Loading || max==0) return {}; + if(plain_.size()<=max) { auto bytes=std::move(plain_);plain_.clear();return bytes; } + Bytes bytes(plain_.begin(),plain_.begin()+max);plain_.erase(plain_.begin(),plain_.begin()+max);return bytes; } -void LoginSession::send_game_packet(wire::Bytes packet) { +void LoginSession::send_game_packet(wire::Bytes packet,bool sequence) { if(state_!=State::Loading) throw std::logic_error("game packet before loading handoff"); if(packet.empty() || packet.size()>65535) throw std::invalid_argument("invalid game packet size"); - emit(std::move(packet),true); + emit(std::move(packet),sequence); } void LoginSession::select(std::uint8_t slot) { if(state_!=State::Selecting) throw std::logic_error("selection requires character roster and select phase"); diff --git a/src/login_session.h b/src/login_session.h index 5c52558c..fdc2053f 100644 --- a/src/login_session.h +++ b/src/login_session.h @@ -20,9 +20,15 @@ public: void reconnect_game(); void feed(std::span input); std::vector take_output(); + void update_player_guild(const std::string& player,uint32_t id,const std::string& name) { + for(auto& c:characters_)if(c.name==player) {c.guild_id=id;c.guild_name=name;} + } void select(std::uint8_t slot); - wire::Bytes take_game_input(); - void send_game_packet(wire::Bytes packet); + // Windows networkmodule.py: net.SetTCPRecvBufferSize(128*1024). A full buffer pauses recv() (restSize<=0). + static constexpr std::size_t kRecvBufferSize=128*1024; + std::size_t receive_space() const { return kRecvBufferSize-(raw_.size()+plain_.size()); } + wire::Bytes take_game_input(std::size_t max=kRecvBufferSize); + void send_game_packet(wire::Bytes packet,bool sequence=true); State state() const { return state_; } const std::string& failure() const { return failure_; } const std::vector& pack_metadata() const { return pack_metadata_; } diff --git a/src/main.cpp b/src/main.cpp index 964bd02e..de089ca5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -23,6 +23,11 @@ #ifdef AVA2_HAS_PYTHON #include "python_runtime.h" #include "python_net.h" +#include "python_event_manager.h" +#include "python_system.h" +#include "eter_base/Random.h" +#include +#include #include "python_gameplay_modules.h" #include "eter_image/GrpDevice.h" #include "eter_ui/PythonWindowManager.h" @@ -156,6 +161,12 @@ int main(int argc, char** argv) { #endif #ifdef AVA2_HAS_PYTHON +#ifdef __ANDROID__ + // metin2.cfg / interface.cfg live in the client's working directory on Windows; the APK's + // working directory is not writable, so they go to the app's internal storage instead. + if (const char* internal = SDL_GetAndroidInternalStoragePath()) + ava2::CPythonSystem::SetConfigDirectory(internal); +#endif std::unique_ptr python; if (!stdlib.empty() || !script_root.empty()) { python = std::make_unique(stdlib, script_root); @@ -182,6 +193,10 @@ int main(int argc, char** argv) { #endif } +#ifdef AVA2_HAS_PYTHON + // WinMain: srandom(time(NULL) + DWORD(GetCurrentProcess())) for EterBase random_range. + eter::srandom(uint32_t(std::time(nullptr)) + std::random_device{}()); +#endif if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) throw std::runtime_error(SDL_GetError()); struct Quit { ~Quit(){ SDL_Quit(); } } quit; @@ -191,8 +206,16 @@ int main(int argc, char** argv) { ); if (!gpu) throw std::runtime_error(SDL_GetError()); + // CPythonApplication::Create sizes the device from metin2.cfg (CPythonSystem::GetWidth/GetHeight). + int screen_width = 1280, screen_height = 720; +#ifdef AVA2_HAS_PYTHON + if (python) { + screen_width = int(ava2::CPythonSystem::Instance().GetWidth()); + screen_height = int(ava2::CPythonSystem::Instance().GetHeight()); + } +#endif std::unique_ptr window( - SDL_CreateWindow("AVA2 — Metin2 Client", 1280, 720, SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY), + SDL_CreateWindow("AVA2 — Metin2 Client", screen_width, screen_height, SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY), SDL_DestroyWindow ); if (!window) throw std::runtime_error(SDL_GetError()); @@ -203,7 +226,7 @@ int main(int argc, char** argv) { ); if (!renderer) throw std::runtime_error(SDL_GetError()); - SDL_SetRenderLogicalPresentation(renderer.get(), 1280, 720, SDL_LOGICAL_PRESENTATION_LETTERBOX); + SDL_SetRenderLogicalPresentation(renderer.get(), screen_width, screen_height, SDL_LOGICAL_PRESENTATION_LETTERBOX); SDL_SetRenderVSync(renderer.get(), 1); SDL_StartTextInput(window.get()); float dpi_scale = SDL_GetWindowPixelDensity(window.get()); @@ -219,9 +242,10 @@ int main(int argc, char** argv) { graphicDevice.Init(renderer.get()); UI::CWindowManager* wm = python ? python->window_manager() : nullptr; if (wm) { - wm->SetScreenSize(1280, 720); - wm->SetResolution(1280, 720); + wm->SetScreenSize(screen_width, screen_height); + wm->SetResolution(screen_width, screen_height); } + if (python) ava2::CPythonSystem::Instance().GetDisplaySettings(); // Preview data must be explicitly requested; never shadow authenticated roster. if (preview_data) { @@ -949,6 +973,8 @@ int main(int argc, char** argv) { ava2::LoginViewSnapshot snapshot; if (python && !view_script.empty()) { python->pump_network(); + // CheckPacket unknown header / "quit" server command: Windows PostQuitMessage(0) + if (ava2::PythonNetworkStream::Instance().IsQuitRequested()) running = false; snapshot = python->view_snapshot(); } #endif @@ -1711,6 +1737,8 @@ int main(int argc, char** argv) { #ifdef AVA2_HAS_PYTHON graphicDevice.BeginScene(false); if (wm) { + // CTimer::GetElapsedMilliecond for the event sets updated by this frame's windows. + ava2::CPythonEventManager::Instance().SetElapsedMillisecond(long(dt * 1000.0f)); wm->Update(); wm->Render(); } @@ -1813,6 +1841,11 @@ int main(int argc, char** argv) { #ifdef AVA2_HAS_PYTHON graphicDevice.Init(nullptr); + // CPythonApplication::Destroy: SaveConfig, then SaveInterfaceStatus while Python is alive. + if (python) { + ava2::CPythonSystem::Instance().SaveConfig(); + ava2::CPythonSystem::Instance().SaveInterfaceStatus(); + } #endif ava2::SoundManager::Instance().Destroy(); SDL_StopTextInput(window.get()); diff --git a/src/messenger_state.h b/src/messenger_state.h new file mode 100644 index 00000000..839d0765 --- /dev/null +++ b/src/messenger_state.h @@ -0,0 +1,31 @@ +#pragma once +// AVA2 UserInterface/PythonMessenger.cpp/.h, including observable callback order. +#include +#include +#include +#include +#include +namespace ava2 { +class MessengerState { +public: + void SetHandler(PyObject* handler); + void Destroy(); // Windows clears lists but retains the handler. + void Reset(); // Runtime teardown also releases the owned Python reference. + void RemoveFriend(const std::string& name); + bool IsFriend(const std::string& name) const; + void FriendLogin(const std::string& name); + void FriendLogout(const std::string& name); + void SetMobile(const std::string& name,uint8_t state); + void AppendGuildMember(const std::string& name); + void RemoveGuildMember(const std::string& name); + void RemoveAllGuildMember(); + void LoginGuildMember(const std::string& name); + void LogoutGuildMember(const std::string& name); + void RefreshGuildMember(); +private: + std::set friends; + std::map guild; + PyObject* handler=nullptr; +}; +MessengerState& GetMessengerState(); +} diff --git a/src/nonplayer_data.cpp b/src/nonplayer_data.cpp index d296633e..ee5a66e0 100644 --- a/src/nonplayer_data.cpp +++ b/src/nonplayer_data.cpp @@ -1,10 +1,45 @@ #include "nonplayer_data.h" +#include "python_wiki.h" #include "legacy_cipher.h" #include "../third_party/ava2-lzo/lzo1x.h" #include +#include +#include +#include "ava2_text_file.h" namespace ava2 { NonPlayerData& NonPlayerData::Instance() { static NonPlayerData data; return data; } const MobRecord* NonPlayerData::get(uint32_t vnum) const { auto it=records.find(vnum);return it==records.end()?nullptr:&it->second; } +bool NonPlayerData::loadMobScale(const std::string& text,const std::string& fileName) { + const auto lines=ava2TextLines(text); + for(size_t i=0;isecond; } +bool NonPlayerData::loadNPCWear(const std::string& text) { + for(const auto& line:ava2TextLines(text)) { + auto tokens=ava2TabTokens(line,false); // SplitLine(i,&TokenVector,"\t") + if(tokens.size()!=NPC_WEAR_MAX+2) continue; + const uint32_t npcVnum=uint32_t(std::atoi(tokens[0].c_str())); + std::vector wear(NPC_WEAR_MAX); + for(size_t i=0;i7) continue; + npcWear[tokens[1]].emplace(npcVnum,wear); + } + return true; +} +int NonPlayerData::getNPCWear(int race,uint8_t wearIndex,const std::string& warpMapName) const { + if(wearIndex>=NPC_WEAR_MAX) return -1; + for(const std::string& key:{warpMapName,std::string("all")}) { + auto map=npcWear.find(key);if(map==npcWear.end()) continue; + auto it=map->second.find(uint32_t(race));if(it!=map->second.end()) return it->second[wearIndex]; + } + return -1; +} bool UseNonPlayerName(uint32_t race) { if(race>=30000 && race<=30020) return false; static const uint32_t excluded[]={20101,20102,20103,20104,20105,20106,20107,20108,20109,0,1,2,3,4,5,6,7,8,9,34041,34042,34043,34044,34045,34046,34047,34048,34049,34050,34051,34052,34053,34054,34001,34003,34009,34010,34011,34012,34008,34007,34005,34006,34016,34023,34024,34025,34026,34027,34028,34021,34022,34015}; @@ -49,6 +84,9 @@ bool NonPlayerData::load(const std::string& data) { for(int j=0;j<11;++j) m.resists[j]=row[118+prefixShift+j]<128?row[118+prefixShift+j]:int(row[118+prefixShift+j])-256; uint32_t bits=wire::read32(row,205+prefixShift+resistShift);std::memcpy(&m.damageMultiply,&bits,4);loaded.push_back(std::move(m)); } + // ENABLE_WIKI: CPythonWiki::LoadMonster per record in file order, then ListReverse. + for(const auto& m:loaded) WikiLoadMonster(m); + WikiListReverse(); for(auto& m:loaded) records.emplace(m.vnum,std::move(m)); // Original insert preserves first record. return true; } catch(const std::exception&) { return false; } diff --git a/src/nonplayer_data.h b/src/nonplayer_data.h index 1406705d..a7cd8504 100644 --- a/src/nonplayer_data.h +++ b/src/nonplayer_data.h @@ -19,8 +19,21 @@ public: const MobRecord* get(uint32_t vnum) const; void clear() { records.clear(); } const std::map& all() const { return records; } + // CPythonNonPlayer::LoadMobScale / LoadNPCWear (ENABLE_MOB_SCALE_SYSTEM, ENABLE_NPC_WEAR_ITEM). + // Like Windows, Destroy() (clear) leaves both tables alone; mob scale never overwrites. + struct MobScale { float x=0,y=0,z=0; }; + enum { NPC_WEAR_RACE, NPC_WEAR_WEAPON, NPC_WEAR_ARMOR, NPC_WEAR_HAIR, NPC_WEAR_ACCE, NPC_WEAR_MOUNT, + NPC_WEAR_SHINING_WEAPON1, NPC_WEAR_SHINING_WEAPON2, NPC_WEAR_SHINING_WEAPON3, + NPC_WEAR_SHINING_ARMOR1, NPC_WEAR_SHINING_ARMOR2, NPC_WEAR_SHINING_ARMOR3, NPC_WEAR_SHINING_SPECIAL, NPC_WEAR_MAX }; + bool loadMobScale(const std::string& text, const std::string& fileName); + const MobScale* getMobScale(uint32_t vnum) const; + void clearNPCWear() { npcWear.clear(); } + bool loadNPCWear(const std::string& text); + int getNPCWear(int race, uint8_t wearIndex, const std::string& warpMapName) const; private: std::map records; + std::map mobScales; + std::map>> npcWear; }; bool UseNonPlayerName(uint32_t race); bool GetNonPlayerName(uint32_t race,std::string& name); diff --git a/src/offline_shop_state.h b/src/offline_shop_state.h new file mode 100644 index 00000000..3e473632 --- /dev/null +++ b/src/offline_shop_state.h @@ -0,0 +1,30 @@ +#pragma once +// AVA2 UserInterface/PythonShop.cpp, active ENABLE_OFFLINESHOP_SYSTEM profile. +#include "eter_net/Packet.h" +#include +#include +#include +namespace ava2 { +struct OfflineShopState { + std::array items{}; + std::map,TOfflineShopItemTable> stock; + uint32_t displayed=0,watchers=0,type=0; + int64_t money=0; + uint64_t flag=0; + int32_t time=0; + bool hasShop=false; + // Original m_isOfflineShop is cleared, but never set, even on START. + std::string sign="NONE"; + TOfflineShopItemData* Item(uint32_t position) { + uint8_t tab=uint8_t(position/80); + if(tab>=3)return nullptr; + auto& item=items[size_t(tab)*80+position%80];return item.vnum?&item:nullptr; + } + void SetItem(uint32_t position,const TOfflineShopItemData& item) { + uint8_t tab=uint8_t(position/80);if(tab<3)items[size_t(tab)*80+position%80]=item; + } +}; +OfflineShopState& GetOfflineShopState(); +void ClearOfflineShopState(); +void InitOfflineShopMethods(); +} diff --git a/src/pet_skill_state.h b/src/pet_skill_state.h new file mode 100644 index 00000000..7757faf2 --- /dev/null +++ b/src/pet_skill_state.h @@ -0,0 +1,21 @@ +#pragma once +// AVA2 UserInterface/PythonSkillPet.cpp/h, NEW_PET_SYSTEM feature profile. +#include +#include +#include +#include +namespace ava2 { +enum PetSkillType {SKILLPET_TYPE_NONE,SKILLPET_TYPE_PASSIVE,SKILLPET_TYPE_AUTO,SKILLPET_TYPE_MAX_NUM}; +struct PetSkillRecord { + uint32_t index=0,delay=0,imageHandle=0; + uint8_t type=0; + std::string name,icon,description; +}; +struct PetSkillState { + std::array slots{}; + std::map records; + void Clear() {records.clear();} // Original Destroy retains all three slot assignments. +}; +PetSkillState& GetPetSkillState(); +bool LoadPetSkills(const std::string& path); +} diff --git a/src/player_settings.cpp b/src/player_settings.cpp new file mode 100644 index 00000000..a6b39d2e --- /dev/null +++ b/src/player_settings.cpp @@ -0,0 +1,297 @@ +// AVA2 UserInterface/PythonPlayerSettingsModule.{h,cpp}: the m_vecEffects, m_vecEmoticons and +// m_vecUse/DropSoundFileName tables that initPlayerSettingsModule hands to the closed +// PythonPlayerSettingsModuleLib, which registers them through CInstanceBase::RegisterEffect, +// CPythonNetworkStream::RegisterEmoticonString and CPythonItem::Set*SoundFileName. +// Tables generated from the AVA2 header with Locale_inc.h applied (SASH, VERSION_162, SHINING, +// ZODIAC_MISSION, MELEY_LAIR_DUNGEON, LVL115_ARMOR_EFFECT, OFFLINESHOP on; COMBAT_ZONE, +// ELEMENT_SPELL_WORLDARD, WOLFMAN, EXPRESSING_EMOTION off). Indices that land at or above +// CInstanceBase::EFFECT_NUM (EFFECT_AFFECT+EFFECT_SKILL_DAMAGE_ZONE..., EFFECT_AFFECT+AFFECT_STATUE* +// read as EFFECT_* offsets) are kept: RegisterEffect rejects them exactly like Windows does. +// Emoticon chat strings are the original CP949 bytes. +#include "player_settings.h" +#include "item_sound.h" +#include "eter_net/NetworkActorManager.h" +#include "eter_net/PythonNetworkStream.h" + +namespace ava2 { +namespace { +struct TCacheEffect { unsigned type; const char* bone; const char* file; bool cache; }; +struct TEmoticon { unsigned type; const char* bone; const char* file; const char* chat; }; + +const TCacheEffect kEffects[] = { + {0, "", "d:/ymir work/effect/etc/dust/dust.mse", false}, + {228, "", "d:/ymir work/effect/etc/dust/running_dust.mse", false}, + {2, "", "d:/ymir work/effect/hit/blow_1/blow_1_low.mse", false}, + {13, "", "d:/ymir work/effect/etc/recuperation/drugup_red.mse", false}, + {14, "", "d:/ymir work/effect/etc/recuperation/drugup_blue.mse", false}, + {15, "", "d:/ymir work/effect/etc/recuperation/drugup_green.mse", false}, + {16, "", "d:/ymir work/effect/etc/recuperation/drugup_purple.mse", false}, + {270, "", "d:/ymir work/effect/etc/recuperation/autodrugup_red.mse", false}, + {271, "", "d:/ymir work/effect/etc/recuperation/autodrugup_blue.mse", false}, + {272, "", "d:/ymir work/effect/etc/buff/buff_item1.mse", false}, + {273, "", "d:/ymir work/effect/etc/buff/buff_item2.mse", false}, + {274, "", "d:/ymir work/effect/etc/buff/buff_item3.mse", false}, + {275, "", "d:/ymir work/effect/etc/buff/buff_item4.mse", false}, + {18, "Bip01", "d:/ymir work/effect/hit/gwantong.mse", false}, + {21, "", "d:/ymir work/effect/etc/firecracker/newyear_firecracker.mse", false}, + {22, "", "d:/ymir work/effect/etc/firecracker/paing_i.mse", false}, + {221, "", "d:/ymir work/effect/etc/click/click_select.mse", false}, + {222, "", "d:/ymir work/effect/etc/click/click_glow_select.mse", false}, + {1, "Bip01 Head", "d:/ymir work/effect/etc/stun/stun.mse", false}, + {17, "Bip01 R Hand", "d:/ymir work/effect/hit/critical.mse", false}, + {254, "", "d:/ymir work/effect/affect/damagevalue/target.mse", false}, + {255, "", "d:/ymir work/effect/affect/damagevalue/nontarget.mse", false}, + {256, "", "d:/ymir work/effect/affect/damagevalue/damage.mse", false}, + {257, "", "d:/ymir work/effect/affect/damagevalue/damage_1.mse", false}, + {258, "", "d:/ymir work/effect/affect/damagevalue/poison.mse", false}, + {259, "", "d:/ymir work/effect/affect/damagevalue/miss.mse", false}, + {260, "", "d:/ymir work/effect/affect/damagevalue/target_miss.mse", false}, + {277, "", "d:/ymir work/effect/etc/buff/buff_item6.mse", false}, + {278, "", "d:/ymir work/effect/etc/buff/buff_item7.mse", false}, + {265, "", "season1/effect/paymessage_warning.mse", false}, + {266, "", "season1/effect/paymessage_decide.mse", false}, + {267, "", "d:/ymir work/effect/hit/percent_damage1.mse", false}, + {268, "", "d:/ymir work/effect/hit/percent_damage2.mse", false}, + {269, "", "d:/ymir work/effect/hit/percent_damage3.mse", false}, + {252, "Bip01", "d:/ymir work/effect/etc/myshop/2.mse", false}, + {9, "Bip01", "d:/ymir work/effect/etc/appear_die/monster_appear.mse", false}, + {10, "Bip01", "d:/ymir work/effect/etc/appear_die/monster_die.mse", false}, + {3, "equip_right_hand", "d:/ymir work/effect/hit/blow_flame/flame_3_weapon.mse", false}, + {4, "", "d:/ymir work/effect/hit/blow_flame/flame_3_blow.mse", false}, + {5, "", "d:/ymir work/effect/hit/blow_flame/flame_3_body.mse", false}, + {6, "equip_right", "d:/ymir work/effect/hit/blow_electric/light_1_weapon.mse", false}, + {7, "", "d:/ymir work/effect/hit/blow_electric/light_1_blow.mse", false}, + {8, "", "d:/ymir work/effect/hit/blow_electric/light_1_body.mse", false}, + {11, "", "d:/ymir work/effect/etc/levelup_1/level_up.mse", false}, + {12, "", "d:/ymir work/effect/etc/skillup/skillup_1.mse", false}, + {224, "Bip01", "d:/ymir work/effect/etc/empire/empire_A.mse", false}, + {225, "Bip01", "d:/ymir work/effect/etc/empire/empire_B.mse", false}, + {226, "Bip01", "d:/ymir work/effect/etc/empire/empire_C.mse", false}, + {24, "equip_right_hand", "d:/ymir work/pc/warrior/effect/geom_sword_loop.mse", false}, + {25, "equip_right_hand", "d:/ymir work/pc/warrior/effect/geom_spear_loop.mse", false}, + {27, "Bip01", "locale/en/effect/gm.mse", false}, + {30, "Bip01", "d:/ymir work/effect/hit/blow_poison/poison_loop.mse", false}, + {31, "", "d:/ymir work/effect/affect/slow.mse", false}, + {32, "Bip01 Head", "d:/ymir work/effect/etc/stun/stun_loop.mse", false}, + {33, "", "d:/ymir work/effect/etc/ready/ready.mse", false}, + {43, "", "d:/ymir work/pc/warrior/effect/gyeokgongjang_loop.mse", false}, + {44, "", "d:/ymir work/pc/assassin/effect/gyeonggong_loop.mse", false}, + {46, "Bip01 R Finger2", "d:/ymir work/pc/sura/effect/gwigeom_loop.mse", false}, + {47, "", "d:/ymir work/pc/sura/effect/fear_loop.mse", false}, + {48, "", "d:/ymir work/pc/sura/effect/jumagap_loop.mse", false}, + {49, "", "d:/ymir work/pc/shaman/effect/3hosin_loop.mse", false}, + {50, "", "d:/ymir work/pc/shaman/effect/boho_loop.mse", false}, + {51, "", "d:/ymir work/pc/shaman/effect/10kwaesok_loop.mse", false}, + {52, "", "d:/ymir work/pc/sura/effect/heuksin_loop.mse", false}, + {53, "", "d:/ymir work/pc/sura/effect/muyeong_loop.mse", false}, + {55, "Bip01", "d:/ymir work/effect/hit/blow_flame/flame_loop.mse", false}, + {56, "Bip01 R Hand", "d:/ymir work/pc/shaman/effect/6gicheon_hand.mse", false}, + {57, "Bip01 L Hand", "d:/ymir work/pc/shaman/effect/jeungryeok_hand.mse", false}, + {59, "Bip01 Head", "d:/ymir work/pc/sura/effect/pabeop_loop.mse", false}, + {60, "", "d:/ymir work/pc/warrior/effect/gyeokgongjang_loop.mse", false}, + {62, "", "d:/ymir work/effect/etc/guild_war_flag/flag_red.mse", false}, + {63, "", "d:/ymir work/effect/etc/guild_war_flag/flag_blue.mse", false}, + {64, "", "d:/ymir work/effect/etc/guild_war_flag/flag_yellow.mse", false}, + {72, "", "d:/ymir work/pc/shaman/effect/chunwoon_4_target.mse", false}, + {73, "Bip01", "d:/ymir work/pc/shaman/effect/chunwoon_moojuk.mse", false}, + {230, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_7.mse", false}, + {231, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_8.mse", false}, + {232, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_9.mse", false}, + {233, "PART_WEAPON_LEFT", "D:/ymir work/pc/common/effect/sword/sword_7_b.mse", false}, + {234, "PART_WEAPON_LEFT", "D:/ymir work/pc/common/effect/sword/sword_8_b.mse", false}, + {235, "PART_WEAPON_LEFT", "D:/ymir work/pc/common/effect/sword/sword_9_b.mse", false}, + {236, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_7_f.mse", false}, + {237, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_8_f.mse", false}, + {238, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_9_f.mse", false}, + {239, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_7_s.mse", false}, + {240, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_8_s.mse", false}, + {241, "PART_WEAPON", "D:/ymir work/pc/common/effect/sword/sword_9_s.mse", false}, + {242, "PART_WEAPON_LEFT", "D:/ymir work/pc/common/effect/sword/sword_7_s.mse", false}, + {243, "PART_WEAPON_LEFT", "D:/ymir work/pc/common/effect/sword/sword_8_s.mse", false}, + {244, "PART_WEAPON_LEFT", "D:/ymir work/pc/common/effect/sword/sword_9_s.mse", false}, + {245, "Bip01", "D:/ymir work/pc/common/effect/armor/armor_7.mse", false}, + {246, "Bip01", "D:/ymir work/pc/common/effect/armor/armor_8.mse", false}, + {247, "Bip01", "D:/ymir work/pc/common/effect/armor/armor_9.mse", false}, + {248, "Bip01", "D:/ymir work/pc/common/effect/armor/armor-4-2-1.mse", false}, + {249, "Bip01", "D:/ymir work/pc/common/effect/armor/armor-4-2-2.mse", false}, + {250, "Bip01", "D:/ymir work/pc/common/effect/armor/armor-5-1.mse", false}, + {251, "Bip01", "d:/ymir work/pc/common/effect/armor/acc_01.mse", false}, + {75, "", "d:/ymir work/effect/monster2/redd_moojuk.mse", true}, + {76, "", "d:/ymir work/effect/monster2/redd_moojuk.mse", true}, + {77, "", "d:/ymir work/effect/monster2/redd_moojuk_blue.mse", true}, + {78, "", "d:/ymir work/effect/monster2/redd_moojuk_green.mse", true}, + {14340, "", "d:/ymir work/effect/monster2/12_shelter_in_01.mse", true}, + {14341, "", "d:/ymir work/effect/monster2/12_shelter_in_02.mse", true}, + {14342, "", "d:/ymir work/effect/monster2/12_shelter_in_03.mse", true}, + {14343, "", "d:/ymir work/effect/monster2/12_shelter_in_04.mse", true}, + {14344, "", "d:/ymir work/effect/monster2/12_shelter_in_05.mse", true}, + {14345, "", "d:/ymir work/effect/monster2/12_shelter_in_06.mse", true}, + {14346, "", "d:/ymir work/effect/monster2/12_shelter_in_07.mse", true}, + {14347, "", "d:/ymir work/effect/monster2/12_shelter_in_08.mse", true}, + {14348, "", "d:/ymir work/effect/monster2/12_tiger_s3_drop.mse", true}, + {14349, "", "d:/ymir work/effect/monster2/12_dra_s2_drop.mse", true}, + {14350, "", "d:/ymir work/effect/monster2/12_mon_s3_drop.mse", true}, + {14351, "", "d:/ymir work/effect/monster2/12_sna_s3_drop.mse", true}, + {14352, "", "d:/ymir work/effect/monster2/12_hor_s3_drop.mse", true}, + {14353, "", "d:/ymir work/effect/monster2/12_chi_s3_drop.mse", true}, + {14354, "", "d:/ymir work/effect/monster2/daepo_na_02_boom.mse", true}, + {280, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/0/sword.mse", true}, + {281, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/1/sword.mse", true}, + {282, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/2/sword.mse", true}, + {283, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/3/sword.mse", true}, + {284, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/4/sword.mse", true}, + {285, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/5/sword.mse", true}, + {286, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/6/sword.mse", true}, + {287, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/7/sword.mse", true}, + {288, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/8/sword.mse", true}, + {289, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/9/sword.mse", true}, + {290, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/10/sword.mse", true}, + {291, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/11/sword.mse", true}, + {292, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/12/sword.mse", true}, + {293, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/13/sword.mse", true}, + {294, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/14/sword.mse", true}, + {2280, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/0/twohand.mse", true}, + {2281, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/1/twohand.mse", true}, + {2282, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/2/twohand.mse", true}, + {2283, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/3/twohand.mse", true}, + {2284, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/4/twohand.mse", true}, + {2285, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/5/twohand.mse", true}, + {2286, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/6/twohand.mse", true}, + {2287, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/7/twohand.mse", true}, + {2288, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/8/twohand.mse", true}, + {2289, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/9/twohand.mse", true}, + {2290, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/10/twohand.mse", true}, + {2291, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/11/twohand.mse", true}, + {2292, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/12/twohand.mse", true}, + {2293, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/13/twohand.mse", true}, + {2294, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/14/twohand.mse", true}, + {4280, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/0/bow.mse", true}, + {4281, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/1/bow.mse", true}, + {4282, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/2/bow.mse", true}, + {4283, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/3/bow.mse", true}, + {4284, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/4/bow.mse", true}, + {4285, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/5/bow.mse", true}, + {4286, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/6/bow.mse", true}, + {4287, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/7/bow.mse", true}, + {4288, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/8/bow.mse", true}, + {4289, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/9/bow.mse", true}, + {4290, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/10/bow.mse", true}, + {4291, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/11/bow.mse", true}, + {4292, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/12/bow.mse", true}, + {4293, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/13/bow.mse", true}, + {4294, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/14/bow.mse", true}, + {6280, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/0/bell.mse", true}, + {6281, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/1/bell.mse", true}, + {6282, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/2/bell.mse", true}, + {6283, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/3/bell.mse", true}, + {6284, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/4/bell.mse", true}, + {6285, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/5/bell.mse", true}, + {6286, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/6/bell.mse", true}, + {6287, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/7/bell.mse", true}, + {6288, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/8/bell.mse", true}, + {6289, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/9/bell.mse", true}, + {6290, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/10/bell.mse", true}, + {6291, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/11/bell.mse", true}, + {6292, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/12/bell.mse", true}, + {6293, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/13/bell.mse", true}, + {6294, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/14/bell.mse", true}, + {8280, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/0/fan.mse", true}, + {8281, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/1/fan.mse", true}, + {8282, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/2/fan.mse", true}, + {8283, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/3/fan.mse", true}, + {8284, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/4/fan.mse", true}, + {8285, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/5/fan.mse", true}, + {8286, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/6/fan.mse", true}, + {8287, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/7/fan.mse", true}, + {8288, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/8/fan.mse", true}, + {8289, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/9/fan.mse", true}, + {8290, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/10/fan.mse", true}, + {8291, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/11/fan.mse", true}, + {8292, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/12/fan.mse", true}, + {8293, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/13/fan.mse", true}, + {8294, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/14/fan.mse", true}, + {10280, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/0/dagger.mse", true}, + {10281, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/1/dagger.mse", true}, + {10282, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/2/dagger.mse", true}, + {10283, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/3/dagger.mse", true}, + {10284, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/4/dagger.mse", true}, + {10285, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/5/dagger.mse", true}, + {10286, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/6/dagger.mse", true}, + {10287, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/7/dagger.mse", true}, + {10288, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/8/dagger.mse", true}, + {10289, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/9/dagger.mse", true}, + {10290, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/10/dagger.mse", true}, + {10291, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/11/dagger.mse", true}, + {10292, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/12/dagger.mse", true}, + {10293, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/13/dagger.mse", true}, + {10294, "PART_WEAPON", "D:/ymir work/effect/plechito/weapons/14/dagger.mse", true}, + {12280, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/0/dagger.mse", true}, + {12281, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/1/dagger.mse", true}, + {12282, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/2/dagger.mse", true}, + {12283, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/3/dagger.mse", true}, + {12284, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/4/dagger.mse", true}, + {12285, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/5/dagger.mse", true}, + {12286, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/6/dagger.mse", true}, + {12287, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/7/dagger.mse", true}, + {12288, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/8/dagger.mse", true}, + {12289, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/9/dagger.mse", true}, + {12290, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/10/dagger.mse", true}, + {12291, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/11/dagger.mse", true}, + {12292, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/12/dagger.mse", true}, + {12293, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/13/dagger.mse", true}, + {12294, "PART_WEAPON_LEFT", "D:/ymir work/effect/plechito/weapons/14/dagger.mse", true}, + {14281, "Bip01", "D:/ymir work/effect/plechito/weapons/0/costume.mse", true}, + {14282, "Bip01", "D:/ymir work/effect/plechito/weapons/1/costume.mse", true}, + {14283, "Bip01", "D:/ymir work/effect/plechito/weapons/2/costume.mse", true}, + {14284, "Bip01", "D:/ymir work/effect/plechito/weapons/3/costume.mse", true}, + {14285, "Bip01", "D:/ymir work/effect/plechito/weapons/4/costume.mse", true}, + {14286, "Bip01", "D:/ymir work/effect/plechito/weapons/5/costume.mse", true}, + {14287, "Bip01", "D:/ymir work/effect/plechito/weapons/6/costume.mse", true}, + {14288, "Bip01", "D:/ymir work/effect/plechito/weapons/7/costume.mse", true}, + {14289, "Bip01", "D:/ymir work/effect/plechito/weapons/8/costume.mse", true}, + {14290, "Bip01", "D:/ymir work/effect/plechito/weapons/9/costume.mse", true}, + {14291, "Bip01", "D:/ymir work/effect/plechito/weapons/10/costume.mse", true}, + {14292, "Bip01", "D:/ymir work/effect/plechito/weapons/11/costume.mse", true}, + {14293, "Bip01", "D:/ymir work/effect/plechito/weapons/12/costume.mse", true}, + {14294, "Bip01", "D:/ymir work/effect/plechito/weapons/13/costume.mse", true}, + {14295, "Bip01", "D:/ymir work/effect/plechito/weapons/14/costume.mse", true}, +}; +const TEmoticon kEmoticons[] = { + {92, "", "d:/ymir work/effect/etc/emoticon/sweat.mse", "(\xc8""\xb2""\xb4""\xe7"")"}, + {93, "", "d:/ymir work/effect/etc/emoticon/money.mse", "(\xb5""\xb7"")"}, + {94, "", "d:/ymir work/effect/etc/emoticon/happy.mse", "(\xb1""\xe2""\xbb""\xdd"")"}, + {95, "", "d:/ymir work/effect/etc/emoticon/love_s.mse", "(\xc1""\xc1""\xbe""\xc6"")"}, + {96, "", "d:/ymir work/effect/etc/emoticon/love_l.mse", "(\xbb""\xe7""\xb6""\xfb"")"}, + {97, "", "d:/ymir work/effect/etc/emoticon/angry.mse", "(\xba""\xd0""\xb3""\xeb"")"}, + {98, "", "d:/ymir work/effect/etc/emoticon/aha.mse", "(\xbe""\xc6""\xc7""\xcf"")"}, + {99, "", "d:/ymir work/effect/etc/emoticon/gloom.mse", "(\xbf""\xec""\xbf""\xef"")"}, + {100, "", "d:/ymir work/effect/etc/emoticon/sorry.mse", "(\xc1""\xcb""\xbc""\xdb"")"}, + {101, "", "d:/ymir work/effect/etc/emoticon/!_mix_back.mse", "(!)"}, + {102, "", "d:/ymir work/effect/etc/emoticon/question.mse", "(?)"}, + {103, "", "d:/ymir work/effect/etc/emoticon/fish.mse", "(fish)"}, +}; + +} // namespace + +void LoadPlayerSettings() { + for (const auto& eft : kEffects) + NetworkActorManager::RegisterEffect(eft.type, eft.bone, eft.file, eft.cache); + for (const auto& emoticon : kEmoticons) { + NetworkActorManager::RegisterEffect(emoticon.type, emoticon.bone, emoticon.file, false); + PythonNetworkStream::Instance().RegisterEmoticonString(emoticon.chat); + } + SetItemUseSound(USESOUND_DEFAULT, "sound/ui/drop.wav"); + SetItemUseSound(USESOUND_ACCESSORY, "sound/ui/equip_ring_amulet.wav"); + SetItemUseSound(USESOUND_ARMOR, "sound/ui/equip_metal_armor.wav"); + SetItemUseSound(USESOUND_BOW, "sound/ui/equip_bow.wav"); + SetItemUseSound(USESOUND_WEAPON, "sound/ui/equip_metal_weapon.wav"); + SetItemUseSound(USESOUND_POTION, "sound/ui/eat_potion.wav"); + SetItemUseSound(USESOUND_PORTAL, "sound/ui/potal_scroll.wav"); + SetItemDropSound(DROPSOUND_DEFAULT, "sound/ui/drop.wav"); + SetItemDropSound(DROPSOUND_ACCESSORY, "sound/ui/equip_ring_amulet.wav"); + SetItemDropSound(DROPSOUND_ARMOR, "sound/ui/equip_metal_armor.wav"); + SetItemDropSound(DROPSOUND_BOW, "sound/ui/equip_bow.wav"); + SetItemDropSound(DROPSOUND_WEAPON, "sound/ui/equip_metal_weapon.wav"); +} + +} // namespace ava2 diff --git a/src/player_settings.h b/src/player_settings.h new file mode 100644 index 00000000..98fce397 --- /dev/null +++ b/src/player_settings.h @@ -0,0 +1,5 @@ +#pragma once +namespace ava2 { +// CPythonPlayerSettingsModule effect / emoticon / item-sound registration (AVA2 app.Create). +void LoadPlayerSettings(); +} diff --git a/src/python_app.cpp b/src/python_app.cpp index 85548bb7..5ed8d61b 100644 --- a/src/python_app.cpp +++ b/src/python_app.cpp @@ -1,11 +1,28 @@ +#include "player_settings.h" #include "python_app.h" #include "server_clock.h" #include "generated_app_constants.h" #include "../upstream/ava2-client/UserInterface/Locale_inc.h" #include "src/eter_image/MarkManager.h" +#include "nonplayer_data.h" +#include "eter_net/NetworkActorManager.h" +#include "eter_render/RaceData.h" +#include "pet_skill_state.h" +#include "python_gameplay_modules.h" +#include "python_native_modules.h" +#include "python_net.h" +#include "python_runtime.h" +#include "ava2_text_file.h" +#include "python_wiki.h" +#include "shared/common/PythonUtils.h" +#include "eter_base/Random.h" +#include #include #include +#include #include +#include +#include namespace ava2 { namespace { @@ -13,6 +30,8 @@ namespace { std::uint32_t local_milliseconds() { return static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count()); } std::int64_t unix_seconds() { return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } ServerClock server_clock(local_milliseconds()); +// EterBase Timer.cpp gs_dwServerTime / gs_dwClientTime (ELTimer_*ServerMSec), separate from app.GetGlobalTime. +std::uint32_t elt_server_time=0,elt_client_time=0; auto app_start=std::chrono::steady_clock::now(); float s_camera_distance = 1500.0f; float s_camera_pitch = 30.0f; @@ -49,12 +68,26 @@ PyObject* app_set_camera(PyObject*, PyObject* args) { Py_RETURN_NONE; } -PyObject* app_set_hair_color_enable(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; Py_RETURN_NONE; } -PyObject* app_set_armor_specular_enable(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; s_armor_specular = (f != 0); Py_RETURN_NONE; } +PyObject* app_set_hair_color_enable(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; NetworkActorManager::SetHairColorEnable(f != 0); Py_RETURN_NONE; } +PyObject* app_set_armor_specular_enable(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; s_armor_specular = (f != 0); NetworkActorManager::SetArmorSpecularEnable(f != 0); Py_RETURN_NONE; } PyObject* app_set_weapon_specular_enable(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; s_weapon_specular = (f != 0); Py_RETURN_NONE; } PyObject* app_set_mouse_handler(PyObject*, PyObject* args) { Py_RETURN_NONE; } -PyObject* app_create(PyObject*, PyObject* args) { Py_RETURN_NONE; } +// appCreate: after the window, LoadPythonPlayerSettingsModuleLibrary registers the +// PythonPlayerSettingsModule tables and CPythonPlayerSettingsModule::Load runs +// introLoading.__main__ (name/title colours, title names, emotion icons, dungeon names), +// then __LoadGameNPC("npclist.txt") and the player race table (CRaceManager / .msm). +PyObject* app_create(PyObject*, PyObject* args) { + ava2::LoadPlayerSettings(); + PyObject* module = PyImport_ImportModule("introLoading"); + PyObject* main = module ? PyObject_GetAttrString(module, "__main__") : nullptr; + PyObject* result = main ? PyObject_CallObject(main, nullptr) : nullptr; + if (!result) PyErr_Print(); + Py_XDECREF(result); Py_XDECREF(main); Py_XDECREF(module); + RaceManager::Instance().LoadGameNPC("npclist.txt"); + RaceManager::Instance().LoadPlayerRaces(); + Py_RETURN_NONE; +} PyObject* app_loop(PyObject*, PyObject*) { Py_RETURN_NONE; } PyObject* app_exit(PyObject*, PyObject*) { Py_RETURN_NONE; } PyObject* app_abort(PyObject*, PyObject*) { Py_RETURN_NONE; } @@ -72,11 +105,32 @@ PyObject* app_get_locale_path(PyObject*, PyObject*) { return PyString_FromString(s_locale_path.c_str()); } +// appLoadLocaleData (AVA2 PythonApplicationModule.cpp). +PyObject* app_load_locale_data(PyObject*, PyObject* args) { + char* localePath; + if (!PyTuple_GetString(args, 0, &localePath)) + return Py_BuildException(); + return Py_BuildValue("i", LoadLocaleData(localePath)); +} + PyObject* app_get_default_codepage(PyObject*, PyObject*) { - return PyInt_FromLong(1252); + return PyInt_FromLong(GetDefaultCodePage()); } PyObject* app_dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; } + +// appGetRandom: EterBase random_range over the swapped bounds. +PyObject* app_get_random(PyObject*, PyObject* poArgs) { + int from; + if (!PyTuple_GetInteger(poArgs, 0, &from)) + return Py_BuildException(); + int to; + if (!PyTuple_GetInteger(poArgs, 1, &to)) + return Py_BuildException(); + if (from > to) + std::swap(from, to); + return Py_BuildValue("i", eter::random_range(from, to)); +} PyObject* app_dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); } PyObject* app_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); } PyObject* app_dummy_float_zero(PyObject*, PyObject*) { return PyFloat_FromDouble(0.0); } @@ -84,6 +138,43 @@ PyObject* app_dummy_str(PyObject*, PyObject*) { return PyString_FromString(""); PyObject* app_dummy_tuple2(PyObject*, PyObject*) { return Py_BuildValue("ii", 0, 0); } PyObject* app_dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 0, 0, 0); } +// CTextLineLoader / appOpenTextFile..appGetTextFileLine (PythonApplicationModule.cpp). +// Windows hands Python the heap pointer as an int; 64-bit hosts get an index instead. +std::unordered_map> s_textLineLoaders; +int s_nextTextLineLoader = 1; + +PyObject* app_open_text_file(PyObject*, PyObject* args) { + const char* fileName = nullptr; + if (!PyArg_ParseTuple(args, "s", &fileName)) return nullptr; + std::vector lines; + try { lines = ava2::ava2TextLines(ReadPackedText(fileName)); } catch (const std::exception&) {} + const int handle = s_nextTextLineLoader++; + s_textLineLoaders[handle] = std::move(lines); + return PyInt_FromLong(handle); +} + +PyObject* app_close_text_file(PyObject*, PyObject* args) { + int handle = 0; + if (!PyArg_ParseTuple(args, "i", &handle)) return nullptr; + s_textLineLoaders.erase(handle); + Py_RETURN_NONE; +} + +PyObject* app_get_text_file_line_count(PyObject*, PyObject* args) { + int handle = 0; + if (!PyArg_ParseTuple(args, "i", &handle)) return nullptr; + auto it = s_textLineLoaders.find(handle); + return PyInt_FromLong(it == s_textLineLoaders.end() ? 0 : long(it->second.size())); +} + +PyObject* app_get_text_file_line(PyObject*, PyObject* args) { + int handle = 0, index = 0; + if (!PyArg_ParseTuple(args, "ii", &handle, &index)) return nullptr; + auto it = s_textLineLoaders.find(handle); + if (it == s_textLineLoaders.end() || index < 0 || size_t(index) >= it->second.size()) return PyString_FromString(""); + return PyString_FromStringAndSize(it->second[index].data(), Py_ssize_t(it->second[index].size())); +} + PyObject* app_set_guild_mark_path(PyObject*, PyObject* args) { const char* path = nullptr; if (PyArg_ParseTuple(args, "s", &path) && path) { @@ -99,12 +190,18 @@ PyObject* app_set_guild_mark_path(PyObject*, PyObject* args) { std::int32_t GetServerTimeStamp() { return server_clock.timestamp(unix_seconds()); } void SetServerTime(std::int32_t time) { server_clock.set(time,local_milliseconds(),unix_seconds()); } -void ResetPythonAppState() { server_clock=ServerClock(local_milliseconds());app_start=std::chrono::steady_clock::now();s_test_server_flag=false;twoHandedAttackSpeedDecrease=0; } +std::uint32_t GetLocalMSec() { return local_milliseconds(); } +std::int32_t GetApplicationSeconds() { return static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now()-app_start).count()); } +void SetServerMSec(std::uint32_t time) { if(time==0) return;elt_server_time=time;elt_client_time=local_milliseconds(); } +std::uint32_t GetServerMSec() { return local_milliseconds()-elt_client_time+elt_server_time; } +void ResetPythonAppState() { elt_server_time=elt_client_time=0;server_clock=ServerClock(local_milliseconds());app_start=std::chrono::steady_clock::now();s_test_server_flag=false;twoHandedAttackSpeedDecrease=0; } std::uint8_t GetEnterGameLanguage() { const char* locales[]={"ymir","en","de","tr","pt","es","fr","ro","pl","it","cz","hu"}; for(std::uint8_t i=1;i<12;++i) if(s_locale_name==locales[i]) return i; return 1; } +// The port serves the AVA2 Latin-1 locales only (en/de/es/...), so the ANSI code page is 1252. +unsigned GetDefaultCodePage() { return 1252; } int GetTwoHandedAttackSpeedDecrease(){return twoHandedAttackSpeedDecrease;} bool IsYmirLocale() { return s_locale_name=="ymir"; } @@ -163,7 +260,7 @@ void initapp() { {"SetGlobalCenterPosition", app_dummy_none, METH_VARARGS, nullptr}, {"SetCenterPosition", app_dummy_none, METH_VARARGS, nullptr}, {"GetCursorPosition", app_dummy_tuple2, METH_VARARGS, nullptr}, - {"GetRandom", app_dummy_zero, METH_VARARGS, nullptr}, + {"GetRandom", app_get_random, METH_VARARGS, nullptr}, {"RunPythonFile", app_dummy_none, METH_VARARGS, nullptr}, {"IsWebPageMode", app_dummy_zero, METH_VARARGS, nullptr}, {"ShowWebPage", app_dummy_none, METH_VARARGS, nullptr}, @@ -193,16 +290,16 @@ void initapp() { {"SetCameraSetting", app_dummy_none, METH_VARARGS, nullptr}, {"SetSightRange", app_dummy_none, METH_VARARGS, nullptr}, {"IsFileExist", app_dummy_zero, METH_VARARGS, nullptr}, - {"OpenTextFile", app_dummy_none, METH_VARARGS, nullptr}, - {"CloseTextFile", app_dummy_none, METH_VARARGS, nullptr}, - {"GetTextFileLineCount", app_dummy_str, METH_VARARGS, nullptr}, - {"GetTextFileLine", app_dummy_str, METH_VARARGS, nullptr}, + {"OpenTextFile", app_open_text_file, METH_VARARGS, nullptr}, + {"CloseTextFile", app_close_text_file, METH_VARARGS, nullptr}, + {"GetTextFileLineCount", app_get_text_file_line_count, METH_VARARGS, nullptr}, + {"GetTextFileLine", app_get_text_file_line, METH_VARARGS, nullptr}, {"GetLocaleServiceName", app_get_locale_service_name, METH_VARARGS, nullptr}, {"GetLocaleName", app_get_locale_name, METH_VARARGS, nullptr}, {"GetLocalePath", app_get_locale_path, METH_VARARGS, nullptr}, {"ForceSetLocale", app_dummy_none, METH_VARARGS, nullptr}, {"LoadLocaleAddr", app_dummy_none, METH_VARARGS, nullptr}, - {"LoadLocaleData", app_dummy_none, METH_VARARGS, nullptr}, + {"LoadLocaleData", app_load_locale_data, METH_VARARGS, nullptr}, {"SetCHEONMA", app_dummy_none, METH_VARARGS, nullptr}, {"IsCHEONMA", app_dummy_zero, METH_VARARGS, nullptr}, {"GetDefaultCodePage", app_get_default_codepage, METH_VARARGS, nullptr}, @@ -295,4 +392,68 @@ void initapp() { PyModule_AddIntConstant(module, "INFO_TEXTTAIL", 3); } +namespace { +void locale_trace_error(const std::string& text) { std::cerr << "[AVA2 TraceError] " << text << std::endl; } +bool load_text(const std::string& path, std::string* text) { + try { *text = ReadPackedText(path); return true; } catch (const std::exception&) { return false; } +} +} + +// Same order, Destroy() calls and early-return points as the Windows coordinator. +// Not ported: YMIR lang%d.cvt (AVA2 runs EUROPE) - see docs/WINDOWS-PARITY.md. +bool LoadLocaleData(const std::string& localePath) { + const std::string szItemList = localePath + "/item_list.txt"; + const std::string szItemProto = localePath + "/item_proto"; + const std::string szItemDesc = localePath + "/itemdesc.txt"; + const std::string szMobProto = localePath + "/mob_proto"; + const std::string szSkillDescFileName = localePath + "/SkillDesc.txt"; + const std::string szSkillTableFileName = localePath + "/SkillTable.txt"; + const std::string szInsultList = localePath + "/insult.txt"; + const std::string szSkillPetFileName = localePath + "/pet_skill.txt"; + const std::string szMobScale = localePath + "/mob_scale.txt"; + + NonPlayerData& rkNPCMgr = NonPlayerData::Instance(); + rkNPCMgr.clear(); + ResetItemDatabase(); + ResetSkillDescriptions(); + GetPetSkillState().Clear(); + + if (!LoadItemList(szItemList)) + locale_trace_error("LoadLocaleData - LoadItemList(" + szItemList + ") Error"); + if (!LoadItemTable(szItemProto)) { + locale_trace_error("LoadLocaleData - LoadItemProto(" + szItemProto + ") Error"); + return false; + } + LoadItemDescriptions(szItemDesc); // Tracenf only + std::string text; + if (!load_text(szMobProto, &text) || !rkNPCMgr.load(text)) { + locale_trace_error("LoadLocaleData - LoadMobProto(" + szMobProto + ") Error"); + return false; + } + // The original passes szMobProto to the two skill messages. + if (!LoadSkillDescriptions(szSkillDescFileName)) { + locale_trace_error("LoadLocaleData - RegisterSkillDesc(" + szMobProto + ") Error"); + return false; + } + if (!LoadSkillTable(szSkillTableFileName)) { + locale_trace_error("LoadLocaleData - RegisterSkillTable(" + szMobProto + ") Error"); + return false; + } + if (!LoadPetSkills(szSkillPetFileName)) { + locale_trace_error("LoadLocaleData - RegisterSkillPet(" + szSkillPetFileName + ") Error"); + return false; + } + LoadInsultList(szInsultList); // Tracenf only + rkNPCMgr.clearNPCWear(); + if (load_text("locale/common/npc_wear.txt", &text)) + rkNPCMgr.loadNPCWear(text); + if (!load_text(szMobScale, &text) || !rkNPCMgr.loadMobScale(text, szMobScale)) { + locale_trace_error("LoadMobScale Error(" + szMobScale + ")"); + return false; + } + LoadItemScale(localePath + "/item_scale.txt"); // Tracenf only + WikiReadData(localePath); // ENABLE_WIKI + return true; +} + } // namespace ava2 diff --git a/src/python_app.h b/src/python_app.h index 3c99b6f2..c197be74 100644 --- a/src/python_app.h +++ b/src/python_app.h @@ -1,5 +1,6 @@ #pragma once #include +#include namespace ava2 { int GetTwoHandedAttackSpeedDecrease(); @@ -8,5 +9,13 @@ bool IsYmirLocale(); std::int32_t GetServerTimeStamp(); void SetServerTime(std::int32_t time); void ResetPythonAppState(); +std::uint32_t GetLocalMSec(); +std::int32_t GetApplicationSeconds(); +void SetServerMSec(std::uint32_t time); +std::uint32_t GetServerMSec(); std::uint8_t GetEnterGameLanguage(); +// ::GetDefaultCodePage (EterBase), the code page app.GetDefaultCodePage and script::Group use. +unsigned GetDefaultCodePage(); +// ::LoadLocaleData (AVA2 UserInterface/PythonApplication.cpp), backing app.LoadLocaleData. +bool LoadLocaleData(const std::string& localePath); } diff --git a/src/python_battlepass.cpp b/src/python_battlepass.cpp new file mode 100644 index 00000000..745040d7 --- /dev/null +++ b/src/python_battlepass.cpp @@ -0,0 +1,51 @@ +// Direct port of AVA2 PythonBattlePass.cpp; preserve Python 2 tuple shapes, +// signed Win32 DWORD results and independent info/progress list indexing. +#include "battlepass_state.h" +#include "python_native_modules.h" +#include "eter_net/PythonNetworkStream.h" +#include "shared/common/PythonUtils.h" +namespace ava2 { +BattlePassState& GetBattlePassState() { static BattlePassState state;return state; } +void BattlePassState::SetHandler(PyObject* value) {Py_XINCREF(value);auto* old=handler;handler=value;Py_XDECREF(old);} +void BattlePassState::Clear(uint8_t sub) { + if(sub==BATTLEPASS_SUB_HEADER_CLEAR) {info.clear();time=0;} + else progress.clear(); +} +void BattlePassState::Loading(uint8_t sub) {PyCallClassMemberFunc(handler,"BINARY_BATTLEPASS_LOADING",Py_BuildValue("(i)",int(sub)));} +void BattlePassState::Reset() {info.clear();progress.clear();time=0;SetHandler(nullptr);} +namespace { +PyObject* count(PyObject*,PyObject*) {return PyInt_FromLong(GetBattlePassState().info.size());} +PyObject* time(PyObject*,PyObject*) {return PyInt_FromLong(GetBattlePassState().time);} +PyObject* dates(PyObject*,PyObject* args) { + int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException(); + const auto& data=GetBattlePassState().info; + if(uint32_t(i)>=data.size())return Py_BuildValue("ii",0,0); + return Py_BuildValue("ii",int32_t(data[i].type),int32_t(data[i].vnum)); +} +PyObject* progress(PyObject*,PyObject* args) { + int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException(); + const auto& data=GetBattlePassState().progress; + if(uint32_t(i)>=data.size())return Py_BuildValue("iii",0,0,0); + return Py_BuildValue("iii",data[i].count,data[i].count_actual,int32_t(data[i].reward_status)); +} +PyObject* items(PyObject*,PyObject* args) { + int i,slot;if(!PyTuple_GetInteger(args,0,&i)||!PyTuple_GetInteger(args,1,&slot))return Py_BuildException(); + const auto& data=GetBattlePassState().info; + // Original missing-record result is scalar 0, not the invalid-slot pair. + if(uint32_t(i)>=data.size())return PyInt_FromLong(0); + if(uint32_t(slot)>=4)return Py_BuildValue("ii",0,0); + return Py_BuildValue("ii",int32_t(data[i].items[slot].vnum),int32_t(data[i].items[slot].count)); +} +PyObject* handler(PyObject*,PyObject* args) {PyObject* value;if(!PyTuple_GetObject(args,0,&value))return Py_BuildException();GetBattlePassState().SetHandler(value);Py_RETURN_NONE;} +PyObject* open(PyObject*,PyObject*) {PythonNetworkStream::Instance().SendBattlePassPacket(false);Py_RETURN_NONE;} +PyObject* reward(PyObject*,PyObject* args) {int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException();PythonNetworkStream::Instance().SendBattlePassPacket(true,i);Py_RETURN_NONE;} +} +void intbattlepass() { + static PyMethodDef methods[]={ + {"CountDates",count,METH_VARARGS,nullptr},{"GetDates",dates,METH_VARARGS,nullptr}, + {"GetDatesItems",items,METH_VARARGS,nullptr},{"GetDatesCount",progress,METH_VARARGS,nullptr}, + {"SetBattlePassHandler",handler,METH_VARARGS,nullptr},{"GetTime",time,METH_VARARGS,nullptr}, + {"Open",open,METH_VARARGS,nullptr},{"Reward",reward,METH_VARARGS,nullptr},{nullptr,nullptr,0,nullptr}}; + Py_InitModule("battlepass",methods); +} +} diff --git a/src/python_chat.cpp b/src/python_chat.cpp new file mode 100644 index 00000000..731393b7 --- /dev/null +++ b/src/python_chat.cpp @@ -0,0 +1,1680 @@ +// Provenance: AVA2 UserInterface/PythonChat.cpp and PythonChatModule.cpp (__CHAT_SETTINGS__ + +// ENABLE_MULTILANGUAGE_SYSTEM build). Kept quirks: chat.IsIgnoreCharacter returns None, a chat +// set's colour slot is its id (sets >= 3 share slot 0), ArrangeShowingChat counts country-muted +// shout lines when it sizes the window, CreateChatSet / GetLineCount key the line store by BYTE, +// and CreateWhisper on an existing name leaves the old whisper in place. +// Not carried: DefaultFont_GetResource / the GM italic font (the text stand-in has no font +// resource, so no line is dropped for a missing font), CPythonStackController::CheckStackReference +// and CPythonApplication::ChangeIcon (the Windows taskbar icon behind ENABLE_DISCORD_STUFF). +#include "python_chat.h" +#include "python_app.h" +#include "python_gameplay_modules.h" +#include "eter_resource/ResourceManager.h" +#include "shared/common/PythonUtils.h" +#include +#include +#include +#include +#include + +namespace ava2 { +namespace { + +const float c_fStartDisappearingTime = 5.0f; +const int c_iMaxLineCount = 5; + +// CResourceManager::IsFileExist + GetResourcePointer for the shout flag images. +void SetFlagImage(CGraphicImageInstance& rInstance, const char* c_szFileName) +{ + CResourceManager* pResourceManager = CResourceManager::InstancePtr(); + if (!pResourceManager) + return; + CResource* pResource = pResourceManager->GetResourcePointer(c_szFileName); + if (pResource && pResource->IsType(CGraphicImage::Type())) + rInstance.SetImagePointer(static_cast(pResource)); +} + +void SetShoutFlags(CPythonChat::TChatLine* pChatLine) +{ + if (pChatLine->countryIndex != 0) + { + const char* langlist[] = { "en", "de", "tr", "pt", "es", "fr", "ro", "pl", "it", "cz", "hu" }; + char buf[128]; + snprintf(buf, sizeof(buf), "d:/ymir work/ui/language_flag/%s.tga", langlist[pChatLine->countryIndex - 1]); + SetFlagImage(pChatLine->InstanceLang, buf); + } + if (pChatLine->empireIndex != 0) + { + char buf[128]; + snprintf(buf, sizeof(buf), "d:/ymir work/ui/flag_empire/empire_%d_256.dds", pChatLine->empireIndex); + SetFlagImage(pChatLine->InstanceEmpire, buf); + } +} + +// EterBase/Stl.cpp split_string. +int split_string(const std::string& input, const std::string& delimiter, std::vector& results, bool includeEmpties) +{ + int iPos = 0; + int newPos = -1; + const UINT sizeS2 = UINT(delimiter.size()); + const UINT isize = UINT(input.size()); + + if ((isize == 0) || (sizeS2 == 0)) + return 0; + + std::vector positions; + newPos = int(input.find(delimiter, 0)); + if (newPos < 0) + return 0; + + int numFound = 0; + while (newPos >= iPos) + { + numFound++; + positions.push_back(newPos); + iPos = newPos; + newPos = int(input.find(delimiter, iPos + sizeS2)); + } + + if (numFound == 0) + return 0; + + for (UINT i = 0; i <= positions.size(); ++i) + { + std::string s(""); + if (i == 0) + { + s = input.substr(i, positions[i]); + } + else + { + const UINT offset = positions[i - 1] + sizeS2; + if (offset < isize) + { + if (i == positions.size()) + s = input.substr(offset); + else if (i > 0) + s = input.substr(positions[i - 1] + sizeS2, positions[i] - positions[i - 1] - sizeS2); + } + } + if (includeEmpties || (s.size() > 0)) + results.push_back(s); + } + return numFound; +} + +// EterBase/Utils.h htoi: -1 for any non-hex character. +int htoi(const char* s) +{ + const char* t = s; + int x = 0, y = 1; + s += strlen(s); + + while (t <= --s) + { + if ('0' <= *s && *s <= '9') + x += y * (*s - '0'); + else if ('a' <= *s && *s <= 'f') + x += y * (*s - 'a' + 10); + else if ('A' <= *s && *s <= 'F') + x += y * (10 + *s - 'A'); + else + return -1; + y <<= 4; + } + + return x; +} + +bool GetItemName(uint32_t dwVnum, std::string* pstrName) +{ + int iType; + return GetItemNameAndType(dwVnum, pstrName, &iType); +} + +} // namespace + +int CPythonChat::TChatSet::ms_iChatModeSize = CHAT_TYPE_MAX_NUM; + +/////////////////////////////////////////////////////////////////////////////////////////////////// + +CDynamicPool CPythonChat::SChatLine::ms_kPool; + +CPythonChat& CPythonChat::Instance() +{ + static CPythonChat s_kChat; + return s_kChat; +} + +DWORD CPythonChat::GetCurrentMillisecond() const +{ + return m_dwFixedMillisecond ? m_dwFixedMillisecond : GetLocalMSec(); +} + +void CPythonChat::SetChatColor(UINT eType, UINT r, UINT g, UINT b) +{ + if (eType >= CHAT_TYPE_MAX_NUM) + return; + + DWORD dwColor = (0xff000000) | (r << 16) | (g << 8) | (b); + m_akD3DXClrChat[eType] = D3DXCOLOR(dwColor); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// + +CPythonChat::SChatLine* CPythonChat::SChatLine::New() +{ + return ms_kPool.Alloc(); +} + +void CPythonChat::SChatLine::Delete(CPythonChat::SChatLine* pkChatLine) +{ + pkChatLine->Instance.Destroy(); + pkChatLine->InstanceLang.Destroy(); + pkChatLine->InstanceEmpire.Destroy(); + ms_kPool.Free(pkChatLine); +} + +void CPythonChat::SChatLine::DestroySystem() +{ + ms_kPool.Destroy(); +} + +void CPythonChat::SChatLine::SetColor(DWORD dwID, DWORD dwColor) +{ + if (dwID >= CHAT_LINE_COLOR_ARRAY_MAX_NUM) + return; + + aColor[dwID] = dwColor; +} + +void CPythonChat::SChatLine::SetColorAll(DWORD dwColor) +{ + for (int i = 0; i < CHAT_LINE_COLOR_ARRAY_MAX_NUM; ++i) + aColor[i] = dwColor; +} + +D3DXCOLOR& CPythonChat::SChatLine::GetColorRef(DWORD dwID) +{ + if (dwID >= CHAT_LINE_COLOR_ARRAY_MAX_NUM) + return aColor[0]; + + return aColor[dwID]; +} + +CPythonChat::SChatLine::SChatLine() +{ + iType = 0; + fAppendedTime = 0.0f; + for (int i = 0; i < CHAT_LINE_COLOR_ARRAY_MAX_NUM; ++i) + aColor[i] = DWORD(0xff0000ff); + countryIndex = 0; + empireIndex = 0; +} + +CPythonChat::SChatLine::~SChatLine() +{ + Instance.Destroy(); + InstanceLang.Destroy(); + InstanceEmpire.Destroy(); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// + +int CPythonChat::CreateChatSet(DWORD dwID) +{ + auto it = m_ChatLineNewDeque.find(BYTE(dwID)); + if (it != m_ChatLineNewDeque.end()) + return dwID; + + TChatSet pChatSet; + TChatLineDeque map_vec; + + auto itChat = m_ChatLineNewDeque.find(0); + if (itChat != m_ChatLineNewDeque.end()) + { + for (auto chat = itChat->second.begin(); chat != itChat->second.end(); ++chat) + { + SChatLine* chatLine = *chat; + SChatLine* pChatLine = SChatLine::New(); + + pChatLine->empireIndex = chatLine->empireIndex; + pChatLine->countryIndex = chatLine->countryIndex; + if (chatLine->iType == CHAT_TYPE_SHOUT) + SetShoutFlags(pChatLine); + + pChatLine->text = chatLine->text; + pChatLine->iType = chatLine->iType; + pChatLine->Instance.SetValue(chatLine->text.c_str()); + pChatLine->fAppendedTime = chatLine->fAppendedTime; + pChatLine->SetColorAll(GetChatColor(pChatLine->iType)); + map_vec.push_back(pChatLine); + } + } + + m_ChatSetMap.emplace(dwID, pChatSet); + m_ChatLineNewDeque.emplace(BYTE(dwID), map_vec); + ArrangeShowingChat(dwID); + return dwID; +} + +void CPythonChat::UpdateViewMode(DWORD dwID) +{ + const float fcurTime = GetGlobalTime(); + + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + TChatLineList* pLineList = &(pChatSet->m_ShowingChatLineList); + int iLineIndex = int(pLineList->size()); + int iHeight = -(int(pLineList->size() + 1) * pChatSet->m_iStep); + + for (TChatLineList::iterator itor = pLineList->begin(); itor != pLineList->end();) + { + TChatLine* pChatLine = (*itor); + + D3DXCOLOR& rColor = pChatLine->GetColorRef(dwID); + + const float fElapsedTime = (fcurTime - pChatLine->fAppendedTime); + if (fElapsedTime >= c_fStartDisappearingTime || iLineIndex >= c_iMaxLineCount) + { + rColor.a -= rColor.a / 10.0f; + + if (rColor.a <= 0.1f) + itor = pLineList->erase(itor); + else + ++itor; + } + else + { + ++itor; + } + + iHeight += pChatSet->m_iStep; + --iLineIndex; + + int iWidth = pChatSet->m_ix; + if (pChatLine->iType == CHAT_TYPE_SHOUT) + { + const bool isAttached = (pChatLine->InstanceLang.GetWidth() > 0 && pChatLine->InstanceEmpire.GetWidth() > 0); + if (isAttached) + { + pChatLine->InstanceLang.SetPosition(float(iWidth), float(pChatSet->m_iy + iHeight + 2)); + iWidth += pChatLine->InstanceLang.GetWidth() + 2; + + pChatLine->InstanceEmpire.SetPosition(float(iWidth + 4), float(pChatSet->m_iy + iHeight + 2)); + iWidth += pChatLine->InstanceEmpire.GetWidth() + 8; + } + } + pChatLine->Instance.SetPosition(float(iWidth), float(pChatSet->m_iy + iHeight)); + pChatLine->Instance.SetColor(rColor); + pChatLine->Instance.Update(); + } +} + +void CPythonChat::UpdateEditMode(DWORD dwID) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + const int c_iAlphaLine = std::max(0, GetVisibleLineCount(dwID) - GetEditableLineCount(dwID) + 2); + + int iLineIndex = 0; + float fAlpha = 0.0f; + float fAlphaStep = 0.0f; + + if (c_iAlphaLine > 0) + fAlphaStep = 1.0f / float(c_iAlphaLine); + + TChatLineList* pLineList = &(pChatSet->m_ShowingChatLineList); + int iHeight = -(int(pLineList->size() + 1) * pChatSet->m_iStep); + + for (TChatLineList::iterator itor = pLineList->begin(); itor != pLineList->end(); ++itor) + { + TChatLine* pChatLine = (*itor); + + D3DXCOLOR& rColor = pChatLine->GetColorRef(dwID); + + // iLineIndex is never advanced in the Windows loop, so every line takes the ramp. + if (iLineIndex < c_iAlphaLine) + { + rColor.a += (fAlpha - rColor.a) / 10.0f; + fAlpha = std::min(fAlpha + fAlphaStep, 1.0f); + } + else + { + rColor.a = std::min(rColor.a + 0.05f, 1.0f); + } + + iHeight += pChatSet->m_iStep; + int iWidth = pChatSet->m_ix; + + if (pChatLine->iType == CHAT_TYPE_SHOUT) + { + const bool isAttached = (pChatLine->InstanceLang.GetWidth() > 0 && pChatLine->InstanceEmpire.GetWidth() > 0); + if (isAttached) + { + pChatLine->InstanceLang.SetPosition(float(iWidth), float(pChatSet->m_iy + iHeight + 2)); + iWidth += pChatLine->InstanceLang.GetWidth() + 2; + + pChatLine->InstanceEmpire.SetPosition(float(iWidth + 4), float(pChatSet->m_iy + iHeight + 2)); + iWidth += pChatLine->InstanceEmpire.GetWidth() + 8; + } + } + pChatLine->Instance.SetPosition(float(iWidth), float(pChatSet->m_iy + iHeight)); + pChatLine->Instance.SetColor(rColor); + pChatLine->Instance.Update(); + } +} + +void CPythonChat::UpdateLogMode(DWORD dwID) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + TChatLineList* pLineList = &(pChatSet->m_ShowingChatLineList); + int iHeight = 0; + + for (TChatLineList::reverse_iterator itor = pLineList->rbegin(); itor != pLineList->rend(); ++itor) + { + TChatLine* pChatLine = (*itor); + + iHeight -= pChatSet->m_iStep; + int iWidth = pChatSet->m_ix; + + if (pChatLine->iType == CHAT_TYPE_SHOUT) + { + const bool isAttached = (pChatLine->InstanceLang.GetWidth() > 0 && pChatLine->InstanceEmpire.GetWidth() > 0); + if (isAttached) + { + pChatLine->InstanceLang.SetPosition(float(iWidth), float(pChatSet->m_iy + iHeight + 2)); + iWidth += pChatLine->InstanceLang.GetWidth() + 2; + + pChatLine->InstanceEmpire.SetPosition(float(iWidth + 4), float(pChatSet->m_iy + iHeight + 2)); + iWidth += pChatLine->InstanceEmpire.GetWidth() + 8; + } + } + pChatLine->Instance.SetPosition(float(iWidth), float(pChatSet->m_iy + iHeight)); + pChatLine->Instance.SetColor(pChatLine->GetColorRef(dwID)); + pChatLine->Instance.Update(); + } +} + +void CPythonChat::Update(DWORD dwID) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + switch (pChatSet->m_iBoardState) + { + case BOARD_STATE_VIEW: + UpdateViewMode(dwID); + break; + case BOARD_STATE_EDIT: + UpdateEditMode(dwID); + break; + case BOARD_STATE_LOG: + UpdateLogMode(dwID); + break; + } + + const DWORD dwcurTime = GetCurrentMillisecond(); + for (TWaitChatList::iterator itor = m_WaitChatList.begin(); itor != m_WaitChatList.end();) + { + TWaitChat& rWaitChat = *itor; + + if (rWaitChat.dwAppendingTime < dwcurTime) + { + AppendChat(rWaitChat.iType, rWaitChat.strChat.c_str()); + itor = m_WaitChatList.erase(itor); + } + else + { + ++itor; + } + } +} + +void CPythonChat::Render(DWORD dwID) +{ + TChatLineList* pLineList = GetChatLineListPtr(dwID); + if (!pLineList) + return; + + for (TChatLineList::iterator itor = pLineList->begin(); itor != pLineList->end(); ++itor) + { + (*itor)->Instance.Render(); + if ((*itor)->iType == CHAT_TYPE_SHOUT) + { + CGraphicImageInstance& lInstance = (*itor)->InstanceLang; + if (lInstance.GetWidth() > 0) + lInstance.Render(); + CGraphicImageInstance& eInstance = (*itor)->InstanceEmpire; + if (eInstance.GetWidth() > 0) + eInstance.Render(); + } + } +} + +void CPythonChat::SetBoardState(DWORD dwID, int iState) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + pChatSet->m_iBoardState = iState; + ArrangeShowingChat(dwID); +} + +void CPythonChat::SetPosition(DWORD dwID, int ix, int iy) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + pChatSet->m_ix = ix; + pChatSet->m_iy = iy; +} + +void CPythonChat::SetHeight(DWORD dwID, int iHeight) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + pChatSet->m_iHeight = iHeight; +} + +void CPythonChat::SetStep(DWORD dwID, int iStep) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + pChatSet->m_iStep = iStep; +} + +// m_iMode[iMode] is indexed without a range check on Windows; an out-of-range mode only +// rearranges here instead of writing past the vector. +void CPythonChat::ToggleChatMode(DWORD dwID, int iMode) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + if (iMode >= 0 && size_t(iMode) < pChatSet->m_iMode.size()) + pChatSet->m_iMode[iMode] = 1 - pChatSet->m_iMode[iMode]; + ArrangeShowingChat(dwID); +} + +void CPythonChat::EnableChatMode(DWORD dwID, int iMode) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + if (iMode >= 0 && size_t(iMode) < pChatSet->m_iMode.size()) + pChatSet->m_iMode[iMode] = TRUE; + ArrangeShowingChat(dwID); +} + +void CPythonChat::DisableChatMode(DWORD dwID, int iMode) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + if (iMode >= 0 && size_t(iMode) < pChatSet->m_iMode.size()) + pChatSet->m_iMode[iMode] = FALSE; + ArrangeShowingChat(dwID); +} + +void CPythonChat::SetEndPos(DWORD dwID, float fPos) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + fPos = std::max(0.0f, fPos); + fPos = std::min(1.0f, fPos); + if (pChatSet->m_fEndPos != fPos) + { + pChatSet->m_fEndPos = fPos; + ArrangeShowingChat(dwID); + } +} + +int CPythonChat::GetVisibleLineCount(DWORD dwID) +{ + TChatLineList* pLineList = GetChatLineListPtr(dwID); + if (!pLineList) + return 0; + + return int(pLineList->size()); +} + +int CPythonChat::GetEditableLineCount(DWORD dwID) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return 0; + + // A zero step divides by zero on Windows. + if (pChatSet->m_iStep == 0) + return 0; + return pChatSet->m_iHeight / pChatSet->m_iStep + 1; +} + +int CPythonChat::GetLineCount(DWORD dwID) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return 0; + auto it = m_ChatLineNewDeque.find(BYTE(dwID)); + if (it == m_ChatLineNewDeque.end()) + return 0; + + int iCount = 0; + for (DWORD i = 0; i < it->second.size(); ++i) + { + if (!pChatSet->CheckMode(it->second[i]->iType)) + continue; + if (!pChatSet->CheckCountryMode(it->second[i]->countryIndex) && it->second[i]->iType == CHAT_TYPE_SHOUT) + continue; + ++iCount; + } + + return iCount; +} + +int CPythonChat::GetLineStep(DWORD dwID) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return 0; + + return pChatSet->m_iStep; +} + +CPythonChat::TChatLineList* CPythonChat::GetChatLineListPtr(DWORD dwID) +{ + TChatSetMap::iterator itor = m_ChatSetMap.find(int(dwID)); + if (m_ChatSetMap.end() == itor) + return nullptr; + + return &(itor->second.m_ShowingChatLineList); +} + +CPythonChat::TChatSet* CPythonChat::GetChatSetPtr(DWORD dwID) +{ + TChatSetMap::iterator itor = m_ChatSetMap.find(int(dwID)); + if (m_ChatSetMap.end() == itor) + return nullptr; + + return &(itor->second); +} + +const CPythonChat::TChatSet* CPythonChat::GetChatSet(DWORD dwID) const +{ + auto itor = m_ChatSetMap.find(int(dwID)); + return itor == m_ChatSetMap.end() ? nullptr : &itor->second; +} + +const CPythonChat::TChatLineDeque* CPythonChat::GetChatLineDeque(DWORD dwID) const +{ + auto itor = m_ChatLineNewDeque.find(BYTE(dwID)); + return itor == m_ChatLineNewDeque.end() ? nullptr : &itor->second; +} + +void CPythonChat::ArrangeShowingChat(DWORD dwID) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + pChatSet->m_ShowingChatLineList.clear(); + auto it = m_ChatLineNewDeque.find(BYTE(dwID)); + if (it == m_ChatLineNewDeque.end()) + return; + + // A zero step divides by zero on Windows. + if (pChatSet->m_iStep == 0) + return; + + // The country check sits after the push on Windows, so muted shout lines still count here. + TChatLineDeque TempChatLineDeque; + for (TChatLineDeque::iterator itor = it->second.begin(); itor != it->second.end(); ++itor) + { + TChatLine* pChatLine = *itor; + if (pChatSet->CheckMode(pChatLine->iType)) + TempChatLineDeque.push_back(pChatLine); + } + + const int icurLineCount = int(TempChatLineDeque.size()); + const int iVisibleLineCount = std::min(icurLineCount, (pChatSet->m_iHeight + pChatSet->m_iStep) / pChatSet->m_iStep); + const int iEndLine = iVisibleLineCount + int(float(icurLineCount - iVisibleLineCount - 1) * pChatSet->m_fEndPos); + + int iHeight = 12; + for (int i = std::min(icurLineCount - 1, iEndLine); i >= 0; --i) + { + if (!pChatSet->CheckMode(TempChatLineDeque[i]->iType)) + continue; + if (!pChatSet->CheckCountryMode(TempChatLineDeque[i]->countryIndex) && TempChatLineDeque[i]->iType == CHAT_TYPE_SHOUT) + continue; + if (pChatSet->m_iHeight + pChatSet->m_iStep <= iHeight) + break; + + pChatSet->m_ShowingChatLineList.push_front(TempChatLineDeque[i]); + + iHeight += pChatSet->m_iStep; + } +} + +void CPythonChat::AppendChat(int iType, const char* c_szChat) +{ + if (strstr(c_szChat, "#ebvs")) + return; + + // |Hitem::...|h[name]|h: the name is replaced by this client's item name. + std::string str = c_szChat; + const std::string findl1 = "|Hitem:"; + for (size_t i = 0; i < str.length(); i++) + { + const size_t find1 = str.find(findl1, i); + if (find1 == std::string::npos) + break; + + const size_t pos1 = find1 + findl1.length(); + i = pos1; + + if (str.length() - pos1 == 0) + break; + + const std::string item_vnumabc = str.substr(pos1); + const size_t pos2 = item_vnumabc.find(':'); + if (pos2 == std::string::npos) + break; + const std::string item_vnum = item_vnumabc.substr(0, pos2); + char* p; + const long n = strtol(item_vnum.c_str(), &p, 16); + if (*p != 0) + { + SDL_Log("%s a number %s", item_vnum.c_str(), str.c_str()); + } + else + { + const size_t pos_1 = item_vnumabc.find("|h["); + const size_t pos_2 = item_vnumabc.find("]|h"); + if (pos_1 != std::string::npos && pos_2 != std::string::npos) + { + const std::string item_name = item_vnumabc.substr(pos_1 + 3, pos_2 - pos_1 - 3); + std::string strName; + if (GetItemName(uint32_t(n), &strName)) + { + if (strcmp(item_name.c_str(), strName.c_str()) != 0) + str = str.replace(str.find(item_name), item_name.length(), strName); + } + } + else + break; + } + } + + if (m_ChatLineNewDeque.empty()) + return; + + std::string strContent = str; + BYTE empireIndex = 0; + BYTE countryIndex = 0; + if (iType == CHAT_TYPE_SHOUT) + { + // "|lang|N|" and "|empire|N|" prefixes (int positions, as on Windows). + const std::string isLangFlag("|lang|"); + int position = int(strContent.find(isLangFlag)); + if (position != int(std::string::npos)) + { + strContent = strContent.substr(position + isLangFlag.length(), strContent.length()); + position = int(strContent.find("|")); + const std::string c_szLanguage = strContent.substr(0, size_t(position)); + countryIndex = BYTE(atoi(c_szLanguage.c_str())); + if (countryIndex > 11 || countryIndex == 0) + countryIndex = 1; + strContent = strContent.substr(size_t(position + 1), strContent.length()); + } + const std::string isEmpireFlag("|empire|"); + position = int(strContent.find(isEmpireFlag)); + if (position != int(std::string::npos)) + { + strContent = strContent.substr(position + isEmpireFlag.length(), strContent.length()); + position = int(strContent.find("|")); + const std::string c_szEmpire = strContent.substr(0, size_t(position)); + empireIndex = BYTE(atoi(c_szEmpire.c_str())); + strContent = strContent.substr(size_t(position + 1), strContent.length()); + } + } + + for (auto it = m_ChatLineNewDeque.begin(); it != m_ChatLineNewDeque.end(); ++it) + { + SChatLine* pChatLine = SChatLine::New(); + + pChatLine->empireIndex = empireIndex; + pChatLine->countryIndex = countryIndex; + if (iType == CHAT_TYPE_SHOUT) + SetShoutFlags(pChatLine); + + pChatLine->text = strContent; + pChatLine->iType = iType; + pChatLine->Instance.SetValue(strContent.c_str()); + pChatLine->fAppendedTime = GetGlobalTime(); + pChatLine->SetColorAll(GetChatColor(iType)); + it->second.push_back(pChatLine); + if (it->second.size() > CHAT_LINE_MAX_NUM) + { + SChatLine* pFrontLine = it->second.front(); + SChatLine::Delete(pFrontLine); + it->second.pop_front(); + } + auto itChatSet = m_ChatSetMap.find(it->first); + if (itChatSet != m_ChatSetMap.end()) + { + TChatSet* pChatSet = &(itChatSet->second); + if (BOARD_STATE_EDIT == pChatSet->m_iBoardState) + ArrangeShowingChat(itChatSet->first); + else + { + pChatSet->m_ShowingChatLineList.push_back(pChatLine); + if (pChatSet->m_ShowingChatLineList.size() > CHAT_LINE_MAX_NUM) + pChatSet->m_ShowingChatLineList.pop_front(); + ArrangeShowingChat(itChatSet->first); + } + } + } +} + +void CPythonChat::AppendChatWithDelay(int iType, const char* c_szChat, int iDelay) +{ + TWaitChat WaitChat; + WaitChat.iType = iType; + WaitChat.strChat = c_szChat; + WaitChat.dwAppendingTime = GetCurrentMillisecond() + iDelay; + m_WaitChatList.push_back(WaitChat); +} + +DWORD CPythonChat::GetChatColor(int iType) +{ + if (iType < CHAT_TYPE_MAX_NUM) + return m_akD3DXClrChat[iType]; + + return D3DXCOLOR(0.0f, 0.0f, 1.0f, 1.0f); +} + +void CPythonChat::IgnoreCharacter(const char* c_szName) +{ + TIgnoreCharacterSet::iterator itor = m_IgnoreCharacterSet.find(c_szName); + if (m_IgnoreCharacterSet.end() != itor) + m_IgnoreCharacterSet.erase(itor); + else + m_IgnoreCharacterSet.insert(c_szName); +} + +BOOL CPythonChat::IsIgnoreCharacter(const char* c_szName) +{ + return m_IgnoreCharacterSet.find(c_szName) != m_IgnoreCharacterSet.end() ? TRUE : FALSE; +} + +CWhisper* CPythonChat::CreateWhisper(const char* c_szName) +{ + CWhisper* pWhisper = CWhisper::New(); + m_WhisperMap.insert(TWhisperMap::value_type(c_szName, pWhisper)); + return pWhisper; +} + +void CPythonChat::AppendWhisper(int iType, const char* c_szName, const char* c_szChat) +{ + TWhisperMap::iterator itor = m_WhisperMap.find(c_szName); + + CWhisper* pWhisper; + if (itor == m_WhisperMap.end()) + { + pWhisper = CreateWhisper(c_szName); + pWhisper->lineCount = 0; + } + else + { + pWhisper = itor->second; + } + + pWhisper->AppendChat(iType, c_szChat); + ++pWhisper->lineCount; +} + +void CPythonChat::ClearWhisper(const char* c_szName) +{ + TWhisperMap::iterator itor = m_WhisperMap.find(c_szName); + + if (itor != m_WhisperMap.end()) + { + CWhisper::Delete(itor->second); + m_WhisperMap.erase(itor); + } +} + +BOOL CPythonChat::GetWhisper(const char* c_szName, CWhisper** ppWhisper) +{ + TWhisperMap::iterator itor = m_WhisperMap.find(c_szName); + + if (itor == m_WhisperMap.end()) + return FALSE; + + *ppWhisper = itor->second; + if (itor->second->lineCount > 0) + itor->second->lineCount = 0; + return TRUE; +} + +void CPythonChat::RenderWhisper(const char* c_szName, float fx, float fy) +{ + CWhisper* pWhisper; + if (GetWhisper(c_szName, &pWhisper)) + pWhisper->Render(fx, fy); +} + +void CPythonChat::InitWhisper(PyObject* ppyObject) +{ + for (TWhisperMap::iterator itor = m_WhisperMap.begin(); itor != m_WhisperMap.end(); ++itor) + { + const std::string strName = itor->first; + PyCallClassMemberFunc(ppyObject, "MakeWhisperButton", Py_BuildValue("(s)", strName.c_str())); + } +} + +void CPythonChat::__DestroyWhisperMap() +{ + for (TWhisperMap::iterator itor = m_WhisperMap.begin(); itor != m_WhisperMap.end(); ++itor) + CWhisper::Delete(itor->second); + m_WhisperMap.clear(); +} + +void CPythonChat::Close() +{ + for (TChatSetMap::iterator itor = m_ChatSetMap.begin(); itor != m_ChatSetMap.end(); ++itor) + { + TChatLineList* pLineList = &(itor->second.m_ShowingChatLineList); + for (TChatLineList::iterator line = pLineList->begin(); line != pLineList->end(); ++line) + (*line)->fAppendedTime = 0.0f; + } +} + +void CPythonChat::Destroy() +{ + __DestroyWhisperMap(); + + m_ShowingChatLineList.clear(); + m_ChatSetMap.clear(); + m_ChatLineDeque.clear(); + m_ChatLineNewDeque.clear(); + // Not in CPythonChat::Destroy: the delayed lines and ignore set outlive Clear() on Windows too, + // so they are left alone here. + SChatLine::DestroySystem(); + CWhisper::DestroySystem(); + + __Initialize(); +} + +void CPythonChat::__Initialize() +{ + m_akD3DXClrChat[CHAT_TYPE_TALKING] = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_INFO] = D3DXCOLOR(1.0f, 0.785f, 0.785f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_NOTICE] = D3DXCOLOR(1.0f, 0.902f, 0.730f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_PARTY] = D3DXCOLOR(0.542f, 1.0f, 0.949f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_GUILD] = D3DXCOLOR(0.906f, 0.847f, 1.0f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_COMMAND] = D3DXCOLOR(0.658f, 1.0f, 0.835f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_SHOUT] = D3DXCOLOR(0.658f, 1.0f, 0.835f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_WHISPER] = D3DXCOLOR(DWORD(0xff4AE14A)); + m_akD3DXClrChat[CHAT_TYPE_BIG_NOTICE] = D3DXCOLOR(1.0f, 0.902f, 0.730f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_MONARCH_NOTICE] = D3DXCOLOR(1.0f, 0.902f, 0.730f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_DICE_INFO] = D3DXCOLOR(DWORD(0xFFcc00cc)); + m_akD3DXClrChat[CHAT_TYPE_MISSION] = D3DXCOLOR(1.0f, 0.902f, 0.730f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_EXP_INFO] = D3DXCOLOR(1.0f, 0.785f, 0.785f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_ITEM_INFO] = D3DXCOLOR(1.0f, 0.785f, 0.785f, 1.0f); + m_akD3DXClrChat[CHAT_TYPE_MONEY_INFO] = D3DXCOLOR(1.0f, 0.785f, 0.785f, 1.0f); + + TChatLineDeque map_vec; + m_ChatLineNewDeque.emplace(0, map_vec); + m_ChatLineNewDeque.emplace(1, map_vec); + m_ChatSetMap.emplace(0, TChatSet()); // normal chat + m_ChatSetMap.emplace(1, TChatSet()); // log chat +} + +CPythonChat::CPythonChat() +{ + __Initialize(); +} + +DWORD CPythonChat::GetNewChatCount() +{ + DWORD count = 0; + for (TWhisperMap::iterator itor = m_WhisperMap.begin(); itor != m_WhisperMap.end(); ++itor) + count += itor->second->lineCount; + return count; +} + +void CPythonChat::DeleteChatSet(DWORD dwID) +{ + auto it = m_ChatSetMap.find(int(dwID)); + if (it != m_ChatSetMap.end()) + m_ChatSetMap.erase(it); + + auto itChat = m_ChatLineNewDeque.find(BYTE(dwID)); + if (itChat != m_ChatLineNewDeque.end()) + { + for (SChatLine* chatLine : itChat->second) + SChatLine::Delete(chatLine); + itChat->second.clear(); + m_ChatLineNewDeque.erase(itChat); + } +} + +void CPythonChat::EnableCountryMode(DWORD dwID, int iMode) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + if (iMode >= 0 && size_t(iMode) < pChatSet->m_iCountryMode.size()) + pChatSet->m_iCountryMode[iMode] = TRUE; + ArrangeShowingChat(dwID); +} + +void CPythonChat::DisableCountryMode(DWORD dwID, int iMode) +{ + TChatSet* pChatSet = GetChatSetPtr(dwID); + if (!pChatSet) + return; + + if (iMode >= 0 && size_t(iMode) < pChatSet->m_iCountryMode.size()) + pChatSet->m_iCountryMode[iMode] = FALSE; + ArrangeShowingChat(dwID); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +CDynamicPool CWhisper::ms_kPool; + +CWhisper* CWhisper::New() +{ + return ms_kPool.Alloc(); +} + +void CWhisper::Delete(CWhisper* pkWhisper) +{ + pkWhisper->Destroy(); + ms_kPool.Free(pkWhisper); +} + +void CWhisper::DestroySystem() +{ + ms_kPool.Destroy(); + + SChatLine::DestroySystem(); +} + +void CWhisper::SetPosition(float fPosition) +{ + m_fcurPosition = fPosition; + __ArrangeChat(); +} + +void CWhisper::SetBoxSize(float fWidth, float fHeight) +{ + m_fWidth = fWidth; + m_fHeight = fHeight; + + for (TChatLineDeque::iterator itor = m_ChatLineDeque.begin(); itor != m_ChatLineDeque.end(); ++itor) + (*itor)->Instance.SetLimitWidth(fWidth); +} + +void CWhisper::AppendChat(int iType, const char* c_szChat) +{ + SChatLine* pChatLine = SChatLine::New(); + pChatLine->Instance.SetValue(c_szChat); + pChatLine->Instance.SetLimitWidth(m_fWidth); + pChatLine->Instance.SetMultiLine(TRUE); + + switch (iType) + { + case CPythonChat::WHISPER_TYPE_SYSTEM: + pChatLine->Instance.SetColor(D3DXCOLOR(1.0f, 0.785f, 0.785f, 1.0f)); + break; + case CPythonChat::WHISPER_TYPE_GM: + pChatLine->Instance.SetColor(D3DXCOLOR(1.0f, 0.632f, 0.0f, 1.0f)); + break; + case CPythonChat::WHISPER_TYPE_CHAT: + default: + pChatLine->Instance.SetColor(D3DXCOLOR(DWORD(0xffffffff))); + break; + } + + m_ChatLineDeque.push_back(pChatLine); + + __ArrangeChat(); +} + +void CWhisper::__ArrangeChat() +{ + for (TChatLineDeque::iterator itor = m_ChatLineDeque.begin(); itor != m_ChatLineDeque.end(); ++itor) + (*itor)->Instance.Update(); +} + +void CWhisper::Render(float fx, float fy) +{ + float fHeight = fy + m_fHeight; + + const int iViewCount = int(m_fHeight / m_fLineStep) - 1; + const int iLineCount = int(m_ChatLineDeque.size()); + int iStartLine = -1; + if (iLineCount > iViewCount) + iStartLine = int(float(iLineCount - iViewCount) * m_fcurPosition) + iViewCount - 1; + else if (!m_ChatLineDeque.empty()) + iStartLine = iLineCount - 1; + + const RECT Rect = { LONG(fx), LONG(fy), LONG(fx + m_fWidth), LONG(fy + m_fHeight) }; + + // The Windows assert(i < size) is compiled out; a position above 1.0 starts past the end. + iStartLine = std::min(iStartLine, iLineCount - 1); + for (int i = iStartLine; i >= 0; --i) + { + TChatLine* pChatLine = m_ChatLineDeque[i]; + + const WORD wLineCount = WORD(pChatLine->Instance.GetTextLineCount()); + fHeight -= wLineCount * m_fLineStep; + + pChatLine->Instance.SetPosition(fx, fHeight); + pChatLine->Instance.Render(&Rect); + + if (fHeight < fy) + break; + } +} + +void CWhisper::__Initialize() +{ + m_fLineStep = 15.0f; + m_fWidth = 300.0f; + m_fHeight = 120.0f; + m_fcurPosition = 1.0f; +} + +void CWhisper::Destroy() +{ + std::for_each(m_ChatLineDeque.begin(), m_ChatLineDeque.end(), SChatLine::Delete); + m_ChatLineDeque.clear(); + m_ShowingChatLineList.clear(); +} + +// lineCount is left uninitialised by Windows for chat.CreateWhisper; it starts at 0 here. +CWhisper::CWhisper() : lineCount(0) +{ + __Initialize(); +} + +CWhisper::~CWhisper() +{ + Destroy(); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// + +CDynamicPool CWhisper::SChatLine::ms_kPool; + +CWhisper::SChatLine* CWhisper::SChatLine::New() +{ + return ms_kPool.Alloc(); +} + +void CWhisper::SChatLine::Delete(CWhisper::SChatLine* pkChatLine) +{ + pkChatLine->Instance.Destroy(); + ms_kPool.Free(pkChatLine); +} + +void CWhisper::SChatLine::DestroySystem() +{ + ms_kPool.Destroy(); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// PythonChatModule.cpp + +namespace { + +PyObject* chatSetChatColor(PyObject*, PyObject* poArgs) +{ + int iType; + if (!PyTuple_GetInteger(poArgs, 0, &iType)) + return Py_BuildException(); + int r; + if (!PyTuple_GetInteger(poArgs, 1, &r)) + return Py_BuildException(); + int g; + if (!PyTuple_GetInteger(poArgs, 2, &g)) + return Py_BuildException(); + int b; + if (!PyTuple_GetInteger(poArgs, 3, &b)) + return Py_BuildException(); + + CPythonChat::Instance().SetChatColor(iType, r, g, b); + return Py_BuildNone(); +} + +PyObject* chatClear(PyObject*, PyObject*) +{ + CPythonChat::Instance().Destroy(); + return Py_BuildNone(); +} + +PyObject* chatClose(PyObject*, PyObject*) +{ + CPythonChat::Instance().Close(); + return Py_BuildNone(); +} + +PyObject* chatCreateChatSet(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + return Py_BuildValue("i", CPythonChat::Instance().CreateChatSet(iID)); +} + +PyObject* chatUpdate(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + CPythonChat::Instance().Update(iID); + return Py_BuildNone(); +} + +PyObject* chatRender(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + CPythonChat::Instance().Render(iID); + return Py_BuildNone(); +} + +PyObject* chatSetBoardState(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int iState; + if (!PyTuple_GetInteger(poArgs, 1, &iState)) + return Py_BuildException(); + + CPythonChat::Instance().SetBoardState(iID, iState); + return Py_BuildNone(); +} + +PyObject* chatSetPosition(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int ix; + if (!PyTuple_GetInteger(poArgs, 1, &ix)) + return Py_BuildException(); + int iy; + if (!PyTuple_GetInteger(poArgs, 2, &iy)) + return Py_BuildException(); + + CPythonChat::Instance().SetPosition(iID, ix, iy); + return Py_BuildNone(); +} + +PyObject* chatSetHeight(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int iHeight; + if (!PyTuple_GetInteger(poArgs, 1, &iHeight)) + return Py_BuildException(); + + CPythonChat::Instance().SetHeight(iID, iHeight); + return Py_BuildNone(); +} + +PyObject* chatSetStep(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int iStep; + if (!PyTuple_GetInteger(poArgs, 1, &iStep)) + return Py_BuildException(); + + CPythonChat::Instance().SetStep(iID, iStep); + return Py_BuildNone(); +} + +PyObject* chatToggleChatMode(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int iType; + if (!PyTuple_GetInteger(poArgs, 1, &iType)) + return Py_BuildException(); + + CPythonChat::Instance().ToggleChatMode(iID, iType); + return Py_BuildNone(); +} + +PyObject* chatEnableChatMode(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int iType; + if (!PyTuple_GetInteger(poArgs, 1, &iType)) + return Py_BuildException(); + + CPythonChat::Instance().EnableChatMode(iID, iType); + return Py_BuildNone(); +} + +PyObject* chatDisableChatMode(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int iType; + if (!PyTuple_GetInteger(poArgs, 1, &iType)) + return Py_BuildException(); + + CPythonChat::Instance().DisableChatMode(iID, iType); + return Py_BuildNone(); +} + +PyObject* chatSetEndPos(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + float fPos; + if (!PyTuple_GetFloat(poArgs, 1, &fPos)) + return Py_BuildException(); + + CPythonChat::Instance().SetEndPos(iID, fPos); + return Py_BuildNone(); +} + +PyObject* chatGetLineCount(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + return Py_BuildValue("i", CPythonChat::Instance().GetLineCount(iID)); +} + +PyObject* chatGetVisibleLineCount(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + return Py_BuildValue("i", CPythonChat::Instance().GetVisibleLineCount(iID)); +} + +PyObject* chatGetLineStep(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + return Py_BuildValue("i", CPythonChat::Instance().GetLineStep(iID)); +} + +PyObject* chatAppendChat(PyObject*, PyObject* poArgs) +{ + int iType; + if (!PyTuple_GetInteger(poArgs, 0, &iType)) + return Py_BuildException(); + char* szChat; + if (!PyTuple_GetString(poArgs, 1, &szChat)) + return Py_BuildException(); + + CPythonChat::Instance().AppendChat(iType, szChat); + return Py_BuildNone(); +} + +PyObject* chatAppendChatWithDelay(PyObject*, PyObject* poArgs) +{ + int iType; + if (!PyTuple_GetInteger(poArgs, 0, &iType)) + return Py_BuildException(); + char* szChat; + if (!PyTuple_GetString(poArgs, 1, &szChat)) + return Py_BuildException(); + int iDelay; + if (!PyTuple_GetInteger(poArgs, 2, &iDelay)) + return Py_BuildException(); + + CPythonChat::Instance().AppendChatWithDelay(iType, szChat, iDelay); + return Py_BuildNone(); +} + +PyObject* chatArrangeShowingChat(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + CPythonChat::Instance().ArrangeShowingChat(iID); + return Py_BuildNone(); +} + +PyObject* chatIgnoreCharacter(PyObject*, PyObject* poArgs) +{ + char* szName; + if (!PyTuple_GetString(poArgs, 0, &szName)) + return Py_BuildException(); + + CPythonChat::Instance().IgnoreCharacter(szName); + return Py_BuildNone(); +} + +// Windows discards the result and returns None. +PyObject* chatIsIgnoreCharacter(PyObject*, PyObject* poArgs) +{ + char* szName; + if (!PyTuple_GetString(poArgs, 0, &szName)) + return Py_BuildException(); + + CPythonChat::Instance().IsIgnoreCharacter(szName); + return Py_BuildNone(); +} + +PyObject* chatCreateWhisper(PyObject*, PyObject* poArgs) +{ + char* szName; + if (!PyTuple_GetString(poArgs, 0, &szName)) + return Py_BuildException(); + + CPythonChat::Instance().CreateWhisper(szName); + return Py_BuildNone(); +} + +PyObject* chatAppendWhisper(PyObject*, PyObject* poArgs) +{ + int iType; + if (!PyTuple_GetInteger(poArgs, 0, &iType)) + return Py_BuildException(); + char* szName; + if (!PyTuple_GetString(poArgs, 1, &szName)) + return Py_BuildException(); + char* szChat; + if (!PyTuple_GetString(poArgs, 2, &szChat)) + return Py_BuildException(); + + CPythonChat::Instance().AppendWhisper(iType, szName, szChat); + return Py_BuildNone(); +} + +PyObject* chatRenderWhisper(PyObject*, PyObject* poArgs) +{ + char* szName; + if (!PyTuple_GetString(poArgs, 0, &szName)) + return Py_BuildException(); + float fx; + if (!PyTuple_GetFloat(poArgs, 1, &fx)) + return Py_BuildException(); + float fy; + if (!PyTuple_GetFloat(poArgs, 2, &fy)) + return Py_BuildException(); + + CPythonChat::Instance().RenderWhisper(szName, fx, fy); + return Py_BuildNone(); +} + +PyObject* chatSetWhisperBoxSize(PyObject*, PyObject* poArgs) +{ + char* szName; + if (!PyTuple_GetString(poArgs, 0, &szName)) + return Py_BuildException(); + float fWidth; + if (!PyTuple_GetFloat(poArgs, 1, &fWidth)) + return Py_BuildException(); + float fHeight; + if (!PyTuple_GetFloat(poArgs, 2, &fHeight)) + return Py_BuildException(); + + CWhisper* pWhisper; + if (CPythonChat::Instance().GetWhisper(szName, &pWhisper)) + pWhisper->SetBoxSize(fWidth, fHeight); + return Py_BuildNone(); +} + +PyObject* chatSetWhisperPosition(PyObject*, PyObject* poArgs) +{ + char* szName; + if (!PyTuple_GetString(poArgs, 0, &szName)) + return Py_BuildException(); + float fPosition; + if (!PyTuple_GetFloat(poArgs, 1, &fPosition)) + return Py_BuildException(); + + CWhisper* pWhisper; + if (CPythonChat::Instance().GetWhisper(szName, &pWhisper)) + pWhisper->SetPosition(fPosition); + return Py_BuildNone(); +} + +PyObject* chatClearWhisper(PyObject*, PyObject* poArgs) +{ + char* szName; + if (!PyTuple_GetString(poArgs, 0, &szName)) + return Py_BuildException(); + + CPythonChat::Instance().ClearWhisper(szName); + return Py_BuildNone(); +} + +PyObject* chatInitWhisper(PyObject*, PyObject* poArgs) +{ + PyObject* poInterface; + if (!PyTuple_GetObject(poArgs, 0, &poInterface)) + return Py_BuildException(); + + CPythonChat::Instance().InitWhisper(poInterface); + return Py_BuildNone(); +} + +PyObject* chatGetLinkFromHyperlink(PyObject*, PyObject* poArgs) +{ + char* szHyperlink; + if (!PyTuple_GetString(poArgs, 0, &szHyperlink)) + return Py_BuildException(); + + std::string stHyperlink(szHyperlink); + std::vector results; + split_string(stHyperlink, ":", results, false); + + // A link without ':' leaves results empty; Windows reads results[0] regardless. + if (!results.empty() && 0 == results[0].compare("item")) + { + if (results.size() < 6) + return Py_BuildValue("s", ""); + + std::string strName; + if (GetItemName(uint32_t(htoi(results[1].c_str())), &strName)) + { + char buf[1024] = { 0 }; + char itemlink[256]; + int len; + bool isAttr = false; + + len = snprintf(itemlink, sizeof(itemlink), "item:%x:%x:%x:%x:%x", + htoi(results[1].c_str()), + htoi(results[2].c_str()), + htoi(results[3].c_str()), + htoi(results[4].c_str()), + htoi(results[5].c_str())); + + if (results.size() >= 8) + { + // An odd attribute count reads past results on Windows; the missing value is 0. + for (size_t i = 6; i < results.size(); i += 2) + { + if (len >= int(sizeof(itemlink))) + break; + len += snprintf(itemlink + len, sizeof(itemlink) - len, ":%x:%d", + htoi(results[i].c_str()), + i + 1 < results.size() ? atoi(results[i + 1].c_str()) : 0); + isAttr = true; + } + } + + if (isAttr) + snprintf(buf, sizeof(buf), "|cffffc700|H%s|h[%s]|h|r", itemlink, strName.c_str()); + else + snprintf(buf, sizeof(buf), "|cfff1e6c0|H%s|h[%s]|h|r", itemlink, strName.c_str()); + + return Py_BuildValue("s", buf); + } + } + + return Py_BuildValue("s", ""); +} + +PyObject* chatDeleteChatSet(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + CPythonChat::Instance().DeleteChatSet(iID); + return Py_BuildNone(); +} + +PyObject* chatEnableCountryMode(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int iType; + if (!PyTuple_GetInteger(poArgs, 1, &iType)) + return Py_BuildException(); + + CPythonChat::Instance().EnableCountryMode(iID, iType); + return Py_BuildNone(); +} + +PyObject* chatDisableCountryMode(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + int iType; + if (!PyTuple_GetInteger(poArgs, 1, &iType)) + return Py_BuildException(); + + CPythonChat::Instance().DisableCountryMode(iID, iType); + return Py_BuildNone(); +} + +} // namespace + +void initChat() +{ + static PyMethodDef s_methods[] = + { + { "SetChatColor", chatSetChatColor, METH_VARARGS, nullptr }, + { "Clear", chatClear, METH_VARARGS, nullptr }, + { "Close", chatClose, METH_VARARGS, nullptr }, + + { "CreateChatSet", chatCreateChatSet, METH_VARARGS, nullptr }, + { "Update", chatUpdate, METH_VARARGS, nullptr }, + { "Render", chatRender, METH_VARARGS, nullptr }, + + { "SetBoardState", chatSetBoardState, METH_VARARGS, nullptr }, + { "SetPosition", chatSetPosition, METH_VARARGS, nullptr }, + { "SetHeight", chatSetHeight, METH_VARARGS, nullptr }, + { "SetStep", chatSetStep, METH_VARARGS, nullptr }, + { "ToggleChatMode", chatToggleChatMode, METH_VARARGS, nullptr }, + { "EnableChatMode", chatEnableChatMode, METH_VARARGS, nullptr }, + { "DisableChatMode", chatDisableChatMode, METH_VARARGS, nullptr }, + { "SetEndPos", chatSetEndPos, METH_VARARGS, nullptr }, + + { "GetLineCount", chatGetLineCount, METH_VARARGS, nullptr }, + { "GetVisibleLineCount", chatGetVisibleLineCount, METH_VARARGS, nullptr }, + { "GetLineStep", chatGetLineStep, METH_VARARGS, nullptr }, + + // Chat + { "AppendChat", chatAppendChat, METH_VARARGS, nullptr }, + { "AppendChatWithDelay", chatAppendChatWithDelay, METH_VARARGS, nullptr }, + { "ArrangeShowingChat", chatArrangeShowingChat, METH_VARARGS, nullptr }, + + // Ignore + { "IgnoreCharacter", chatIgnoreCharacter, METH_VARARGS, nullptr }, + { "IsIgnoreCharacter", chatIsIgnoreCharacter, METH_VARARGS, nullptr }, + + // Whisper + { "CreateWhisper", chatCreateWhisper, METH_VARARGS, nullptr }, + { "AppendWhisper", chatAppendWhisper, METH_VARARGS, nullptr }, + { "RenderWhisper", chatRenderWhisper, METH_VARARGS, nullptr }, + { "SetWhisperBoxSize", chatSetWhisperBoxSize, METH_VARARGS, nullptr }, + { "SetWhisperPosition", chatSetWhisperPosition, METH_VARARGS, nullptr }, + { "ClearWhisper", chatClearWhisper, METH_VARARGS, nullptr }, + { "InitWhisper", chatInitWhisper, METH_VARARGS, nullptr }, + + // Link + { "GetLinkFromHyperlink", chatGetLinkFromHyperlink, METH_VARARGS, nullptr }, + { "DeleteChatSet", chatDeleteChatSet, METH_VARARGS, nullptr }, + { "EnableCountryMode", chatEnableCountryMode, METH_VARARGS, nullptr }, + { "DisableCountryMode", chatDisableCountryMode, METH_VARARGS, nullptr }, + + { nullptr, nullptr, 0, nullptr }, + }; + + PyObject* poModule = Py_InitModule("chat", s_methods); + + PyModule_AddIntConstant(poModule, "CHAT_TYPE_TALKING", CPythonChat::CHAT_TYPE_TALKING); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_INFO", CPythonChat::CHAT_TYPE_INFO); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_NOTICE", CPythonChat::CHAT_TYPE_NOTICE); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_PARTY", CPythonChat::CHAT_TYPE_PARTY); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_GUILD", CPythonChat::CHAT_TYPE_GUILD); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_COMMAND", CPythonChat::CHAT_TYPE_COMMAND); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_SHOUT", CPythonChat::CHAT_TYPE_SHOUT); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_WHISPER", CPythonChat::CHAT_TYPE_WHISPER); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_BIG_NOTICE", CPythonChat::CHAT_TYPE_BIG_NOTICE); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_MONARCH_NOTICE", CPythonChat::CHAT_TYPE_MONARCH_NOTICE); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_DICE_INFO", CPythonChat::CHAT_TYPE_DICE_INFO); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_EXP_INFO", CPythonChat::CHAT_TYPE_EXP_INFO); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_ITEM_INFO", CPythonChat::CHAT_TYPE_ITEM_INFO); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_MONEY_INFO", CPythonChat::CHAT_TYPE_MONEY_INFO); + PyModule_AddIntConstant(poModule, "CHAT_TYPE_MISSION", CPythonChat::CHAT_TYPE_MISSION); + + PyModule_AddIntConstant(poModule, "WHISPER_TYPE_CHAT", CPythonChat::WHISPER_TYPE_CHAT); + PyModule_AddIntConstant(poModule, "WHISPER_TYPE_SYSTEM", CPythonChat::WHISPER_TYPE_SYSTEM); + PyModule_AddIntConstant(poModule, "WHISPER_TYPE_GM", CPythonChat::WHISPER_TYPE_GM); + + PyModule_AddIntConstant(poModule, "BOARD_STATE_VIEW", CPythonChat::BOARD_STATE_VIEW); + PyModule_AddIntConstant(poModule, "BOARD_STATE_EDIT", CPythonChat::BOARD_STATE_EDIT); + PyModule_AddIntConstant(poModule, "BOARD_STATE_LOG", CPythonChat::BOARD_STATE_LOG); + + PyModule_AddIntConstant(poModule, "CHAT_SET_CHAT_WINDOW", 0); + PyModule_AddIntConstant(poModule, "CHAT_SET_LOG_WINDOW", 1); +} + +} // namespace ava2 diff --git a/src/python_chat.h b/src/python_chat.h new file mode 100644 index 00000000..620a9214 --- /dev/null +++ b/src/python_chat.h @@ -0,0 +1,307 @@ +#pragma once +// CPythonChat / CWhisper: the chat line store behind the "chat" module and the server chat path. +// Provenance: AVA2 UserInterface/PythonChat.{h,cpp} and PythonChatModule.cpp, compiled with +// __CHAT_SETTINGS__, ENABLE_MULTILANGUAGE_SYSTEM, ENABLE_DICE_SYSTEM, dracaryS_DUNGEON_LIB and +// ENABLE_DISCORD_STUFF (Locale_inc.h); LINK_IN_CHAT is off. +#include "eter_ui/PythonWindow.h" +#include "eter_image/GrpImageInstance.h" +#include "shared/common/DynamicPool.h" +#include +#include +#include +#include +#include +#include +#include + +namespace ava2 { + +class CWhisper +{ +public: + typedef UI::CGraphicTextInstance CGraphicTextInstance; + + typedef struct SChatLine + { + CGraphicTextInstance Instance; + + SChatLine() {} + ~SChatLine() { Instance.Destroy(); } + + static void DestroySystem(); + + static SChatLine* New(); + static void Delete(SChatLine* pkChatLine); + + static CDynamicPool ms_kPool; + } TChatLine; + + typedef std::deque TChatLineDeque; + typedef std::list TChatLineList; + +public: + CWhisper(); + ~CWhisper(); + + void Destroy(); + + void SetPosition(float fPosition); + void SetBoxSize(float fWidth, float fHeight); + void AppendChat(int iType, const char* c_szChat); + void Render(float fx, float fy); + DWORD lineCount; + + // Test access. + const TChatLineDeque& GetLines() const { return m_ChatLineDeque; } + float GetWidth() const { return m_fWidth; } + float GetHeight() const { return m_fHeight; } + float GetCurPosition() const { return m_fcurPosition; } + +protected: + void __Initialize(); + void __ArrangeChat(); + +protected: + float m_fLineStep; + float m_fWidth; + float m_fHeight; + float m_fcurPosition; + + TChatLineDeque m_ChatLineDeque; + TChatLineList m_ShowingChatLineList; + +public: + static void DestroySystem(); + + static CWhisper* New(); + static void Delete(CWhisper* pkWhisper); + + static CDynamicPool ms_kPool; +}; + +class CPythonChat +{ +public: + typedef UI::CGraphicTextInstance CGraphicTextInstance; + + enum EChatType + { + CHAT_TYPE_TALKING, + CHAT_TYPE_INFO, + CHAT_TYPE_NOTICE, + CHAT_TYPE_PARTY, + CHAT_TYPE_GUILD, + CHAT_TYPE_COMMAND, + CHAT_TYPE_SHOUT, + CHAT_TYPE_WHISPER, + CHAT_TYPE_BIG_NOTICE, + CHAT_TYPE_MONARCH_NOTICE, + CHAT_TYPE_DICE_INFO, + CHAT_TYPE_EXP_INFO, + CHAT_TYPE_ITEM_INFO, + CHAT_TYPE_MONEY_INFO, + CHAT_TYPE_MISSION, + CHAT_TYPE_MAX_NUM, + }; + + enum EWhisperType + { + WHISPER_TYPE_CHAT = 0, + WHISPER_TYPE_NOT_EXIST = 1, + WHISPER_TYPE_TARGET_BLOCKED = 2, + WHISPER_TYPE_SENDER_BLOCKED = 3, + WHISPER_TYPE_ERROR = 4, + WHISPER_TYPE_GM = 5, + WHISPER_TYPE_SYSTEM = 0xFF + }; + + enum EBoardState + { + BOARD_STATE_VIEW, + BOARD_STATE_EDIT, + BOARD_STATE_LOG, + }; + + enum + { + CHAT_LINE_MAX_NUM = 300, + CHAT_LINE_COLOR_ARRAY_MAX_NUM = 3, + }; + + typedef struct SChatLine + { + int iType; + float fAppendedTime; + D3DXCOLOR aColor[CHAT_LINE_COLOR_ARRAY_MAX_NUM]; + CGraphicTextInstance Instance; + CGraphicImageInstance InstanceLang; + CGraphicImageInstance InstanceEmpire; + SChatLine(); + virtual ~SChatLine(); + BYTE countryIndex; + BYTE empireIndex; + std::string text; + void SetColor(DWORD dwID, DWORD dwColor); + void SetColorAll(DWORD dwColor); + D3DXCOLOR& GetColorRef(DWORD dwID); + static void DestroySystem(); + + static SChatLine* New(); + static void Delete(SChatLine* pkChatLine); + + static CDynamicPool ms_kPool; + } TChatLine; + + typedef struct SWaitChat + { + int iType; + std::string strChat; + + DWORD dwAppendingTime; + } TWaitChat; + + typedef std::deque TChatLineDeque; + typedef std::list TChatLineList; + + typedef std::map TWhisperMap; + typedef std::set TIgnoreCharacterSet; + typedef std::list TWaitChatList; + + typedef struct SChatSet + { + int m_ix; + int m_iy; + int m_iHeight; + int m_iStep; + float m_fEndPos; + + int m_iBoardState; + std::vector m_iMode; + + TChatLineList m_ShowingChatLineList; + std::vector m_iCountryMode; + bool CheckCountryMode(DWORD dwType) + { + if (dwType >= m_iCountryMode.size()) + return false; + return m_iCountryMode[dwType] ? true : false; + } + bool CheckMode(DWORD dwType) + { + if (dwType >= m_iMode.size()) + return false; + + return m_iMode[dwType] ? true : false; + } + + SChatSet() + { + m_iBoardState = BOARD_STATE_VIEW; + + m_ix = 0; + m_iy = 0; + m_fEndPos = 1.0f; + m_iHeight = 0; + m_iStep = 15; + + m_iMode.clear(); + m_iMode.resize(ms_iChatModeSize, 1); + m_iCountryMode.clear(); + m_iCountryMode.resize(15, 1); + } + + static int ms_iChatModeSize; + } TChatSet; + + typedef std::map TChatSetMap; + +public: + static CPythonChat& Instance(); + + void SetChatColor(UINT eType, UINT r, UINT g, UINT b); + + void Destroy(); + void Close(); + DWORD GetNewChatCount(); + int CreateChatSet(DWORD dwID); + void Update(DWORD dwID); + void Render(DWORD dwID); + void RenderWhisper(const char* c_szName, float fx, float fy); + + void SetBoardState(DWORD dwID, int iState); + void SetPosition(DWORD dwID, int ix, int iy); + void SetHeight(DWORD dwID, int iHeight); + void SetStep(DWORD dwID, int iStep); + void ToggleChatMode(DWORD dwID, int iMode); + void EnableChatMode(DWORD dwID, int iMode); + void DisableChatMode(DWORD dwID, int iMode); + void SetEndPos(DWORD dwID, float fPos); + void DeleteChatSet(DWORD dwID); + void EnableCountryMode(DWORD dwID, int iMode); + void DisableCountryMode(DWORD dwID, int iMode); + int GetVisibleLineCount(DWORD dwID); + int GetEditableLineCount(DWORD dwID); + int GetLineCount(DWORD dwID); + int GetLineStep(DWORD dwID); + + // Chat + void AppendChat(int iType, const char* c_szChat); + void AppendChatWithDelay(int iType, const char* c_szChat, int iDelay); + void ArrangeShowingChat(DWORD dwID); + + // Ignore + void IgnoreCharacter(const char* c_szName); + BOOL IsIgnoreCharacter(const char* c_szName); + + // Whisper + CWhisper* CreateWhisper(const char* c_szName); + void AppendWhisper(int iType, const char* c_szName, const char* c_szChat); + void ClearWhisper(const char* c_szName); + BOOL GetWhisper(const char* c_szName, CWhisper** ppWhisper); + void InitWhisper(PyObject* ppyObject); + + // CTimer stand-in: 0 follows the real clock (CTimer with m_bUseRealTime); tests pin a value. + // GetGlobalTime is the same clock in seconds, as CPythonApplication samples it per frame. + void SetCurrentMillisecond(DWORD dwTime) { m_dwFixedMillisecond = dwTime; } + DWORD GetCurrentMillisecond() const; + float GetGlobalTime() const { return float(GetCurrentMillisecond()) / 1000.0f; } + + // Test access. + const TChatSet* GetChatSet(DWORD dwID) const; + const TChatLineDeque* GetChatLineDeque(DWORD dwID) const; + const TWhisperMap& GetWhisperMap() const { return m_WhisperMap; } + size_t GetWaitChatCount() const { return m_WaitChatList.size(); } + DWORD GetChatColorValue(int iType) { return GetChatColor(iType); } + +protected: + CPythonChat(); + + void __Initialize(); + void __DestroyWhisperMap(); + + TChatLineList* GetChatLineListPtr(DWORD dwID); + TChatSet* GetChatSetPtr(DWORD dwID); + + void UpdateViewMode(DWORD dwID); + void UpdateEditMode(DWORD dwID); + void UpdateLogMode(DWORD dwID); + + DWORD GetChatColor(int iType); + +protected: + TChatLineDeque m_ChatLineDeque; + TChatLineList m_ShowingChatLineList; + TChatSetMap m_ChatSetMap; + TWhisperMap m_WhisperMap; + TIgnoreCharacterSet m_IgnoreCharacterSet; + TWaitChatList m_WaitChatList; + + std::map m_ChatLineNewDeque; + D3DXCOLOR m_akD3DXClrChat[CHAT_TYPE_MAX_NUM]; + + DWORD m_dwFixedMillisecond = 0; +}; + +void initChat(); + +} // namespace ava2 diff --git a/src/python_chr.cpp b/src/python_chr.cpp new file mode 100644 index 00000000..41ae8309 --- /dev/null +++ b/src/python_chr.cpp @@ -0,0 +1,1483 @@ +// chr / chrmgr: 1:1 ports of AVA2 UserInterface/PythonCharacterModule.cpp (initchr) and +// PythonCharacterManagerModule.cpp (initchrmgr), compiled with the Locale_inc.h set RACE_HEIGHT, +// ENABLE_SASH_SYSTEM, ENABLE_MELEY_LAIR_DUNGEON and ENABLE_CONQUEROR_LEVEL on and NEW_PET_SYSTEM / +// WJ_COMBAT_ZONE off (so chr.RequestPetName and chrmgr.EFFECT_COMBAT_ZONE_POTION do not exist). +// CPythonCharacterManager / CInstanceBase are eter_net/NetworkActorManager, CRaceManager / CRaceData +// are eter_render/RaceData. Windows backends that are not ported (the pick pass, add/modulate/blend +// render modes, specular info, bounding spheres, weapon trace, the horse actor, the direction line) +// leave those calls as the original argument parsing only; docs/PORT-PLAN.md pass 25 lists them. +#include +#include "python_gameplay_modules.h" +#include "eter_net/NetworkActorManager.h" +#include "eter_render/RaceData.h" +#include "eter_render/TextTailManager.h" +#include "eter_render/Gr2ModelRenderer.h" +#include "eter_render/TerrainHeightmap.h" +#include "shared/common/PythonUtils.h" +#include +#include +#include +#include +#include +#include + +namespace ava2 { +namespace { + +// CActorInstance::EType +enum { TYPE_ENEMY = 0, TYPE_NPC = 1, TYPE_STONE = 2, TYPE_PC = 6 }; +// CRaceMotionData::MODE_HORSE +enum { MODE_HORSE = 9 }; + +NetworkActorManager& Mgr() { return NetworkActorManager::Instance(); } +SNetworkActorData* GetSelectedInstancePtr() { return Mgr().GetSelectedInstance(); } +SNetworkActorData* GetInstancePtr(int vid) { return Mgr().GetActorData(uint32_t(vid)); } + +// CInstanceBase::NEW_GetPixelPosition: the port's actor stores (x, height, y). +void GetPixelPosition(const SNetworkActorData& inst, float* x, float* y, float* z) { + if (inst.m_pActorInstance) { + *x = inst.m_pActorInstance->GetX(); *y = inst.m_pActorInstance->GetZ(); *z = inst.m_pActorInstance->GetY(); + } else { + *x = float(inst.m_lCurX); *y = float(inst.m_lCurY); *z = float(inst.m_lCurZ); + } +} +// CInstanceBase::NEW_SetPixelPosition (the text tail follows the graphic position on Windows). +void SetPixelPosition(SNetworkActorData& inst, float x, float y, float z) { + inst.m_lCurX = inst.m_lDstX = int32_t(x); + inst.m_lCurY = inst.m_lDstY = int32_t(y); + inst.m_lCurZ = int32_t(z); + if (inst.m_pActorInstance) inst.m_pActorInstance->SetPosition(x, z, y); + TextTailManager::Instance().SetCharacterPosition(inst.m_dwVID, x, z, y); +} +// CInstanceBase::__GetBackgroundHeight (0 without a map). +float GetBackgroundHeight(float x, float y) { + const TerrainHeightmap* terrain = GetActiveBackgroundTerrain(); + return terrain ? terrain->GetHeightAtWorld(x, y) : 0.0f; +} +// CInstanceBase::SetRotation: the graphic rotation is the actor yaw (AppendActor: SetYaw(m_fRot)). +void SetRotation(SNetworkActorData& inst, float rotation) { + inst.m_fRot = rotation; + if (inst.m_pActorInstance) inst.m_pActorInstance->SetYaw(rotation); +} +float GetRotation(const SNetworkActorData& inst) { + return inst.m_pActorInstance ? inst.m_pActorInstance->GetYaw() : inst.m_fRot; +} + +// CPythonCharacterManager::CreateInstance: RegisterInstance + CInstanceBase::Create. +void CreateInstance(SNetworkActorData& createData) { + if (Mgr().GetActorData(createData.m_dwVID)) { + std::cerr << "[AVA2 TraceError] CPythonCharacterManager::CreateInstance: VID[" << createData.m_dwVID << "] - ALREADY EXIST" << std::endl; + return; + } + createData.m_lCurZ = int32_t(GetBackgroundHeight(float(createData.m_lCurX), float(createData.m_lCurY))); + Mgr().AppendActor(createData); +} + +uint32_t ScriptVID(int vid) { return vid >= 0 ? uint32_t(vid) : 0xffffffffu; } +// CPythonCharacterManager::SetEmoticon / IsPossibleEmoticon: 0xffffffff is the selected instance. +SNetworkActorData* InstanceOrSelected(uint32_t vid) { + return vid == 0xffffffffu ? GetSelectedInstancePtr() : Mgr().GetActorData(vid); +} + +#define RACE_DATA_OR_EXCEPTION(name) \ + RaceData* name = RaceManager::Instance().GetSelectedRaceDataPointer(); \ + if (!name) return Py_BuildException("RaceData has not selected!") + +////////////////////////////////////////////////////////////////////////// +// chrmgr +////////////////////////////////////////////////////////////////////////// + +PyObject* chrmgrSetEmpireNameMode(PyObject*, PyObject* poArgs) { + int iEnable; + if (!PyTuple_GetInteger(poArgs, 0, &iEnable)) return Py_BadArgument(); + NetworkActorManager::SetEmpireNameMode(iEnable ? true : false); + Mgr().RefreshAllPCTextTail(); + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterTitleName(PyObject*, PyObject* poArgs) { + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) return Py_BadArgument(); + char* szTitleName; + if (!PyTuple_GetString(poArgs, 1, &szTitleName)) return Py_BadArgument(); + NetworkActorManager::RegisterTitleName(iIndex, szTitleName); + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterColor(PyObject* poArgs, bool isTitle) { + int index, ir, ig, ib; + if (!PyTuple_GetInteger(poArgs, 0, &index)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &ir)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 2, &ig)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 3, &ib)) return Py_BadArgument(); + if (isTitle) NetworkActorManager::RegisterTitleColor(unsigned(index), unsigned(ir), unsigned(ig), unsigned(ib)); + else NetworkActorManager::RegisterNameColor(unsigned(index), unsigned(ir), unsigned(ig), unsigned(ib)); + return Py_BuildNone(); +} +PyObject* chrmgrRegisterNameColor(PyObject*, PyObject* poArgs) { return chrmgrRegisterColor(poArgs, false); } +PyObject* chrmgrRegisterTitleColor(PyObject*, PyObject* poArgs) { return chrmgrRegisterColor(poArgs, true); } + +PyObject* chrmgrGetPickedVID(PyObject*, PyObject*) { + uint32_t dwPickedActorID; + if (Mgr().OLD_GetPickedInstanceVID(&dwPickedActorID)) return Py_BuildValue("i", dwPickedActorID); + return Py_BuildValue("i", -1); +} + +PyObject* chrmgrGetVIDInfo(PyObject*, PyObject* poArgs) { + int nVID; + if (!PyTuple_GetInteger(poArgs, 0, &nVID)) return Py_BadArgument(); + + char szDetail[256] = ""; + const SNetworkActorData* pkInstBase = GetInstancePtr(nVID); + if (pkInstBase) { + float x, y, z; + GetPixelPosition(*pkInstBase, &x, &y, &z); + long xInst = long(x), yInst = long(y); + // CPythonBackground::LocalPositionToGlobalPosition + if (const OutdoorMapInfo* map = GetOutdoorMap()) { xInst += long(map->baseX); yInst += long(map->baseY); } + std::snprintf(szDetail, sizeof(szDetail), "pos=(%ld, %ld)", xInst, yInst); + } + + // IsRegisteredVID / IsAliveVID: the alive map. The port keeps no dead list (DeleteInstanceByFade + // removes at once), so IsDeadVID is always 0. + const int isAlive = pkInstBase ? 1 : 0; + char szInfo[1024]; + std::snprintf(szInfo, sizeof(szInfo), "VID %d (isRegistered=%d, isAlive=%d, isDead=%d) %s", nVID, isAlive, isAlive, 0, szDetail); + return Py_BuildValue("s", szInfo); +} + +PyObject* chrmgrSetPathName(PyObject*, PyObject* poArgs) { + char* szPathName; + if (!PyTuple_GetString(poArgs, 0, &szPathName)) return Py_BadArgument(); + // Windows also queues a CCheatDetectQueueMgr UNKNOWN_MAPPED_FILE_PATH_NAME report here. + if (!std::strstr(szPathName, "d:/ymir")) return Py_BuildNone(); + RaceManager::Instance().SetPathName(szPathName); + return Py_BuildNone(); +} + +PyObject* chrmgrCreateRace(PyObject*, PyObject* poArgs) { + int iRace; + if (!PyTuple_GetInteger(poArgs, 0, &iRace)) return Py_BadArgument(); + RaceManager::Instance().CreateRace(uint32_t(iRace)); + return Py_BuildNone(); +} + +PyObject* chrmgrSelectRace(PyObject*, PyObject* poArgs) { + int iRace; + if (!PyTuple_GetInteger(poArgs, 0, &iRace)) return Py_BadArgument(); + RaceManager::Instance().SelectRace(uint32_t(iRace)); + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterAttachingBoneName(PyObject*, PyObject* poArgs) { + int iPartIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iPartIndex)) return Py_BadArgument(); + char* szBoneName; + if (!PyTuple_GetString(poArgs, 1, &szBoneName)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->RegisterAttachingBoneName(uint32_t(iPartIndex), szBoneName); + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterMotionMode(PyObject*, PyObject* poArgs) { + int iMotionIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iMotionIndex)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->RegisterMotionMode(uint16_t(iMotionIndex)); + return Py_BuildNone(); +} + +PyObject* chrmgrSetMotionRandomWeight(PyObject*, PyObject* poArgs) { + int iMode, iMotion, iSubMotion, iPercentage; + if (!PyTuple_GetInteger(poArgs, 0, &iMode)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &iMotion)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 2, &iSubMotion)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 3, &iPercentage)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + // Windows discards the Py_BuildException result here and returns None. + if (!pRaceData->SetMotionRandomWeight(uint16_t(iMode), uint16_t(iMotion), uint16_t(iSubMotion), uint8_t(iPercentage))) + Py_BuildException("Failed to SetMotionRandomWeight"); + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterNormalAttack(PyObject*, PyObject* poArgs) { + int iMode, iMotion; + if (!PyTuple_GetInteger(poArgs, 0, &iMode)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &iMotion)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->RegisterNormalAttack(uint16_t(iMode), uint16_t(iMotion)); + return Py_BuildNone(); +} + +PyObject* chrmgrReserveComboAttack(PyObject*, PyObject* poArgs) { + int iMode, iCount; + if (!PyTuple_GetInteger(poArgs, 0, &iMode)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &iCount)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->ReserveComboAttack(uint16_t(iMode), 0, uint32_t(iCount)); + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterComboAttack(PyObject*, PyObject* poArgs) { + int iMode, iComboIndex, iMotionIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iMode)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &iComboIndex)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 2, &iMotionIndex)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->RegisterComboAttack(uint16_t(iMode), 0, uint32_t(iComboIndex), uint16_t(iMotionIndex)); + return Py_BuildNone(); +} + +PyObject* chrmgrReserveComboAttackNew(PyObject*, PyObject* poArgs) { + int iMotionMode, iComboType, iCount; + if (!PyTuple_GetInteger(poArgs, 0, &iMotionMode)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &iComboType)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 2, &iCount)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->ReserveComboAttack(uint16_t(iMotionMode), uint16_t(iComboType), uint32_t(iCount)); + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterComboAttackNew(PyObject*, PyObject* poArgs) { + int iMotionMode, iComboType, iComboIndex, iMotionIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iMotionMode)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &iComboType)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 2, &iComboIndex)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 3, &iMotionIndex)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->RegisterComboAttack(uint16_t(iMotionMode), uint16_t(iComboType), uint32_t(iComboIndex), uint16_t(iMotionIndex)); + return Py_BuildNone(); +} + +PyObject* chrmgrLoadRaceData(PyObject*, PyObject* poArgs) { + char* szFileName; + if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + const std::string fullFileName = RaceManager::Instance().GetFullPathFileName(szFileName); + if (!pRaceData->LoadRaceData(fullFileName)) + std::cerr << "[AVA2 TraceError] Failed to load race data : " << fullFileName << std::endl; + return Py_BuildNone(); +} + +PyObject* chrmgrLoadLocalRaceData(PyObject*, PyObject* poArgs) { + char* szFileName; + if (!PyTuple_GetString(poArgs, 0, &szFileName)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + if (!pRaceData->LoadRaceData(szFileName)) + std::cerr << "[AVA2 TraceError] Failed to load race data : " << szFileName << std::endl; + return Py_BuildNone(); +} + +// chrmgrRegisterMotionData / RegisterCacheMotionData (the static cache is a Windows resource hint). +// CRaceData::RegisterMotionData loads the .msa first; the port registers the file and reads it +// when the motion plays. +PyObject* chrmgrRegisterMotionDataImpl(PyObject* poArgs) { + int iMode, iMotion; + if (!PyTuple_GetInteger(poArgs, 0, &iMode)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &iMotion)) return Py_BadArgument(); + char* szFileName; + if (!PyTuple_GetString(poArgs, 2, &szFileName)) return Py_BadArgument(); + int iWeight = 0; + PyTuple_GetInteger(poArgs, 3, &iWeight); + iWeight = std::min(100, iWeight); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->RegisterMotion(uint16_t(iMode), uint16_t(iMotion), RaceManager::Instance().GetFullPathFileName(szFileName), iWeight); + return Py_BuildNone(); +} +PyObject* chrmgrRegisterCacheMotionData(PyObject*, PyObject* poArgs) { return chrmgrRegisterMotionDataImpl(poArgs); } +PyObject* chrmgrRegisterMotionData(PyObject*, PyObject* poArgs) { return chrmgrRegisterMotionDataImpl(poArgs); } + +PyObject* chrmgrRegisterRaceSrcName(PyObject*, PyObject* poArgs) { + char* szName; + if (!PyTuple_GetString(poArgs, 0, &szName)) return Py_BadArgument(); + char* szSrcName; + if (!PyTuple_GetString(poArgs, 1, &szSrcName)) return Py_BadArgument(); + RaceManager::Instance().RegisterRaceSrcName(szName, szSrcName); + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterRaceName(PyObject*, PyObject* poArgs) { + int iRaceIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iRaceIndex)) return Py_BadArgument(); + char* szName; + if (!PyTuple_GetString(poArgs, 1, &szName)) return Py_BadArgument(); + RaceManager::Instance().RegisterRaceName(uint32_t(iRaceIndex), szName); + return Py_BuildNone(); +} + +PyObject* chrmgrSetShapeModel(PyObject*, PyObject* poArgs) { + int eShape; + if (!PyTuple_GetInteger(poArgs, 0, &eShape)) return Py_BadArgument(); + char* szFileName; + if (!PyTuple_GetString(poArgs, 1, &szFileName)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->SetShapeModel(uint32_t(eShape), szFileName); + return Py_BuildNone(); +} + +PyObject* chrmgrAppendShapeSkin(PyObject*, PyObject* poArgs) { + int eShape, ePart; + if (!PyTuple_GetInteger(poArgs, 0, &eShape)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &ePart)) return Py_BadArgument(); + char* szSrcFileName; + if (!PyTuple_GetString(poArgs, 2, &szSrcFileName)) return Py_BadArgument(); + char* szDstFileName; + if (!PyTuple_GetString(poArgs, 3, &szDstFileName)) return Py_BadArgument(); + RACE_DATA_OR_EXCEPTION(pRaceData); + pRaceData->AppendShapeSkin(uint32_t(eShape), uint32_t(ePart), szSrcFileName, szDstFileName); + return Py_BuildNone(); +} + +// The body is #ifndef NDEBUG; the release client returns None without parsing. +PyObject* chrmgrSetMovingSpeed(PyObject*, PyObject*) { return Py_BuildNone(); } + +PyObject* chrmgrRegisterEffectImpl(PyObject* poArgs, bool isCache) { + int eEftType; + if (!PyTuple_GetInteger(poArgs, 0, &eEftType)) return Py_BadArgument(); + char* szBoneName; + if (!PyTuple_GetString(poArgs, 1, &szBoneName)) return Py_BadArgument(); + char* szPathName; + if (!PyTuple_GetString(poArgs, 2, &szPathName)) return Py_BadArgument(); + NetworkActorManager::RegisterEffect(unsigned(eEftType), szBoneName, szPathName, isCache); + return Py_BuildNone(); +} +PyObject* chrmgrRegisterEffect(PyObject*, PyObject* poArgs) { return chrmgrRegisterEffectImpl(poArgs, false); } +PyObject* chrmgrRegisterCacheEffect(PyObject*, PyObject* poArgs) { return chrmgrRegisterEffectImpl(poArgs, true); } + +PyObject* chrmgrSetDustGap(PyObject*, PyObject* poArgs) { + int nGap; + if (!PyTuple_GetInteger(poArgs, 0, &nGap)) return Py_BadArgument(); + NetworkActorManager::SetDustGap(float(nGap)); + return Py_BuildNone(); +} + +PyObject* chrmgrSetHorseDustGap(PyObject*, PyObject* poArgs) { + int nGap; + if (!PyTuple_GetInteger(poArgs, 0, &nGap)) return Py_BadArgument(); + NetworkActorManager::SetHorseDustGap(float(nGap)); + return Py_BuildNone(); +} + +// CActorInstance::ShowDirectionLine has no port-side debug line renderer; the toggle state is kept. +PyObject* chrmgrToggleDirectionLine(PyObject*, PyObject*) { + static bool s_isVisible = true; + s_isVisible = !s_isVisible; + return Py_BuildNone(); +} + +PyObject* chrmgrRegisterPointEffect(PyObject*, PyObject* poArgs) { + int iEft; + if (!PyTuple_GetInteger(poArgs, 0, &iEft)) return Py_BadArgument(); + char* szFileName; + if (!PyTuple_GetString(poArgs, 1, &szFileName)) return Py_BadArgument(); + Mgr().RegisterPointEffect(uint32_t(iEft), szFileName); + return Py_BuildNone(); +} + +PyObject* chrmgrShowPointEffect(PyObject*, PyObject* poArgs) { + int nVID, nEft; + if (!PyTuple_GetInteger(poArgs, 0, &nVID)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &nEft)) return Py_BadArgument(); + Mgr().ShowPointEffect(uint32_t(nEft), ScriptVID(nVID)); + return Py_BuildNone(); +} + +PyObject* chrmgrSetAffect(PyObject*, PyObject* poArgs) { + int nVID, nEft, nVisible; + if (!PyTuple_GetInteger(poArgs, 0, &nVID)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &nEft)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 2, &nVisible)) return Py_BadArgument(); + Mgr().SCRIPT_SetAffect(ScriptVID(nVID), unsigned(nEft), nVisible != 0); + return Py_BuildNone(); +} + +PyObject* chrmgrSetEmoticon(PyObject*, PyObject* poArgs) { + int nVID, nEft; + if (!PyTuple_GetInteger(poArgs, 0, &nVID)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &nEft)) return Py_BadArgument(); + if (SNetworkActorData* inst = InstanceOrSelected(ScriptVID(nVID))) Mgr().SetEmoticon(inst->m_dwVID, unsigned(nEft)); + return Py_BuildNone(); +} + +PyObject* chrmgrIsPossibleEmoticon(PyObject*, PyObject* poArgs) { + int nVID; + if (!PyTuple_GetInteger(poArgs, 0, &nVID)) return Py_BadArgument(); + const SNetworkActorData* inst = InstanceOrSelected(ScriptVID(nVID)); + return Py_BuildValue("i", inst && Mgr().IsPossibleEmoticon(inst->m_dwVID) ? 1 : 0); +} + +PyObject* chrmgrSetRaceHeight(PyObject*, PyObject* poArgs) { + int iRaceIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iRaceIndex)) return Py_BadArgument(); + float fRaceHeight = 0.0f; + if (!PyTuple_GetFloat(poArgs, 1, &fRaceHeight)) return Py_BadArgument(); + RaceManager::Instance().SetRaceHeight(iRaceIndex, fRaceHeight); + return Py_BuildNone(); +} + +////////////////////////////////////////////////////////////////////////// +// chr +////////////////////////////////////////////////////////////////////////// + +// InstanceBase.h RaceToJob / RaceToSex (ENABLE_WOLFMAN_CHARACTER off). +PyObject* chrRaceToJob(PyObject*, PyObject* poArgs) { + int race; + if (!PyTuple_GetInteger(poArgs, 0, &race)) return Py_BuildException(); + return Py_BuildValue("i", race % 4); +} + +PyObject* chrRaceToSex(PyObject*, PyObject* poArgs) { + int race; + if (!PyTuple_GetInteger(poArgs, 0, &race)) return Py_BuildException(); + return Py_BuildValue("i", race == 0 || race == 2 || race == 5 || race == 7 ? 1 : 0); +} + +PyObject* chrDestroy(PyObject*, PyObject*) { + Mgr().Destroy(); + return Py_BuildNone(); +} + +// CPythonCharacterManager::Update ticks on the frame timer; the port measures the call interval. +PyObject* chrUpdate(PyObject*, PyObject*) { + using clock = std::chrono::steady_clock; + static clock::time_point s_last; + static bool s_hasLast = false; + const clock::time_point now = clock::now(); + const float dt = s_hasLast ? std::chrono::duration(now - s_last).count() : 0.0f; + s_last = now; + s_hasLast = true; + Mgr().Update(dt, GetActiveBackgroundTerrain()); + return Py_BuildNone(); +} + +// Deform / Render / RenderCollision: the port deforms in ActorInstance::Update and draws the actor +// list through GetAllActiveChrDraws (main loop), so the script calls have nothing left to do. +PyObject* chrDeform(PyObject*, PyObject*) { return Py_BuildNone(); } +PyObject* chrRender(PyObject*, PyObject*) { return Py_BuildNone(); } +PyObject* chrRenderCollision(PyObject*, PyObject*) { return Py_BuildNone(); } + +PyObject* chrCreateInstance(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + + if (PyTuple_Size(poArgs) == 2) { + PyObject* poDict = PyTuple_GetItem(poArgs, 1); + if (!PyDict_Check(poDict)) return Py_BuildException(); + + SNetworkActorData kCreateData; + kCreateData.m_bType = TYPE_PC; + kCreateData.m_dwVID = uint32_t(iVirtualID); + kCreateData.m_fRot = 0.0f; // CInstanceBase::DIR_NORTH + kCreateData.m_stName = "NONAME"; + kCreateData.m_dwMovSpd = 100; + kCreateData.m_dwAtkSpd = 100; + kCreateData.m_dwArmor = 8; + + if (PyObject* poHorse = PyDict_GetItemString(poDict, "horse")) kCreateData.m_dwMountVnum = uint32_t(PyLong_AsLong(poHorse)); + if (PyObject* poX = PyDict_GetItemString(poDict, "x")) kCreateData.m_lCurX = int32_t(PyLong_AsLong(poX)); + // Windows writes "y" into m_lPosX as well. + if (PyObject* poY = PyDict_GetItemString(poDict, "y")) kCreateData.m_lCurX = int32_t(PyLong_AsLong(poY)); + + CreateInstance(kCreateData); + } else { + Mgr().RegisterInstance(uint32_t(iVirtualID)); + } + return Py_BuildNone(); +} + +PyObject* chrDeleteInstance(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + Mgr().RemoveActor(uint32_t(iVirtualID)); + return Py_BuildNone(); +} + +PyObject* chrDeleteInstanceByFade(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + Mgr().DeleteInstanceByFade(uint32_t(iVirtualID)); + return Py_BuildNone(); +} + +PyObject* chrSelectInstance(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + Mgr().SelectInstance(uint32_t(iVirtualID)); + return Py_BuildNone(); +} + +PyObject* chrHasInstance(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + return Py_BuildValue("i", GetInstancePtr(iVirtualID) ? 1 : 0); +} + +PyObject* chrIsEnemy(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + const SNetworkActorData* pInstance = GetInstancePtr(iVirtualID); + if (!pInstance) return Py_BuildValue("i", 0); + return Py_BuildValue("i", pInstance->m_bType == TYPE_ENEMY ? 1 : 0); +} + +PyObject* chrIsNPC(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + const SNetworkActorData* pInstance = GetInstancePtr(iVirtualID); + if (!pInstance) return Py_BuildValue("i", 0); + return Py_BuildValue("i", pInstance->m_bType == TYPE_NPC ? 1 : 0); +} + +PyObject* chrIsGameMaster(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + const SNetworkActorData* pInstance = GetInstancePtr(iVirtualID); + if (!pInstance) return Py_BuildValue("i", 0); + return Py_BuildValue("i", IsGameMaster(*pInstance) ? 1 : 0); +} + +PyObject* chrIsPartyMember(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + const SNetworkActorData* pInstance = GetInstancePtr(iVirtualID); + if (!pInstance) return Py_BuildValue("i", 0); + return Py_BuildValue("i", NetworkActorManager::IsPartyMember(pInstance->m_dwVID) ? 1 : 0); +} + +// Select: an ON_CLICK_EVENT_SHOP NPC gets SetAddRenderMode + SetAddColor(0, 0.3, 0). The port has no +// add-colour render mode, so Select / SetAddRenderMode / SetBlendRenderMode / Unselect only parse. +PyObject* chrSelect(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + return Py_BuildNone(); +} + +PyObject* chrSetAddRenderMode(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + float fr, fg, fb; + if (!PyTuple_GetFloat(poArgs, 1, &fr)) return Py_BuildException(); + if (!PyTuple_GetFloat(poArgs, 2, &fg)) return Py_BuildException(); + if (!PyTuple_GetFloat(poArgs, 3, &fb)) return Py_BuildException(); + return Py_BuildNone(); +} + +PyObject* chrSetBlendRenderMode(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + float fAlpha; + if (!PyTuple_GetFloat(poArgs, 1, &fAlpha)) return Py_BuildException(); + return Py_BuildNone(); +} + +PyObject* chrUnselect(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + return Py_BuildNone(); +} + +PyObject* chrPick(PyObject*, PyObject*) { + uint32_t VirtualID = 0; + if (Mgr().OLD_GetPickedInstanceVID(&VirtualID)) return Py_BuildValue("i", VirtualID); + return Py_BuildValue("i", -1); +} + +// CInstanceBase::Hide/Show blend the alpha to 0/1; the port skips the instance in BuildDrawCommands. +PyObject* chrHide(PyObject*, PyObject*) { + if (SNetworkActorData* pkInst = GetSelectedInstancePtr()) pkInst->m_isHidden = true; + return Py_BuildNone(); +} + +PyObject* chrShow(PyObject*, PyObject*) { + if (SNetworkActorData* pkInst = GetSelectedInstancePtr()) pkInst->m_isHidden = false; + return Py_BuildNone(); +} + +// CPythonCharacterManager::PickAll: IntersectDefendingSphere over the instances, else 0xffffffff. +// No defending-sphere pick pass is ported, so nothing is ever hit. +PyObject* chrPickAll(PyObject*, PyObject*) { + return Py_BuildValue("i", -1); +} + +PyObject* chrSetRace(PyObject*, PyObject* poArgs) { + int iRace; + if (!PyTuple_GetInteger(poArgs, 0, &iRace)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + pkInst->m_dwRace = uint32_t(iRace); + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->SetRace(uint32_t(iRace)); + return Py_BuildNone(); +} + +PyObject* chrSetHair(PyObject*, PyObject* poArgs) { + int iRace; + if (!PyTuple_GetInteger(poArgs, 0, &iRace)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + NetworkActorManager::SetHair(*pkInst, uint32_t(iRace)); + return Py_BuildNone(); +} + +PyObject* chrChangeHair(PyObject*, PyObject* poArgs) { + int iHair; + if (!PyTuple_GetInteger(poArgs, 0, &iHair)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + NetworkActorManager::ChangeHair(*pkInst, uint32_t(iHair)); + return Py_BuildNone(); +} + +// SetArmor also calls RegisterBoundingSphere (picking spheres are not ported). +PyObject* chrSetArmor(PyObject*, PyObject* poArgs) { + int iForm; + if (!PyTuple_GetInteger(poArgs, 0, &iForm)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + NetworkActorManager::SetArmor(*pkInst, uint32_t(iForm)); + return Py_BuildNone(); +} + +PyObject* chrChangeShape(PyObject*, PyObject* poArgs) { + int iForm; + if (!PyTuple_GetInteger(poArgs, 0, &iForm)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + NetworkActorManager::ChangeArmor(*pkInst, uint32_t(iForm)); + return Py_BuildNone(); +} + +PyObject* chrSetWeapon(PyObject*, PyObject* poArgs) { + int iForm; + if (!PyTuple_GetInteger(poArgs, 0, &iForm)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + NetworkActorManager::SetWeapon(*pkInst, uint32_t(iForm)); + return Py_BuildNone(); +} + +// CInstanceBase::SetVirtualID: the graphic instance's VID only (the manager key is unchanged). +PyObject* chrSetVirtualID(PyObject*, PyObject* poArgs) { + int iVID; + if (!PyTuple_GetInteger(poArgs, 0, &iVID)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->SetVID(uint32_t(iVID)); + return Py_BuildNone(); +} + +// CInstanceBase::SetNameString: m_stName only (the text tail is attached by Create). +PyObject* chrSetNameString(PyObject*, PyObject* poArgs) { + char* c_szName; + if (!PyTuple_GetString(poArgs, 0, &c_szName)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + pkInst->m_stName.assign(c_szName, std::strlen(c_szName)); + return Py_BuildNone(); +} + +PyObject* chrSetInstanceType(PyObject*, PyObject* poArgs) { + int iInstanceType; + if (!PyTuple_GetInteger(poArgs, 0, &iInstanceType)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + pkInst->m_bType = uint8_t(iInstanceType); + return Py_BuildNone(); +} + +// AttachEffectByName / AttachEffectByID: the CInstanceBase call is commented out on Windows too. +PyObject* chrAttachEffectImpl(PyObject* poArgs, bool byName) { + int iParentPartIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iParentPartIndex)) return Py_BuildException(); + char* pszBoneName; + if (!PyTuple_GetString(poArgs, 1, &pszBoneName)) pszBoneName = nullptr; + if (byName) { + char* pszEffectName; + if (!PyTuple_GetString(poArgs, 2, &pszEffectName)) return Py_BuildException(); + } else { + int iEffectID; + if (!PyTuple_GetInteger(poArgs, 2, &iEffectID)) return Py_BuildException(); + } + int iLife = -1; // CActorInstance::EFFECT_LIFE_INFINITE + if (PyTuple_Size(poArgs) == 4 && !PyTuple_GetInteger(poArgs, 3, &iLife)) return Py_BuildException(); + return Py_BuildNone(); +} +PyObject* chrAttachEffectByName(PyObject*, PyObject* poArgs) { return chrAttachEffectImpl(poArgs, true); } +PyObject* chrAttachEffectByID(PyObject*, PyObject* poArgs) { return chrAttachEffectImpl(poArgs, false); } + +// Refresh(NAME_WAIT) is commented out on Windows (the select screen has no WAIT motion yet). +PyObject* chrRefresh(PyObject*, PyObject*) { return Py_BuildNone(); } + +// CInstanceBase::MountHorse(20030): the horse actor (m_kHorse) is not ported; the rider switches to +// MODE_HORSE like Windows. DismountHorse only destroys m_kHorse, so it has nothing to undo here. +PyObject* chrMountHorse(PyObject*, PyObject*) { + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->SetMotionMode(MODE_HORSE); + return Py_BuildNone(); +} + +PyObject* chrDismountHorse(PyObject*, PyObject*) { + return Py_BuildNone(); +} + +PyObject* chrRevive(PyObject*, PyObject*) { + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + pkInst->m_isMoving = false; // m_isGoing / m_isWalking + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->Revive(); + return Py_BuildNone(); +} + +PyObject* chrDie(PyObject*, PyObject*) { + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->Die(); + return Py_BuildNone(); +} + +// LookAt is commented out on Windows. +PyObject* chrLookAt(PyObject*, PyObject* poArgs) { + int iCellX, iCellY; + if (!PyTuple_GetInteger(poArgs, 0, &iCellX)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iCellY)) return Py_BuildException(); + return Py_BuildNone(); +} + +PyObject* chrSetMotionMode(PyObject*, PyObject* poArgs) { + int iMotionMode; + if (!PyTuple_GetInteger(poArgs, 0, &iMotionMode)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->SetMotionMode(iMotionMode); + return Py_BuildNone(); +} + +// Motion blend times are not ported (ActorInstance switches at once / at the cycle end). +PyObject* chrSetLoopMotion(PyObject*, PyObject* poArgs) { + int iMotionIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iMotionIndex)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->SetLoopMotionIndex(uint16_t(iMotionIndex)); + return Py_BuildNone(); +} + +PyObject* chrBlendLoopMotion(PyObject*, PyObject* poArgs) { + int iMotionIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iMotionIndex)) return Py_BuildException(); + float fBlendTime; + if (!PyTuple_GetFloat(poArgs, 1, &fBlendTime)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->SetLoopMotionIndex(uint16_t(iMotionIndex)); + return Py_BuildNone(); +} + +PyObject* chrPushMotionImpl(PyObject* poArgs, bool isLoop) { + int iMotionIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iMotionIndex)) return Py_BuildException(); + float fBlendTime; + if (!PyTuple_GetFloat(poArgs, 1, &fBlendTime)) fBlendTime = 0.1f; + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + if (pkInst->m_pActorInstance) pkInst->m_pActorInstance->PushMotionIndex(uint16_t(iMotionIndex), isLoop); + return Py_BuildNone(); +} +PyObject* chrPushOnceMotion(PyObject*, PyObject* poArgs) { return chrPushMotionImpl(poArgs, false); } +PyObject* chrPushLoopMotion(PyObject*, PyObject* poArgs) { return chrPushMotionImpl(poArgs, true); } + +PyObject* chrSetPixelPosition(PyObject*, PyObject* poArgs) { + int iX, iY; + if (!PyTuple_GetInteger(poArgs, 0, &iX)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iY)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + int iZ; + if (PyTuple_GetInteger(poArgs, 2, &iZ)) + SetPixelPosition(*pkInst, float(iX), float(iY), float(iZ)); // NEW_SetPixelPosition + else + SetPixelPosition(*pkInst, float(iX), float(iY), GetBackgroundHeight(float(iX), float(iY))); // SCRIPT_SetPixelPosition + return Py_BuildNone(); +} + +// CInstanceBase::SetDirection(GetDegreeFromDirection(dir)). Windows dereferences the selected +// instance without a null check; the port returns None instead of crashing. +PyObject* chrSetDirection(PyObject*, PyObject* poArgs) { + int iDirection; + if (!PyTuple_GetInteger(poArgs, 0, &iDirection)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + static const float s_dirRot[8] = { 45.0f * 4, 45.0f * 3, 45.0f * 2, 45.0f, 0.0f, 360.0f - 45.0f, 360.0f - 45.0f * 2, 360.0f - 45.0f * 3 }; + SetRotation(*pkInst, iDirection < 0 || iDirection >= 8 ? 0.0f : s_dirRot[iDirection]); + return Py_BuildNone(); +} + +PyObject* chrGetPixelPosition(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + const SNetworkActorData* pkInst = GetInstancePtr(iVirtualID); + if (!pkInst) return Py_BuildNone(); + float x, y, z; + GetPixelPosition(*pkInst, &x, &y, &z); + return Py_BuildValue("fff", x, y, z); +} + +PyObject* chrSetRotation(PyObject*, PyObject* poArgs) { + float fRotation; + if (!PyTuple_GetFloat(poArgs, 0, &fRotation)) return Py_BuildException(); + SNetworkActorData* pCharacterInstance = GetSelectedInstancePtr(); + if (!pCharacterInstance) return Py_BuildNone(); + SetRotation(*pCharacterInstance, std::fmod(fRotation + 180.0f, 360.0f)); + return Py_BuildNone(); +} + +// SetXYRotation (the X/Y tilt) has no port counterpart; the Z rotation is applied. +PyObject* chrSetRotationAll(PyObject*, PyObject* poArgs) { + float fRotX, fRotY, fRotZ; + if (!PyTuple_GetFloat(poArgs, 0, &fRotX)) return Py_BuildException(); + if (!PyTuple_GetFloat(poArgs, 1, &fRotY)) return Py_BuildException(); + if (!PyTuple_GetFloat(poArgs, 2, &fRotZ)) return Py_BuildException(); + SNetworkActorData* pCharacterInstance = GetSelectedInstancePtr(); + if (!pCharacterInstance) return Py_BuildNone(); + SetRotation(*pCharacterInstance, fRotZ); + return Py_BuildNone(); +} + +// BlendRotation: the port sets the target rotation at once. +PyObject* chrBlendRotation(PyObject*, PyObject* poArgs) { + float fRotation, fBlendTime; + if (!PyTuple_GetFloat(poArgs, 0, &fRotation)) return Py_BuildException(); + if (!PyTuple_GetFloat(poArgs, 1, &fBlendTime)) return Py_BuildException(); + fRotation = std::fmod(720.0f - fRotation, 360.0f); + SNetworkActorData* pCharacterInstance = GetSelectedInstancePtr(); + if (!pCharacterInstance) return Py_BuildNone(); + SetRotation(*pCharacterInstance, fRotation); + return Py_BuildNone(); +} + +PyObject* chrGetRotation(PyObject*, PyObject*) { + const SNetworkActorData* pCharacterInstance = GetSelectedInstancePtr(); + if (!pCharacterInstance) return Py_BuildValue("f", 0.0f); + return Py_BuildValue("f", 360.0f - GetRotation(*pCharacterInstance)); +} + +PyObject* chrGetRace(PyObject*, PyObject*) { + const SNetworkActorData* pCharacterInstance = GetSelectedInstancePtr(); + if (!pCharacterInstance) return Py_BuildValue("i", 0); + return Py_BuildValue("i", pCharacterInstance->m_dwRace); +} + +PyObject* chrGetName(PyObject*, PyObject*) { + const SNetworkActorData* pCharacterInstance = GetSelectedInstancePtr(); + if (!pCharacterInstance) return Py_BuildValue("i", 0); + return Py_BuildValue("s", pCharacterInstance->m_stName.c_str()); +} + +PyObject* chrGetNameByVID(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + const SNetworkActorData* pInstance = GetInstancePtr(iVirtualID); + if (!pInstance) return Py_BuildValue("s", "None"); + return Py_BuildValue("s", pInstance->m_stName.c_str()); +} + +PyObject* chrGetGuildID(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + const SNetworkActorData* pInstance = GetInstancePtr(iVirtualID); + if (!pInstance) return Py_BuildValue("i", 0); + return Py_BuildValue("i", pInstance->m_dwGuildID); +} + +// CPythonGraphic::ProjectPosition through the scene renderer the text tails use; off-screen +// (fz == 1 on Windows) or no renderer answers (-100, -100). +PyObject* chrGetProjectPosition(PyObject*, PyObject* poArgs) { + int iVirtualID, iHeight; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iHeight)) return Py_BuildException(); + const SNetworkActorData* pInstance = GetInstancePtr(iVirtualID); + if (!pInstance) return Py_BuildValue("ii", -100, -100); + float x, y, z; + GetPixelPosition(*pInstance, &x, &y, &z); + const Gr2SceneRenderer* renderer = TextTailManager::Instance().GetCurrentSceneRenderer(); + float fx, fy; + if (!renderer || !renderer->ProjectToScreen(x, z + float(iHeight), y, fx, fy)) return Py_BuildValue("ii", -100, -100); + return Py_BuildValue("ii", int(fx), int(fy)); +} + +PyObject* chrGetVirtualNumber(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + if (const SNetworkActorData* pkInst = GetInstancePtr(iVirtualID)) return Py_BuildValue("i", pkInst->m_dwVirtualNumber); + return Py_BuildValue("i", int(TYPE_PC)); +} + +PyObject* chrGetInstanceType(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + if (const SNetworkActorData* pkInst = GetInstancePtr(iVirtualID)) return Py_BuildValue("i", int(pkInst->m_bType)); + return Py_BuildValue("i", int(TYPE_PC)); +} + +// CGraphicObjectInstance::GetBoundBox is not ported; the selected instance answers an empty box. +PyObject* chrGetBoundBoxOnlyXY(PyObject*, PyObject*) { + return Py_BuildValue("ffff", 0.0f, 0.0f, 0.0f, 0.0f); +} + +PyObject* chrtestGetPKData(PyObject*, PyObject*) { + const SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildValue("ii", 0, 4); + return Py_BuildValue("ii", int(pkInst->m_sAlignment), int(NetworkActorManager::GetAlignmentGrade(pkInst->m_sAlignment))); +} + +// CActorInstance::SetComboType: the port plays no combo chains from the script. +PyObject* chrtestSetComboType(PyObject*, PyObject* poArgs) { + int iComboType; + if (!PyTuple_GetInteger(poArgs, 0, &iComboType)) return Py_BuildException(); + return Py_BuildNone(); +} + +// test render-mode helpers: no add/modulate/specular render modes in the port. +PyObject* chrtestSetColorRenderMode(PyObject* poArgs) { + int iVirtualID, iColor; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iColor)) return Py_BuildException(); + return Py_BuildNone(); +} +PyObject* chrtestSetAddRenderMode(PyObject*, PyObject* poArgs) { return chrtestSetColorRenderMode(poArgs); } +PyObject* chrtestSetModulateRenderMode(PyObject*, PyObject* poArgs) { return chrtestSetColorRenderMode(poArgs); } + +PyObject* chrtestSetRGBRenderMode(PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + float fr, fg, fb; + if (!PyTuple_GetFloat(poArgs, 1, &fr)) return Py_BuildException(); + if (!PyTuple_GetFloat(poArgs, 2, &fg)) return Py_BuildException(); + if (!PyTuple_GetFloat(poArgs, 3, &fb)) return Py_BuildException(); + return Py_BuildNone(); +} +PyObject* chrtestSetAddRenderModeRGB(PyObject*, PyObject* poArgs) { return chrtestSetRGBRenderMode(poArgs); } +PyObject* chrtestSetModulateRenderModeRGB(PyObject*, PyObject* poArgs) { return chrtestSetRGBRenderMode(poArgs); } + +PyObject* chrtestSetSpecularRenderModeImpl(PyObject* poArgs) { + int iVirtualID, iPart; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iPart)) return Py_BuildException(); + float fAlpha; + if (!PyTuple_GetFloat(poArgs, 2, &fAlpha)) return Py_BuildException(); + return Py_BuildNone(); +} +PyObject* chrtestSetSpecularRenderMode(PyObject*, PyObject* poArgs) { return chrtestSetSpecularRenderModeImpl(poArgs); } +PyObject* chrtestSetSpecularRenderMode2(PyObject*, PyObject* poArgs) { return chrtestSetSpecularRenderModeImpl(poArgs); } + +PyObject* chrtestRestoreRenderMode(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + return Py_BuildNone(); +} + +PyObject* chrFaintTest(PyObject*, PyObject*) { + SNetworkActorData* pCharacterInstance = GetSelectedInstancePtr(); + if (pCharacterInstance && pCharacterInstance->m_pActorInstance) { + ActorInstance& actor = *pCharacterInstance->m_pActorInstance; + if (actor.IsFaint()) { + actor.SetFaint(false); + } else { + actor.InterceptMotionIndex(RaceData::NAME_DAMAGE_FLYING, false); + actor.PushMotionIndex(RaceData::NAME_STAND_UP, false); + actor.PushMotionIndex(RaceData::NAME_WAIT, true); + actor.SetFaint(true); + } + } + return Py_BuildNone(); +} + +// SetMoveSpeed / SetAttackSpeed: the bodies are commented out on Windows. +PyObject* chrSetMoveSpeed(PyObject*, PyObject*) { return Py_BuildNone(); } +PyObject* chrSetAttackSpeed(PyObject*, PyObject*) { return Py_BuildNone(); } + +// Weapon trace (CWeaponTrace) is not ported; the main-instance calls only parse. +PyObject* chrWeaponTraceSetTexture(PyObject*, PyObject* poArgs) { + char* szPathName; + if (!PyTuple_GetString(poArgs, 0, &szPathName)) return Py_BadArgument(); + return Py_BuildNone(); +} +PyObject* chrWeaponTraceUseTexture(PyObject*, PyObject*) { return Py_BuildNone(); } +PyObject* chrWeaponTraceUseAlpha(PyObject*, PyObject*) { return Py_BuildNone(); } + +// NEW_MoveToDestPixelPositionDirection: the port walks the instance there with its move loop +// (the advancing rotation toward the destination is not recomputed). +PyObject* chrMoveToDestPosition(PyObject*, PyObject* poArgs) { + int iVID, ix, iy; + if (!PyTuple_GetInteger(poArgs, 0, &iVID)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &ix)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 2, &iy)) return Py_BadArgument(); + const SNetworkActorData* pCharacterInstance = GetInstancePtr(iVID); + if (!pCharacterInstance) return Py_BuildNone(); + SNetworkMoveActorData move; + move.m_dwVID = pCharacterInstance->m_dwVID; + move.m_lPosX = ix; + move.m_lPosY = iy; + move.m_fRot = GetRotation(*pCharacterInstance); + move.m_dwFunc = 1; + Mgr().MoveActor(move); + return Py_BuildNone(); +} + +// testSetRideMan: RegisterInstance(1) + Create (Windows crashes when VID 1 already exists and +// leaves the zeroed create-data VID 0 on the graphic; the port returns and keys the actor as 1). +PyObject* chrtestSetRideMan(PyObject*, PyObject* poArgs) { + int ix, iy; + if (!PyTuple_GetInteger(poArgs, 0, &ix)) return Py_BadArgument(); + if (!PyTuple_GetInteger(poArgs, 1, &iy)) return Py_BadArgument(); + int imount = 20030; + PyTuple_GetInteger(poArgs, 2, &imount); + + if (!Mgr().RegisterInstance(1)) return Py_BuildNone(); + SNetworkActorData kCreateData; + kCreateData.m_dwVID = 1; + kCreateData.m_bType = TYPE_PC; + kCreateData.m_dwRace = 0; + kCreateData.m_dwArmor = 0; + kCreateData.m_dwHair = 100; + kCreateData.m_dwMovSpd = 100; + kCreateData.m_dwAtkSpd = 100; + kCreateData.m_dwMountVnum = uint32_t(imount); + kCreateData.m_lCurX = ix; + kCreateData.m_lCurY = iy; + kCreateData.m_lCurZ = int32_t(GetBackgroundHeight(float(ix), float(iy))); + Mgr().AppendActor(kCreateData); + return Py_BuildNone(); +} + +PyObject* chrSetSash(PyObject*, PyObject* poArgs) { + int dwSash; + if (!PyTuple_GetInteger(poArgs, 0, &dwSash)) return Py_BuildException(); + SNetworkActorData* pkInst = GetSelectedInstancePtr(); + if (!pkInst) return Py_BuildNone(); + Mgr().SetSash(pkInst->m_dwVID, uint32_t(dwSash)); + return Py_BuildNone(); +} + +PyObject* chrIsStone(PyObject*, PyObject* poArgs) { + int iVirtualID; + if (!PyTuple_GetInteger(poArgs, 0, &iVirtualID)) return Py_BuildException(); + const SNetworkActorData* pInstance = GetInstancePtr(iVirtualID); + if (!pInstance) return Py_BuildValue("i", 0); + return Py_BuildValue("i", pInstance->m_bType == TYPE_STONE ? 1 : 0); +} + +} // namespace + +std::vector GetAllActiveChrDraws() { + return NetworkActorManager::Instance().BuildDrawCommands(0.0f); +} + +void initchrmgr() { + static PyMethodDef s_methods[] = { + {"SetRaceHeight", chrmgrSetRaceHeight, METH_VARARGS, nullptr}, + {"SetEmpireNameMode", chrmgrSetEmpireNameMode, METH_VARARGS, nullptr}, + {"GetVIDInfo", chrmgrGetVIDInfo, METH_VARARGS, nullptr}, + {"GetPickedVID", chrmgrGetPickedVID, METH_VARARGS, nullptr}, + {"SetShapeModel", chrmgrSetShapeModel, METH_VARARGS, nullptr}, + {"AppendShapeSkin", chrmgrAppendShapeSkin, METH_VARARGS, nullptr}, + {"SetPathName", chrmgrSetPathName, METH_VARARGS, nullptr}, + {"LoadRaceData", chrmgrLoadRaceData, METH_VARARGS, nullptr}, + {"LoadLocalRaceData", chrmgrLoadLocalRaceData, METH_VARARGS, nullptr}, + {"CreateRace", chrmgrCreateRace, METH_VARARGS, nullptr}, + {"SelectRace", chrmgrSelectRace, METH_VARARGS, nullptr}, + {"RegisterAttachingBoneName", chrmgrRegisterAttachingBoneName, METH_VARARGS, nullptr}, + {"RegisterMotionMode", chrmgrRegisterMotionMode, METH_VARARGS, nullptr}, + {"SetMotionRandomWeight", chrmgrSetMotionRandomWeight, METH_VARARGS, nullptr}, + {"RegisterNormalAttack", chrmgrRegisterNormalAttack, METH_VARARGS, nullptr}, + {"ReserveComboAttack", chrmgrReserveComboAttack, METH_VARARGS, nullptr}, + {"RegisterComboAttack", chrmgrRegisterComboAttack, METH_VARARGS, nullptr}, + {"ReserveComboAttackNew", chrmgrReserveComboAttackNew, METH_VARARGS, nullptr}, + {"RegisterComboAttackNew", chrmgrRegisterComboAttackNew, METH_VARARGS, nullptr}, + {"RegisterMotionData", chrmgrRegisterMotionData, METH_VARARGS, nullptr}, + {"RegisterRaceName", chrmgrRegisterRaceName, METH_VARARGS, nullptr}, + {"RegisterRaceSrcName", chrmgrRegisterRaceSrcName, METH_VARARGS, nullptr}, + {"RegisterCacheMotionData", chrmgrRegisterCacheMotionData, METH_VARARGS, nullptr}, + {"SetAffect", chrmgrSetAffect, METH_VARARGS, nullptr}, + {"SetEmoticon", chrmgrSetEmoticon, METH_VARARGS, nullptr}, + {"IsPossibleEmoticon", chrmgrIsPossibleEmoticon, METH_VARARGS, nullptr}, + {"RegisterEffect", chrmgrRegisterEffect, METH_VARARGS, nullptr}, + {"RegisterCacheEffect", chrmgrRegisterCacheEffect, METH_VARARGS, nullptr}, + {"RegisterPointEffect", chrmgrRegisterPointEffect, METH_VARARGS, nullptr}, + {"ShowPointEffect", chrmgrShowPointEffect, METH_VARARGS, nullptr}, + {"ToggleDirectionLine", chrmgrToggleDirectionLine, METH_VARARGS, nullptr}, + {"SetMovingSpeed", chrmgrSetMovingSpeed, METH_VARARGS, nullptr}, + {"SetDustGap", chrmgrSetDustGap, METH_VARARGS, nullptr}, + {"SetHorseDustGap", chrmgrSetHorseDustGap, METH_VARARGS, nullptr}, + {"RegisterTitleName", chrmgrRegisterTitleName, METH_VARARGS, nullptr}, + {"RegisterNameColor", chrmgrRegisterNameColor, METH_VARARGS, nullptr}, + {"RegisterTitleColor", chrmgrRegisterTitleColor, METH_VARARGS, nullptr}, + {nullptr, nullptr, 0, nullptr} + }; + auto* module = Py_InitModule("chrmgr", s_methods); + + PyModule_AddIntConstant(module, "NAMECOLOR_SHOP", 27); + PyModule_AddIntConstant(module, "NAMECOLOR_MOB", 7); + PyModule_AddIntConstant(module, "NAMECOLOR_NPC", 8); + PyModule_AddIntConstant(module, "NAMECOLOR_PC", 9); + PyModule_AddIntConstant(module, "NAMECOLOR_EMPIRE_MOB", 14); + PyModule_AddIntConstant(module, "NAMECOLOR_EMPIRE_NPC", 15); + PyModule_AddIntConstant(module, "NAMECOLOR_EMPIRE_PC", 16); + PyModule_AddIntConstant(module, "NAMECOLOR_FUNC", 21); + PyModule_AddIntConstant(module, "NAMECOLOR_PK", 22); + PyModule_AddIntConstant(module, "NAMECOLOR_PVP", 23); + PyModule_AddIntConstant(module, "NAMECOLOR_PARTY", 24); + PyModule_AddIntConstant(module, "NAMECOLOR_WARP", 25); + PyModule_AddIntConstant(module, "NAMECOLOR_WAYPOINT", 26); + PyModule_AddIntConstant(module, "NAMECOLOR_EXTRA", 31); + PyModule_AddIntConstant(module, "NAMECOLOR_METIN", 30); + PyModule_AddIntConstant(module, "NAMECOLOR_CONQUEROR", 29); + PyModule_AddIntConstant(module, "NAMECOLOR_BOSS", 28); + PyModule_AddIntConstant(module, "NAMECOLOR_TOURNAMENT_TEAM_A", 32); + PyModule_AddIntConstant(module, "NAMECOLOR_TOURNAMENT_TEAM_B", 33); + PyModule_AddIntConstant(module, "EFFECT_ELEMENTS_WEAPON", 280); + PyModule_AddIntConstant(module, "EFFECT_SPAWN_DISAPPEAR", 10); + PyModule_AddIntConstant(module, "EFFECT_SPAWN_APPEAR", 9); + PyModule_AddIntConstant(module, "EFFECT_DUST", 0); + PyModule_AddIntConstant(module, "EFFECT_HORSE_DUST", 228); + PyModule_AddIntConstant(module, "EFFECT_STUN", 1); + PyModule_AddIntConstant(module, "EFFECT_HIT", 2); + PyModule_AddIntConstant(module, "EFFECT_FLAME_ATTACK", 3); + PyModule_AddIntConstant(module, "EFFECT_FLAME_HIT", 4); + PyModule_AddIntConstant(module, "EFFECT_FLAME_ATTACH", 5); + PyModule_AddIntConstant(module, "EFFECT_ELECTRIC_ATTACK", 6); + PyModule_AddIntConstant(module, "EFFECT_ELECTRIC_HIT", 7); + PyModule_AddIntConstant(module, "EFFECT_ELECTRIC_ATTACH", 8); + PyModule_AddIntConstant(module, "EFFECT_SELECT", 221); + PyModule_AddIntConstant(module, "EFFECT_TARGET", 222); + PyModule_AddIntConstant(module, "EFFECT_CRITICAL", 17); + PyModule_AddIntConstant(module, "EFFECT_DAMAGE_TARGET", 254); + PyModule_AddIntConstant(module, "EFFECT_DAMAGE_NOT_TARGET", 255); + PyModule_AddIntConstant(module, "EFFECT_DAMAGE_SELFDAMAGE", 256); + PyModule_AddIntConstant(module, "EFFECT_DAMAGE_SELFDAMAGE2", 257); + PyModule_AddIntConstant(module, "EFFECT_DAMAGE_POISON", 258); + PyModule_AddIntConstant(module, "EFFECT_DAMAGE_MISS", 259); + PyModule_AddIntConstant(module, "EFFECT_DAMAGE_TARGETMISS", 260); + PyModule_AddIntConstant(module, "EFFECT_DAMAGE_CRITICAL", 261); + PyModule_AddIntConstant(module, "EFFECT_LEVELUP", 11); + PyModule_AddIntConstant(module, "EFFECT_SKILLUP", 12); + PyModule_AddIntConstant(module, "EFFECT_HPUP_RED", 13); + PyModule_AddIntConstant(module, "EFFECT_SPUP_BLUE", 14); + PyModule_AddIntConstant(module, "EFFECT_SPEEDUP_GREEN", 15); + PyModule_AddIntConstant(module, "EFFECT_DXUP_PURPLE", 16); + PyModule_AddIntConstant(module, "EFFECT_PENETRATE", 18); + PyModule_AddIntConstant(module, "EFFECT_BLOCK", 19); + PyModule_AddIntConstant(module, "EFFECT_DODGE", 20); + PyModule_AddIntConstant(module, "EFFECT_FIRECRACKER", 21); + PyModule_AddIntConstant(module, "EFFECT_SPIN_TOP", 22); + PyModule_AddIntConstant(module, "EFFECT_WEAPON", 23); + PyModule_AddIntConstant(module, "EFFECT_AFFECT", 27); + PyModule_AddIntConstant(module, "EFFECT_EMOTICON", 92); + PyModule_AddIntConstant(module, "EFFECT_EMPIRE", 223); + PyModule_AddIntConstant(module, "EFFECT_REFINED", 229); + PyModule_AddIntConstant(module, "EFFECT_SUCCESS", 262); + PyModule_AddIntConstant(module, "EFFECT_FAIL", 263); + PyModule_AddIntConstant(module, "EFFECT_FR_SUCCESS", 264); + PyModule_AddIntConstant(module, "EFFECT_LEVELUP_ON_14_FOR_GERMANY", 265); + PyModule_AddIntConstant(module, "EFFECT_LEVELUP_UNDER_15_FOR_GERMANY", 266); + PyModule_AddIntConstant(module, "EFFECT_PERCENT_DAMAGE1", 267); + PyModule_AddIntConstant(module, "EFFECT_PERCENT_DAMAGE2", 268); + PyModule_AddIntConstant(module, "EFFECT_PERCENT_DAMAGE3", 269); + PyModule_AddIntConstant(module, "EFFECT_AUTO_HPUP", 270); + PyModule_AddIntConstant(module, "EFFECT_AUTO_SPUP", 271); + PyModule_AddIntConstant(module, "EFFECT_RAMADAN_RING_EQUIP", 272); + PyModule_AddIntConstant(module, "EFFECT_HALLOWEEN_CANDY_EQUIP", 273); + PyModule_AddIntConstant(module, "EFFECT_HAPPINESS_RING_EQUIP", 274); + PyModule_AddIntConstant(module, "EFFECT_LOVE_PENDANT_EQUIP", 275); + PyModule_AddIntConstant(module, "EFFECT_SASH_SUCCEDED", 277); + PyModule_AddIntConstant(module, "EFFECT_SASH_EQUIP", 278); + PyModule_AddIntConstant(module, "EFFECT_HEALER", 279); + PyModule_AddIntConstant(module, "EFFECT_SHINING_WEAPON", 280); + PyModule_AddIntConstant(module, "EFFECT_SHINING_ARMOR", 14281); + PyModule_AddIntConstant(module, "EFFECT_SHINING_SPECIAL", 14302); + PyModule_AddIntConstant(module, "EFFECT_SKILL_DAMAGE_ZONE", 14313); + PyModule_AddIntConstant(module, "EFFECT_SKILL_DAMAGE_ZONE_BUYUK", 14314); + PyModule_AddIntConstant(module, "EFFECT_SKILL_DAMAGE_ZONE_ORTA", 14315); + PyModule_AddIntConstant(module, "EFFECT_SKILL_DAMAGE_ZONE_KUCUK", 14316); + PyModule_AddIntConstant(module, "EFFECT_SKILL_SAFE_ZONE", 14317); + PyModule_AddIntConstant(module, "EFFECT_SKILL_SAFE_ZONE_BUYUK", 14318); + PyModule_AddIntConstant(module, "EFFECT_SKILL_SAFE_ZONE_KUCUK", 14320); + PyModule_AddIntConstant(module, "EFFECT_SKILL_SAFE_ZONE_ORTA", 14319); + PyModule_AddIntConstant(module, "EFFECT_METEOR", 14321); + PyModule_AddIntConstant(module, "EFFECT_BEAD_RAIN", 14322); + PyModule_AddIntConstant(module, "EFFECT_FALL_ROCK", 14323); + PyModule_AddIntConstant(module, "EFFECT_ARROW_RAIN", 14324); + PyModule_AddIntConstant(module, "EFFECT_HORSE_DROP", 14325); + PyModule_AddIntConstant(module, "EFFECT_EGG_DROP", 14326); + PyModule_AddIntConstant(module, "EFFECT_DEAPO_BOOM", 14327); +} + +void initchr() { + static PyMethodDef s_methods[] = { + {"DismountHorse", chrDismountHorse, METH_VARARGS, nullptr}, + {"MountHorse", chrMountHorse, METH_VARARGS, nullptr}, + {"SetSash", chrSetSash, METH_VARARGS, nullptr}, + {"Destroy", chrDestroy, METH_VARARGS, nullptr}, + {"Update", chrUpdate, METH_VARARGS, nullptr}, + {"Deform", chrDeform, METH_VARARGS, nullptr}, + {"Render", chrRender, METH_VARARGS, nullptr}, + {"RenderCollision", chrRenderCollision, METH_VARARGS, nullptr}, + {"CreateInstance", chrCreateInstance, METH_VARARGS, nullptr}, + {"DeleteInstance", chrDeleteInstance, METH_VARARGS, nullptr}, + {"DeleteInstanceByFade", chrDeleteInstanceByFade, METH_VARARGS, nullptr}, + {"SelectInstance", chrSelectInstance, METH_VARARGS, nullptr}, + {"HasInstance", chrHasInstance, METH_VARARGS, nullptr}, + {"IsEnemy", chrIsEnemy, METH_VARARGS, nullptr}, + {"IsNPC", chrIsNPC, METH_VARARGS, nullptr}, + {"IsGameMaster", chrIsGameMaster, METH_VARARGS, nullptr}, + {"IsPartyMember", chrIsPartyMember, METH_VARARGS, nullptr}, + {"Select", chrSelect, METH_VARARGS, nullptr}, + {"SetAddRenderMode", chrSetAddRenderMode, METH_VARARGS, nullptr}, + {"SetBlendRenderMode", chrSetBlendRenderMode, METH_VARARGS, nullptr}, + {"Unselect", chrUnselect, METH_VARARGS, nullptr}, + {"Hide", chrHide, METH_VARARGS, nullptr}, + {"Show", chrShow, METH_VARARGS, nullptr}, + {"Pick", chrPick, METH_VARARGS, nullptr}, + {"PickAll", chrPickAll, METH_VARARGS, nullptr}, + {"SetArmor", chrSetArmor, METH_VARARGS, nullptr}, + {"SetWeapon", chrSetWeapon, METH_VARARGS, nullptr}, + {"ChangeShape", chrChangeShape, METH_VARARGS, nullptr}, + {"SetRace", chrSetRace, METH_VARARGS, nullptr}, + {"SetHair", chrSetHair, METH_VARARGS, nullptr}, + {"ChangeHair", chrChangeHair, METH_VARARGS, nullptr}, + {"SetVirtualID", chrSetVirtualID, METH_VARARGS, nullptr}, + {"SetNameString", chrSetNameString, METH_VARARGS, nullptr}, + {"SetInstanceType", chrSetInstanceType, METH_VARARGS, nullptr}, + {"SetPixelPosition", chrSetPixelPosition, METH_VARARGS, nullptr}, + {"SetDirection", chrSetDirection, METH_VARARGS, nullptr}, + {"Refresh", chrRefresh, METH_VARARGS, nullptr}, + {"Revive", chrRevive, METH_VARARGS, nullptr}, + {"Die", chrDie, METH_VARARGS, nullptr}, + {"AttachEffectByID", chrAttachEffectByID, METH_VARARGS, nullptr}, + {"AttachEffectByName", chrAttachEffectByName, METH_VARARGS, nullptr}, + {"LookAt", chrLookAt, METH_VARARGS, nullptr}, + {"SetMotionMode", chrSetMotionMode, METH_VARARGS, nullptr}, + {"SetLoopMotion", chrSetLoopMotion, METH_VARARGS, nullptr}, + {"BlendLoopMotion", chrBlendLoopMotion, METH_VARARGS, nullptr}, + {"PushOnceMotion", chrPushOnceMotion, METH_VARARGS, nullptr}, + {"PushLoopMotion", chrPushLoopMotion, METH_VARARGS, nullptr}, + {"GetPixelPosition", chrGetPixelPosition, METH_VARARGS, nullptr}, + {"SetRotation", chrSetRotation, METH_VARARGS, nullptr}, + {"SetRotationAll", chrSetRotationAll, METH_VARARGS, nullptr}, + {"BlendRotation", chrBlendRotation, METH_VARARGS, nullptr}, + {"GetRotation", chrGetRotation, METH_VARARGS, nullptr}, + {"GetRace", chrGetRace, METH_VARARGS, nullptr}, + {"GetName", chrGetName, METH_VARARGS, nullptr}, + {"GetNameByVID", chrGetNameByVID, METH_VARARGS, nullptr}, + {"GetGuildID", chrGetGuildID, METH_VARARGS, nullptr}, + {"GetProjectPosition", chrGetProjectPosition, METH_VARARGS, nullptr}, + {"GetVirtualNumber", chrGetVirtualNumber, METH_VARARGS, nullptr}, + {"GetInstanceType", chrGetInstanceType, METH_VARARGS, nullptr}, + {"GetBoundBoxOnlyXY", chrGetBoundBoxOnlyXY, METH_VARARGS, nullptr}, + {"RaceToJob", chrRaceToJob, METH_VARARGS, nullptr}, + {"RaceToSex", chrRaceToSex, METH_VARARGS, nullptr}, + {"testGetPKData", chrtestGetPKData, METH_VARARGS, nullptr}, + {"FaintTest", chrFaintTest, METH_VARARGS, nullptr}, + {"SetMoveSpeed", chrSetMoveSpeed, METH_VARARGS, nullptr}, + {"SetAttackSpeed", chrSetAttackSpeed, METH_VARARGS, nullptr}, + {"WeaponTraceSetTexture", chrWeaponTraceSetTexture, METH_VARARGS, nullptr}, + {"WeaponTraceUseAlpha", chrWeaponTraceUseAlpha, METH_VARARGS, nullptr}, + {"WeaponTraceUseTexture", chrWeaponTraceUseTexture, METH_VARARGS, nullptr}, + {"MoveToDestPosition", chrMoveToDestPosition, METH_VARARGS, nullptr}, + {"testSetComboType", chrtestSetComboType, METH_VARARGS, nullptr}, + {"testSetAddRenderMode", chrtestSetAddRenderMode, METH_VARARGS, nullptr}, + {"testSetModulateRenderMode", chrtestSetModulateRenderMode, METH_VARARGS, nullptr}, + {"testSetAddRenderModeRGB", chrtestSetAddRenderModeRGB, METH_VARARGS, nullptr}, + {"testSetModulateRenderModeRGB", chrtestSetModulateRenderModeRGB, METH_VARARGS, nullptr}, + {"testSetSpecularRenderMode", chrtestSetSpecularRenderMode, METH_VARARGS, nullptr}, + {"testSetSpecularRenderMode2", chrtestSetSpecularRenderMode2, METH_VARARGS, nullptr}, + {"testRestoreRenderMode", chrtestRestoreRenderMode, METH_VARARGS, nullptr}, + {"testSetRideMan", chrtestSetRideMan, METH_VARARGS, nullptr}, + {"IsStone", chrIsStone, METH_VARARGS, nullptr}, + {nullptr, nullptr, 0, nullptr} + }; + auto* module = Py_InitModule("chr", s_methods); + + PyModule_AddIntConstant(module, "PLAYER_NAME_MAX_LEN", 12); + PyModule_AddIntConstant(module, "MOTION_NONE", 0); + PyModule_AddIntConstant(module, "MOTION_SPAWN", 25); + PyModule_AddIntConstant(module, "MOTION_WAIT", 1); + PyModule_AddIntConstant(module, "MOTION_WALK", 2); + PyModule_AddIntConstant(module, "MOTION_RUN", 3); + PyModule_AddIntConstant(module, "MOTION_CHANGE_WEAPON", 4); + PyModule_AddIntConstant(module, "MOTION_DAMAGE", 5); + PyModule_AddIntConstant(module, "MOTION_DAMAGE_FLYING", 6); + PyModule_AddIntConstant(module, "MOTION_STAND_UP", 7); + PyModule_AddIntConstant(module, "MOTION_DAMAGE_BACK", 8); + PyModule_AddIntConstant(module, "MOTION_DAMAGE_FLYING_BACK", 9); + PyModule_AddIntConstant(module, "MOTION_STAND_UP_BACK", 10); + PyModule_AddIntConstant(module, "MOTION_DEAD", 11); + PyModule_AddIntConstant(module, "MOTION_DEAD_BACK", 12); + PyModule_AddIntConstant(module, "MOTION_NORMAL_ATTACK", 13); + PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_1", 14); + PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_2", 15); + PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_3", 16); + PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_4", 17); + PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_5", 18); + PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_6", 19); + PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_7", 20); + PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_8", 21); + PyModule_AddIntConstant(module, "MOTION_INTRO_WAIT", 22); + PyModule_AddIntConstant(module, "MOTION_INTRO_SELECTED", 23); + PyModule_AddIntConstant(module, "MOTION_INTRO_NOT_SELECTED", 24); + PyModule_AddIntConstant(module, "MOTION_FISHING_THROW", 26); + PyModule_AddIntConstant(module, "MOTION_FISHING_WAIT", 27); + PyModule_AddIntConstant(module, "MOTION_FISHING_STOP", 28); + PyModule_AddIntConstant(module, "MOTION_FISHING_REACT", 29); + PyModule_AddIntConstant(module, "MOTION_FISHING_CATCH", 30); + PyModule_AddIntConstant(module, "MOTION_FISHING_FAIL", 31); + PyModule_AddIntConstant(module, "MOTION_STOP", 32); + PyModule_AddIntConstant(module, "MOTION_SKILL", 50); + PyModule_AddIntConstant(module, "MOTION_CLAP", 306); + PyModule_AddIntConstant(module, "MOTION_DANCE_1", 326); + PyModule_AddIntConstant(module, "MOTION_DANCE_2", 327); + PyModule_AddIntConstant(module, "MOTION_DANCE_3", 328); + PyModule_AddIntConstant(module, "MOTION_DANCE_4", 329); + PyModule_AddIntConstant(module, "MOTION_DANCE_5", 330); + PyModule_AddIntConstant(module, "MOTION_DANCE_6", 331); + PyModule_AddIntConstant(module, "MOTION_CONGRATULATION", 343); + PyModule_AddIntConstant(module, "MOTION_FORGIVE", 344); + PyModule_AddIntConstant(module, "MOTION_ANGRY", 345); + PyModule_AddIntConstant(module, "MOTION_ATTRACTIVE", 346); + PyModule_AddIntConstant(module, "MOTION_SAD", 347); + PyModule_AddIntConstant(module, "MOTION_SHY", 348); + PyModule_AddIntConstant(module, "MOTION_CHEERUP", 349); + PyModule_AddIntConstant(module, "MOTION_BANTER", 350); + PyModule_AddIntConstant(module, "MOTION_JOY", 351); + PyModule_AddIntConstant(module, "MOTION_CHEERS_1", 307); + PyModule_AddIntConstant(module, "MOTION_CHEERS_2", 308); + PyModule_AddIntConstant(module, "MOTION_KISS_WITH_WARRIOR", 309); + PyModule_AddIntConstant(module, "MOTION_KISS_WITH_ASSASSIN", 310); + PyModule_AddIntConstant(module, "MOTION_KISS_WITH_SURA", 311); + PyModule_AddIntConstant(module, "MOTION_KISS_WITH_SHAMAN", 312); + PyModule_AddIntConstant(module, "MOTION_FRENCH_KISS_WITH_WARRIOR", 313); + PyModule_AddIntConstant(module, "MOTION_FRENCH_KISS_WITH_ASSASSIN", 314); + PyModule_AddIntConstant(module, "MOTION_FRENCH_KISS_WITH_SURA", 315); + PyModule_AddIntConstant(module, "MOTION_FRENCH_KISS_WITH_SHAMAN", 316); + PyModule_AddIntConstant(module, "MOTION_SLAP_HIT_WITH_WARRIOR", 317); + PyModule_AddIntConstant(module, "MOTION_SLAP_HIT_WITH_ASSASSIN", 318); + PyModule_AddIntConstant(module, "MOTION_SLAP_HIT_WITH_SURA", 319); + PyModule_AddIntConstant(module, "MOTION_SLAP_HIT_WITH_SHAMAN", 320); + PyModule_AddIntConstant(module, "MOTION_SLAP_HURT_WITH_WARRIOR", 321); + PyModule_AddIntConstant(module, "MOTION_SLAP_HURT_WITH_ASSASSIN", 322); + PyModule_AddIntConstant(module, "MOTION_SLAP_HURT_WITH_SURA", 323); + PyModule_AddIntConstant(module, "MOTION_SLAP_HURT_WITH_SHAMAN", 324); + PyModule_AddIntConstant(module, "MOTION_DIG", 325); + PyModule_AddIntConstant(module, "MOTION_MODE_RESERVED", 0); + PyModule_AddIntConstant(module, "MOTION_MODE_GENERAL", 1); + PyModule_AddIntConstant(module, "MOTION_MODE_ONEHAND_SWORD", 2); + PyModule_AddIntConstant(module, "MOTION_MODE_TWOHAND_SWORD", 3); + PyModule_AddIntConstant(module, "MOTION_MODE_DUALHAND_SWORD", 4); + PyModule_AddIntConstant(module, "MOTION_MODE_BOW", 5); + PyModule_AddIntConstant(module, "MOTION_MODE_FAN", 6); + PyModule_AddIntConstant(module, "MOTION_MODE_BELL", 7); + PyModule_AddIntConstant(module, "MOTION_MODE_FISHING", 8); + PyModule_AddIntConstant(module, "MOTION_MODE_HORSE", 9); + PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_ONEHAND_SWORD", 10); + PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_TWOHAND_SWORD", 11); + PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_DUALHAND_SWORD", 12); + PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_BOW", 13); + PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_FAN", 14); + PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_BELL", 15); + PyModule_AddIntConstant(module, "MOTION_MODE_WEDDING_DRESS", 16); + PyModule_AddIntConstant(module, "MOTION_MODE_CLAW", 17); + PyModule_AddIntConstant(module, "MOTION_MODE_BOW_SPECIAL", 18); + PyModule_AddIntConstant(module, "DIR_NORTH", 0); + PyModule_AddIntConstant(module, "DIR_NORTHEAST", 1); + PyModule_AddIntConstant(module, "DIR_EAST", 2); + PyModule_AddIntConstant(module, "DIR_SOUTHEAST", 3); + PyModule_AddIntConstant(module, "DIR_SOUTH", 4); + PyModule_AddIntConstant(module, "DIR_SOUTHWEST", 5); + PyModule_AddIntConstant(module, "DIR_WEST", 6); + PyModule_AddIntConstant(module, "DIR_NORTHWEST", 7); + PyModule_AddIntConstant(module, "INSTANCE_TYPE_PLAYER", 6); + PyModule_AddIntConstant(module, "INSTANCE_TYPE_NPC", 1); + PyModule_AddIntConstant(module, "INSTANCE_TYPE_ENEMY", 0); + PyModule_AddIntConstant(module, "INSTANCE_TYPE_BUILDING", 5); + PyModule_AddIntConstant(module, "INSTANCE_TYPE_OBJECT", 11); + PyModule_AddIntConstant(module, "PART_WEAPON", 1); + PyModule_AddIntConstant(module, "PART_HEAD", 2); + PyModule_AddIntConstant(module, "PART_WEAPON_LEFT", 3); + PyModule_AddIntConstant(module, "PART_SASH", 5); + PyModule_AddIntConstant(module, "AFFECT_POISON", 3); + PyModule_AddIntConstant(module, "AFFECT_SLOW", 4); + PyModule_AddIntConstant(module, "AFFECT_STUN", 5); + PyModule_AddIntConstant(module, "AFFECT_MOV_SPEED_POTION", 11); + PyModule_AddIntConstant(module, "AFFECT_ATT_SPEED_POTION", 12); + PyModule_AddIntConstant(module, "AFFECT_FISH_MIND", 13); + PyModule_AddIntConstant(module, "AFFECT_JEONGWI", 14); + PyModule_AddIntConstant(module, "AFFECT_GEOMGYEONG", 15); + PyModule_AddIntConstant(module, "AFFECT_CHEONGEUN", 16); + PyModule_AddIntConstant(module, "AFFECT_GYEONGGONG", 17); + PyModule_AddIntConstant(module, "AFFECT_EUNHYEONG", 18); + PyModule_AddIntConstant(module, "AFFECT_GWIGEOM", 19); + PyModule_AddIntConstant(module, "AFFECT_GONGPO", 20); + PyModule_AddIntConstant(module, "AFFECT_JUMAGAP", 21); + PyModule_AddIntConstant(module, "AFFECT_HOSIN", 22); + PyModule_AddIntConstant(module, "AFFECT_BOHO", 23); + PyModule_AddIntConstant(module, "AFFECT_KWAESOK", 24); + PyModule_AddIntConstant(module, "AFFECT_HEUKSIN", 25); + PyModule_AddIntConstant(module, "AFFECT_MUYEONG", 26); + PyModule_AddIntConstant(module, "AFFECT_GICHEON", 29); + PyModule_AddIntConstant(module, "AFFECT_JEUNGRYEOK", 30); + PyModule_AddIntConstant(module, "AFFECT_PABEOP", 32); + PyModule_AddIntConstant(module, "AFFECT_FALLEN_CHEONGEUN", 33); + PyModule_AddIntConstant(module, "AFFECT_CHINA_FIREWORK", 38); + PyModule_AddIntConstant(module, "AFFECT_BLEEDING", 42); + PyModule_AddIntConstant(module, "AFFECT_RED_POSSESSION", 43); + PyModule_AddIntConstant(module, "AFFECT_BLUE_POSSESSION", 44); + PyModule_AddIntConstant(module, "AFFECT_CHEONUN", 46); + PyModule_AddIntConstant(module, "NEW_AFFECT_MULTI_FARM", 704); + PyModule_AddIntConstant(module, "NEW_AFFECT_AUTO_PICK_UP", 705); + PyModule_AddIntConstant(module, "NEW_AFFECT_VOTE4BUFF", 809); + PyModule_AddIntConstant(module, "NEW_AFFECT_MALL", 510); + PyModule_AddIntConstant(module, "NEW_AFFECT_NO_DEATH_PENALTY", 511); + PyModule_AddIntConstant(module, "NEW_AFFECT_SKILL_BOOK_BONUS", 512); + PyModule_AddIntConstant(module, "NEW_AFFECT_SKILL_BOOK_NO_DELAY", 513); + PyModule_AddIntConstant(module, "NEW_AFFECT_EXP_BONUS", 500); + PyModule_AddIntConstant(module, "NEW_AFFECT_EXP_BONUS_EURO_FREE", 516); + PyModule_AddIntConstant(module, "NEW_AFFECT_EXP_BONUS_EURO_FREE_UNDER_15", 517); + PyModule_AddIntConstant(module, "NEW_AFFECT_ITEM_BONUS", 501); + PyModule_AddIntConstant(module, "NEW_AFFECT_SAFEBOX", 502); + PyModule_AddIntConstant(module, "NEW_AFFECT_AUTOLOOT", 503); + PyModule_AddIntConstant(module, "NEW_AFFECT_FISH_MIND", 504); + PyModule_AddIntConstant(module, "NEW_AFFECT_MARRIAGE_FAST", 505); + PyModule_AddIntConstant(module, "NEW_AFFECT_GOLD_BONUS", 506); + PyModule_AddIntConstant(module, "NEW_AFFECT_AUTO_HP_RECOVERY", 534); + PyModule_AddIntConstant(module, "NEW_AFFECT_AUTO_SP_RECOVERY", 535); + PyModule_AddIntConstant(module, "AFFECT_AUTO_ATTACK_SPEED_RECOVERY", 850); + PyModule_AddIntConstant(module, "AFFECT_AUTO_MOV_SPEED_RECOVERY", 851); + PyModule_AddIntConstant(module, "AFFECT_AUTO_CRITICAL_RECOVERY", 852); + PyModule_AddIntConstant(module, "AFFECT_AUTO_PENETRATE_RECOVERY", 853); + PyModule_AddIntConstant(module, "AFFECT_AUTO_VIT_RECOVERY", 854); + PyModule_AddIntConstant(module, "AFFECT_AUTO_STR_RECOVERY", 855); + PyModule_AddIntConstant(module, "AFFECT_AUTO_INT_RECOVERY", 856); + PyModule_AddIntConstant(module, "AFFECT_AUTO_DEX_RECOVERY", 857); + PyModule_AddIntConstant(module, "AFFECT_AUTO_RED_POTION_RECOVERY", 858); + PyModule_AddIntConstant(module, "AFFECT_AUTO_ORANGE_POTION_RECOVERY", 859); + PyModule_AddIntConstant(module, "AFFECT_AUTO_YELLOW_POTION_RECOVERY", 860); + PyModule_AddIntConstant(module, "AFFECT_AUTO_GREEN_POTION_RECOVERY", 861); + PyModule_AddIntConstant(module, "AFFECT_AUTO_BLUE_POTION_RECOVERY", 862); + PyModule_AddIntConstant(module, "AFFECT_AUTO_WHITE_POTION_RECOVERY", 863); + PyModule_AddIntConstant(module, "NEW_AFFECT_DRAGON_SOUL_QUALIFIED", 540); + PyModule_AddIntConstant(module, "NEW_AFFECT_DRAGON_SOUL_DECK1", 541); + PyModule_AddIntConstant(module, "NEW_AFFECT_DRAGON_SOUL_DECK2", 542); + PyModule_AddIntConstant(module, "AFFECT_POTION_1", 303); + PyModule_AddIntConstant(module, "AFFECT_POTION_2", 304); + PyModule_AddIntConstant(module, "AFFECT_POTION_3", 305); + PyModule_AddIntConstant(module, "AFFECT_POTION_4", 306); + PyModule_AddIntConstant(module, "AFFECT_POTION_5", 307); + PyModule_AddIntConstant(module, "AFFECT_POTION_6", 308); + PyModule_AddIntConstant(module, "NEW_AFFECT_DECORATION", 703); + PyModule_AddIntConstant(module, "AFFECT_STATUE1", 48); + PyModule_AddIntConstant(module, "AFFECT_STATUE2", 49); + PyModule_AddIntConstant(module, "AFFECT_STATUE3", 50); + PyModule_AddIntConstant(module, "AFFECT_STATUE4", 51); +} + +} // namespace ava2 diff --git a/src/python_cube_renewal.cpp b/src/python_cube_renewal.cpp new file mode 100644 index 00000000..0f147ddb --- /dev/null +++ b/src/python_cube_renewal.cpp @@ -0,0 +1,44 @@ +// AVA2 UserInterface/PythonCubeRenewal.cpp and ENABLE_CUBE_RENEWAL_WORLDARD. +#include "cube_renewal_state.h" +#include "python_native_modules.h" +#include "eter_net/PythonNetworkStream.h" +#include "shared/common/PythonUtils.h" +#include +#include +namespace ava2 { +CubeRenewalState& GetCubeRenewalState() { static CubeRenewalState state;return state; } +void CubeRenewalState::SetHandler(PyObject* value) { + Py_XINCREF(value);auto* old=handler;handler=value;Py_XDECREF(old); +} +void CubeRenewalState::LoadingList() { PyCallClassMemberFunc(handler,"BINARY_CUBE_RENEWAL_LOADING",Py_BuildValue("()")); } +void CubeRenewalState::Reset() { records.clear();SetHandler(nullptr); } +namespace { +PyObject* count(PyObject*,PyObject*) { return PyInt_FromLong(GetCubeRenewalState().records.size()); } +PyObject* dates(PyObject*,PyObject* args) { + int index;if(!PyTuple_GetInteger(args,0,&index))return Py_BuildException(); + const auto& records=GetCubeRenewalState().records; + if(uint32_t(index)>=records.size())return Py_BuildValue("iibiiiiiiiiiiiis",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"None"); + const auto& r=records[index];const std::string category(r.category,strnlen(r.category,sizeof(r.category))); + return Py_BuildValue("iibiiiiiiiiiiiis",std::bit_cast(r.vnum_reward),r.count_reward,int(r.item_reward_stackable!=0), + std::bit_cast(r.vnum_material_1),r.count_material_1,std::bit_cast(r.vnum_material_2),r.count_material_2, + std::bit_cast(r.vnum_material_3),r.count_material_3,std::bit_cast(r.vnum_material_4),r.count_material_4, + std::bit_cast(r.vnum_material_5),r.count_material_5,r.gold,r.percent,category.c_str()); +} +PyObject* handler(PyObject*,PyObject* args) { + PyObject* value;if(!PyTuple_GetObject(args,0,&value))return Py_BuildException(); + GetCubeRenewalState().SetHandler(value);Py_RETURN_NONE; +} +PyObject* make(PyObject*,PyObject* args) { + int index,count;if(!PyTuple_GetInteger(args,0,&index)||!PyTuple_GetInteger(args,1,&count))return Py_BuildException(); + PythonNetworkStream::Instance().SendCubeRenewalPacket(false,uint32_t(index),uint32_t(count));Py_RETURN_NONE; +} +PyObject* close(PyObject*,PyObject*) { PythonNetworkStream::Instance().SendCubeRenewalPacket(true);Py_RETURN_NONE; } +} +void intcuberenewal() { + static PyMethodDef methods[]={ + {"CountDates",count,METH_VARARGS,nullptr},{"GetDates",dates,METH_VARARGS,nullptr}, + {"SetCubeRenewalHandler",handler,METH_VARARGS,nullptr},{"CubeRenewalMakeItem",make,METH_VARARGS,nullptr}, + {"CubeRenewalClose",close,METH_VARARGS,nullptr},{nullptr,nullptr,0,nullptr}}; + Py_InitModule("cube_renewal",methods); +} +} diff --git a/src/python_drop_item.cpp b/src/python_drop_item.cpp new file mode 100644 index 00000000..76ea1a8f --- /dev/null +++ b/src/python_drop_item.cpp @@ -0,0 +1,37 @@ +// Direct port of AVA2 UserInterface/PythonDropItem.cpp. +#include "drop_item_state.h" +#include "python_native_modules.h" +#include "eter_net/PythonNetworkStream.h" +#include "shared/common/PythonUtils.h" +#include +namespace ava2 { +DropItemState& GetDropItemState() {static DropItemState state;return state;} +void DropItemState::SetHandler(PyObject* value) {Py_XINCREF(value);auto* old=handler;handler=value;Py_XDECREF(old);} +void DropItemState::Clear() {page=1;records.clear();} +void DropItemState::Loading() {PyCallClassMemberFunc(handler,"BINARY_DROP_ITEM_LOADING",Py_BuildValue("()"));} +void DropItemState::Reset() {Clear();SetHandler(nullptr);} +namespace { +PyObject* open(PyObject*,PyObject*) {PythonNetworkStream::Instance().SendDropItemPacket(false);Py_RETURN_NONE;} +PyObject* search(PyObject*,PyObject* args) {int vnum;if(!PyTuple_GetInteger(args,0,&vnum))return Py_BuildException();PythonNetworkStream::Instance().SendDropItemPacket(true,vnum);Py_RETURN_NONE;} +PyObject* count(PyObject*,PyObject*) {return PyInt_FromLong(GetDropItemState().records.size());} +PyObject* dates(PyObject*,PyObject* args) { + int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException(); + const auto& data=GetDropItemState().records; + if(uint32_t(i)>=data.size())return Py_BuildValue("siii","None",0,0,0); + const auto& r=data[i];const std::string name(r.name_mob,strnlen(r.name_mob,sizeof(r.name_mob))); + return Py_BuildValue("siii",name.c_str(),int32_t(r.id_mob),int32_t(r.prob_item),r.count_item); +} +PyObject* page_view(PyObject*,PyObject*) {return PyInt_FromLong(5);} +PyObject* select(PyObject*,PyObject* args) {int page;if(!PyTuple_GetInteger(args,0,&page))return Py_BuildException();GetDropItemState().page=page;Py_RETURN_NONE;} +PyObject* page(PyObject*,PyObject*) {return PyInt_FromLong(GetDropItemState().page);} +PyObject* handler(PyObject*,PyObject* args) {PyObject* value;if(!PyTuple_GetObject(args,0,&value))return Py_BuildException();GetDropItemState().SetHandler(value);Py_RETURN_NONE;} +} +void intdropitem() { + static PyMethodDef methods[]={ + {"Open",open,METH_VARARGS,nullptr},{"SearchItem",search,METH_VARARGS,nullptr}, + {"CountDates",count,METH_VARARGS,nullptr},{"GetDates",dates,METH_VARARGS,nullptr}, + {"GetPageView",page_view,METH_VARARGS,nullptr},{"SetPageSelect",select,METH_VARARGS,nullptr}, + {"GetPageActual",page,METH_VARARGS,nullptr},{"SetDropItemHandler",handler,METH_VARARGS,nullptr},{nullptr,nullptr,0,nullptr}}; + Py_InitModule("drop_item",methods); +} +} diff --git a/src/python_dungeon_info.cpp b/src/python_dungeon_info.cpp new file mode 100644 index 00000000..ae56d020 --- /dev/null +++ b/src/python_dungeon_info.cpp @@ -0,0 +1,51 @@ +// Direct port of AVA2 UserInterface/PythonDungeonInfo.cpp. +#include "dungeon_info_state.h" +#include "python_native_modules.h" +#include "eter_net/PythonNetworkStream.h" +#include "shared/common/PythonUtils.h" +#include +namespace ava2 { +DungeonInfoState& GetDungeonInfoState() {static DungeonInfoState state;return state;} +namespace { +template std::string text(const char (&value)[N]) {return std::string(value,strnlen(value,N));} +PyObject* count(PyObject*,PyObject*) {return PyInt_FromLong(GetDungeonInfoState().info.size());} +PyObject* count_ranking(PyObject*,PyObject*) {return PyInt_FromLong(GetDungeonInfoState().ranking.size());} +PyObject* page_view(PyObject*,PyObject*) {return PyInt_FromLong(13);} +PyObject* page(PyObject*,PyObject*) {return PyInt_FromLong(GetDungeonInfoState().page);} +PyObject* set_page(PyObject*,PyObject* args) {int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException();GetDungeonInfoState().page=i;Py_RETURN_NONE;} +PyObject* info(PyObject*,PyObject* args) { + int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException(); + const auto& data=GetDungeonInfoState().info; + if(uint32_t(i)>=data.size())return Py_BuildValue("issiiiiiiisssiiiiiiii",0,"None","None",0,0,0,0,0,0,0,"None","None","None",0,0,0,0,0,0,0,0); + const auto& r=data[i]; + return Py_BuildValue("issiiiiiiisssiiiiiiii",r.id,text(r.name).c_str(),text(r.img).c_str(),r.lv_min,r.lv_max,r.party_max, + int32_t(r.respawn),int32_t(r.time_room),r.time_respawn_dungeon,r.time_room_dungeon, + text(r.entrance).c_str(),text(r.resistance).c_str(),text(r.force).c_str(),r.vnum_item,r.count_item,r.count_finish, + r.time_finish,r.difficulty,r.damage_done,r.damage_received,r.id_boss); +} +PyObject* mission(PyObject*,PyObject* args) { + int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException();const auto& data=GetDungeonInfoState().missions; + if(uint32_t(i)>=data.size())return Py_BuildValue("iiii",0,0,0,0); + const auto& r=data[i];return Py_BuildValue("iiii",r.vnum_mob_mision,r.count_mob_mision,r.count_mob_a_mision,r.status_mision); +} +PyObject* ranking(PyObject*,PyObject* args) { + int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException();const auto& data=GetDungeonInfoState().ranking; + if(uint32_t(i)>=data.size())return Py_BuildValue("iisi",0,0,"None",0); + const auto& r=data[i];return Py_BuildValue("iisi",r.vnum_mob_r,r.type,text(r.name_r).c_str(),r.extra_r); +} +PyObject* open(PyObject*,PyObject*) {PythonNetworkStream::Instance().SendDungeonInfoPacket(DUNGEON_INFO_SUB_HEADER_OPEN);Py_RETURN_NONE;} +template PyObject* request(PyObject*,PyObject* args) { + int i;if(!PyTuple_GetInteger(args,0,&i))return Py_BuildException();PythonNetworkStream::Instance().SendDungeonInfoPacket(Sub,i);Py_RETURN_NONE; +} +} +void intdungeoninfo() { + static PyMethodDef methods[]={ + {"CountDateRanking",count_ranking,METH_VARARGS,nullptr},{"InfoDateRanking",ranking,METH_VARARGS,nullptr}, + {"InfoDateMision",mission,METH_VARARGS,nullptr},{"CountDate",count,METH_VARARGS,nullptr},{"InfoDate",info,METH_VARARGS,nullptr}, + {"Open",open,METH_VARARGS,nullptr},{"Teleport",request,METH_VARARGS,nullptr}, + {"Ranking",request,METH_VARARGS,nullptr},{"Mision",request,METH_VARARGS,nullptr}, + {"SetPageCount",set_page,METH_VARARGS,nullptr},{"GetPageCount",page,METH_VARARGS,nullptr},{"GetPageView",page_view,METH_VARARGS,nullptr}, + {nullptr,nullptr,0,nullptr}}; + Py_InitModule("dungeon_info",methods); +} +} diff --git a/src/python_event_manager.cpp b/src/python_event_manager.cpp new file mode 100644 index 00000000..14bbbae7 --- /dev/null +++ b/src/python_event_manager.cpp @@ -0,0 +1,1466 @@ +// Provenance: AVA2 UserInterface/PythonEventManager.cpp + PythonEventManagerMoudle.cpp +// (ENABLE_MULTILANGUAGE_SYSTEM: event.AddEvent). Ported line by line; differences: +// - Methods that dereference m_EventSetVector[i] without a NULL check on Windows (Skip, +// SetVisibleLineCount, SetVisibleStartLine, GetVisibleStartLine, GetLineCount, and GetLineHeight +// on an empty line list) return their "no set" value for a cleared slot instead of crashing. +// - The port has no minimap atlas signals or event camera (IAbstractApplication) yet: ADDMAPSIGNAL, +// CLEARMAPSIGNAL, SETCMAPPOS, SET_CAMERA, BLEND_CAMERA and RESTORE_CAMERA are consumed without +// effect. Text lines are the port's CGraphicTextInstance (no real font yet). +#include "python_event_manager.h" +#include "python_app.h" +#include "python_gameplay_modules.h" +#include "python_native_modules.h" +#include "python_minimap.h" +#include "python_runtime.h" +#include "nonplayer_data.h" +#include "eter_net/PythonNetworkStream.h" +#include "shared/common/PythonUtils.h" +#include +#include +#include +#include +#include + +namespace ava2 { +namespace { + +const long c_lNormal_Waiting_Time = 10; +const int c_fLine_Temp = 16; +const unsigned CP_1256 = 1256; + +const std::string& GetArgumentString(const char* c_szName, script::TArgList& rArgumentList) +{ + for (auto& arg : rArgumentList) + if (0 == arg.strName.compare(c_szName)) + return arg.strValue; + + static std::string strEmptyValue = ""; + return strEmptyValue; +} + +const char* GetArgument(const char* c_szName, script::TArgList& rArgumentList) +{ + return GetArgumentString(c_szName, rArgumentList).c_str(); +} + +// EterBase _getf: the left-time format comes from the client (event.SetLeftTimeString) like on Windows. +std::string FormatLeftTime(const std::string& format, int iLeftTime) +{ + char buf[1024]; +#if defined(__clang__) || defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#pragma GCC diagnostic ignored "-Wformat-security" +#endif + std::snprintf(buf, sizeof(buf), format.c_str(), iLeftTime); +#if defined(__clang__) || defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + return buf; +} + +// Calls with a new reference to a borrowed handler; a collected or unset handler is NULL, which +// PyCallClassMemberFunc treats like Windows' NULL poEventHandler. +void CallMember(const CPythonEventManager::CBorrowedObject& object, const char* c_szFunc, PyObject* poArgs) +{ + PyObject* poObject = object.Get(); + PyCallClassMemberFunc(poObject, c_szFunc, poArgs); + Py_XDECREF(poObject); +} + +} // namespace + +void CPythonEventManager::CBorrowedObject::Reset(PyObject* object) +{ + if (m_isWeak) + Py_XDECREF(m_ref); + m_ref = nullptr; + m_isWeak = false; + if (!object) + return; + + if (PyObject* ref = PyWeakref_NewRef(object, nullptr)) + { + m_ref = ref; + m_isWeak = true; + return; + } + PyErr_Clear(); + m_ref = object; +} + +PyObject* CPythonEventManager::CBorrowedObject::Get() const +{ + PyObject* object = m_isWeak ? PyWeakref_GetObject(m_ref) : m_ref; + if (!object || object == Py_None && m_isWeak) + return nullptr; + Py_INCREF(object); + return object; +} + +CPythonEventManager& CPythonEventManager::Instance() +{ + static CPythonEventManager s_instance; + return s_instance; +} + +void CPythonEventManager::__InitEventSet(TEventSet& rEventSet) +{ + rEventSet.ix = 0; + rEventSet.iy = 0; + rEventSet.iWidth = 0; + rEventSet.iyLocal = 0; + + rEventSet.isLock = false; + rEventSet.lLastDelayTime = 0; + rEventSet.iCurrentLetter = 0; + rEventSet.CurrentColor = TColor(); + rEventSet.strCurrentLine = ""; + + rEventSet.pCurrentTextLine = nullptr; + rEventSet.ScriptTextLineList.clear(); + + rEventSet.isConfirmWait = false; + rEventSet.pConfirmTimeTextLine = nullptr; + rEventSet.iConfirmEndTime = 0; + + rEventSet.DiffuseColor = TColor(); + rEventSet.lWaitingTime = c_lNormal_Waiting_Time; + rEventSet.iRestrictedCharacterCount = 30; + + rEventSet.iVisibleStartLine = 0; + rEventSet.iVisibleLineCount = BOX_VISIBLE_LINE_COUNT; + + rEventSet.iAdjustLine = 0; + + rEventSet.isTextCenterMode = false; + rEventSet.isWaitFlag = false; + + __InsertLine(rEventSet); +} + +int CPythonEventManager::RegisterEventSet(const char* c_szFileName) +{ + // CEterPackManager::Get + File.Read into a Size()+1 buffer: the script ends with a NUL. + std::string strEventString; + try + { + strEventString = ReadPackedText(c_szFileName); + } + catch (const std::exception&) + { + return -1; + } + strEventString.push_back('\0'); + + TEventSet* pEventSet = m_EventSetPool.Alloc(); + if (!pEventSet) + return -1; + + pEventSet->pCurrentTextLine = nullptr; // __ClearEventSetp on a reused set + pEventSet->ScriptTextLineList.clear(); + int iScriptGroup = pEventSet->ScriptGroup.Create(strEventString); + if (-1 == iScriptGroup) + { + __ClearEventSetp(pEventSet); + return -1; + } + + pEventSet->iTotalLineCount = iScriptGroup; + + std::strncpy(pEventSet->szFileName, c_szFileName, 32); + pEventSet->szFileName[32] = '\0'; + + pEventSet->pCurrentTextLine = nullptr; + pEventSet->poEventHandler.Reset(nullptr); + + __InitEventSet(*pEventSet); + + const unsigned iEmptySlotIndex = GetEmptyEventSetSlot(); + m_EventSetVector[iEmptySlotIndex] = pEventSet; + return int(iEmptySlotIndex); +} + +void CPythonEventManager::SetVisibleLineCount(int iIndex, int iLineCount) +{ + if (TEventSet* pEventSet = __GetEventSet(iIndex)) + pEventSet->iVisibleLineCount = iLineCount; +} + +int CPythonEventManager::GetLineHeight(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + if (!pEventSet) + return 0; + + // Windows reads ScriptTextLineList.front() even when the list is empty (no line inserted yet). + if (pEventSet->ScriptTextLineList.empty()) + return pEventSet->pCurrentTextLine ? pEventSet->pCurrentTextLine->GetLineHeight() : 0; + + return pEventSet->ScriptTextLineList.front().pInstance->GetLineHeight(); +} + +int CPythonEventManager::GetTotalLineCount(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + return pEventSet ? pEventSet->iTotalLineCount : 0; +} + +int CPythonEventManager::RegisterEventSetFromString(const std::string& strScript) +{ + TEventSet* pEventSet = m_EventSetPool.Alloc(); + if (!pEventSet) + return -1; + + // SCRIPT_PARSING_FAILURE_CLEAR_BUG + pEventSet->pCurrentTextLine = nullptr; + pEventSet->ScriptTextLineList.clear(); + // END_OF_SCRIPT_PARSING_FAILURE_CLEAR_BUG + + int iScriptGroup = pEventSet->ScriptGroup.Create(strScript); + if (-1 == iScriptGroup) + { + __ClearEventSetp(pEventSet); + return -1; + } + + pEventSet->iTotalLineCount = iScriptGroup; + + pEventSet->szFileName[0] = 0; + pEventSet->poEventHandler.Reset(nullptr); + __InitEventSet(*pEventSet); + + // A script that starts with [RUN_CINEMA value;file] plays that file instead. + script::TCmd ScriptCommand; + int pEventPosition; + int iEventType; + if (pEventSet->ScriptGroup.ReadCmd(ScriptCommand)) + { + if (GetScriptEventIndex(ScriptCommand.name.c_str(), &pEventPosition, &iEventType)) + { + if (EVENT_TYPE_RUN_CINEMA == iEventType) + { + std::string strFileName = GetArgument("value", ScriptCommand.argList); + __ClearEventSetp(pEventSet); + return RegisterEventSet(strFileName.c_str()); + } + } + } + + const unsigned iEmptySlotIndex = GetEmptyEventSetSlot(); + m_EventSetVector[iEmptySlotIndex] = pEventSet; + return int(iEmptySlotIndex); +} + +void CPythonEventManager::ClearEventSeti(int iIndex) +{ + if (!CheckEventSetIndex(iIndex)) + return; + + __ClearEventSetp(m_EventSetVector[iIndex]); + m_EventSetVector[iIndex] = nullptr; +} + +void CPythonEventManager::__ClearEventSetp(TEventSet* pEventSet) +{ + if (!pEventSet) + return; + + for (TTextLine& rkLine : pEventSet->ScriptTextLineList) + { + rkLine.pInstance->Destroy(); + m_ScriptTextLinePool.Free(rkLine.pInstance); + } + pEventSet->ScriptTextLineList.clear(); + + if (pEventSet->pCurrentTextLine) + { + pEventSet->pCurrentTextLine->Destroy(); + m_ScriptTextLinePool.Free(pEventSet->pCurrentTextLine); + } + pEventSet->pCurrentTextLine = nullptr; + pEventSet->strCurrentLine = ""; + pEventSet->iCurrentLetter = 0; + pEventSet->poEventHandler.Reset(nullptr); + + m_EventSetPool.Free(pEventSet); +} + +unsigned CPythonEventManager::GetEmptyEventSetSlot() +{ + for (unsigned i = 0; i < m_EventSetVector.size(); ++i) + if (nullptr == m_EventSetVector[i]) + return i; + + m_EventSetVector.push_back(nullptr); + return unsigned(m_EventSetVector.size() - 1); +} + +void CPythonEventManager::SetRestrictedCount(int iIndex, int iCount) +{ + if (!CheckEventSetIndex(iIndex)) + return; + + TEventSet* pEventSet = m_EventSetVector[iIndex]; + if (!pEventSet) + { + SDL_Log("CPythonEventManager::SetRestrictedCount m_EventSetVector[iIndex=%d]==NULL", iIndex); + return; + } + + pEventSet->iRestrictedCharacterCount = iCount; +} + +void CPythonEventManager::SetEventHandler(int iIndex, PyObject* poEventHandler) +{ + if (!CheckEventSetIndex(iIndex)) + return; + + TEventSet* pEventSet = m_EventSetVector[iIndex]; + if (!pEventSet) + { + SDL_Log("CPythonEventManager::SetEventHandler m_EventSetVector[iIndex=%d]==NULL", iIndex); + return; + } + + pEventSet->poEventHandler.Reset(poEventHandler); +} + +int CPythonEventManager::GetEventSetLocalYPosition(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + return pEventSet ? pEventSet->iyLocal : 0; +} + +void CPythonEventManager::AddEventSetLocalYPosition(int iIndex, int iAddValue) +{ + if (TEventSet* pEventSet = __GetEventSet(iIndex)) + pEventSet->iyLocal += iAddValue; +} + +void CPythonEventManager::InsertText(int iIndex, const char* c_szText, int iX_pos) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + if (!pEventSet) + return; + + pEventSet->strCurrentLine = c_szText; + if (pEventSet->pCurrentTextLine) + { + pEventSet->pCurrentTextLine->SetValue(c_szText); + if (iX_pos == 0) + pEventSet->pCurrentTextLine->SetHorizonalAlign(CGraphicTextInstance::HORIZONTAL_ALIGN_CENTER); + pEventSet->pCurrentTextLine->Update(); + } + + __InsertLine(*pEventSet, false, iX_pos); +} + +void CPythonEventManager::UpdateEventSet(int iIndex, int ix, int iy) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + if (!pEventSet) + return; + + pEventSet->ix = ix; + pEventSet->iy = iy; + + RefreshLinePosition(pEventSet); + + if (pEventSet->isConfirmWait) + { + // max(0, int - DWORD) is unsigned on Windows: an expired wait shows a negative count. + const int iLeftTime = int(uint32_t(pEventSet->iConfirmEndTime) - GetLocalMSec() / 1000); + pEventSet->pConfirmTimeTextLine->SetValueString(FormatLeftTime(m_strLeftTimeString, iLeftTime)); + } + + if (pEventSet->isWaitFlag) + return; + + long lElapsedTime = m_lElapsedMillisecond; + + pEventSet->lLastDelayTime = std::max(0L, pEventSet->lLastDelayTime - lElapsedTime); + + while (lElapsedTime > 0) + { + pEventSet->lLastDelayTime -= lElapsedTime; + + if (pEventSet->lLastDelayTime <= 0) + { + lElapsedTime = -pEventSet->lLastDelayTime; + if (lElapsedTime <= 0) + break; + + ProcessEventSet(pEventSet); + + if (pEventSet->lLastDelayTime < 0) + { + pEventSet->lLastDelayTime = 0; + break; + } + } + else + break; + } +} + +void CPythonEventManager::SetEventSetWidth(int iIndex, int iWidth) +{ + if (TEventSet* pEventSet = __GetEventSet(iIndex)) + pEventSet->iWidth = iWidth; +} + +bool CPythonEventManager::ProcessEventSet(TEventSet* pEventSet) +{ + if (pEventSet->isLock) + return false; + + script::TCmd ScriptCommand; + + if (!pEventSet->ScriptGroup.GetCmd(ScriptCommand)) + { + pEventSet->isLock = true; + return false; + } + + int pEventPosition; + int iEventType; + if (!GetScriptEventIndex(ScriptCommand.name.c_str(), &pEventPosition, &iEventType)) + return false; + + script::TArgList& args = ScriptCommand.argList; + + switch (iEventType) + { + case EVENT_TYPE_LETTER: + { + const std::string& c_rstValue = GetArgumentString("value", args); + pEventSet->strCurrentLine.append(c_rstValue); + pEventSet->pCurrentTextLine->SetValueString(pEventSet->strCurrentLine); + pEventSet->pCurrentTextLine->SetColor(pEventSet->CurrentColor.r, pEventSet->CurrentColor.g, pEventSet->CurrentColor.b); + pEventSet->iCurrentLetter += int(c_rstValue.length()); + + if (pEventSet->iCurrentLetter >= pEventSet->iRestrictedCharacterCount) + __InsertLine(*pEventSet); + + pEventSet->lLastDelayTime = pEventSet->lWaitingTime; + break; + } + + case EVENT_TYPE_DELAY: + { + if (EVENT_POSITION_START == pEventPosition) + pEventSet->lWaitingTime = atoi(GetArgument("value", args)); + else + pEventSet->lWaitingTime = c_lNormal_Waiting_Time; + break; + } + + case EVENT_TYPE_COLOR: + { + if (EVENT_POSITION_START == pEventPosition) + { + pEventSet->CurrentColor.r = float(atof(GetArgument("r", args))); + pEventSet->CurrentColor.g = float(atof(GetArgument("g", args))); + pEventSet->CurrentColor.b = float(atof(GetArgument("b", args))); + pEventSet->CurrentColor.a = 1.0f; + } + else + pEventSet->CurrentColor = TColor(); + break; + } + + case EVENT_TYPE_COLOR256: + { + if (EVENT_POSITION_START == pEventPosition) + { + pEventSet->CurrentColor.r = float(atof(GetArgument("r", args)) / 255.0f); + pEventSet->CurrentColor.g = float(atof(GetArgument("g", args)) / 255.0f); + pEventSet->CurrentColor.b = float(atof(GetArgument("b", args)) / 255.0f); + pEventSet->CurrentColor.a = 1.0f; + } + else + pEventSet->CurrentColor = TColor(); + break; + } + + case EVENT_TYPE_ENTER: + __InsertLine(*pEventSet); + break; + + case EVENT_TYPE_WAIT: + pEventSet->iyLocal = 0; + pEventSet->isLock = true; + break; + + case EVENT_TYPE_NEXT: + MakeNextButton(pEventSet, BUTTON_TYPE_NEXT); + pEventSet->iAdjustLine += 2; + break; + + case EVENT_TYPE_DONE: + MakeNextButton(pEventSet, BUTTON_TYPE_DONE); + CallMember(pEventSet->poEventHandler, "DoneEvent", Py_BuildValue("()")); + pEventSet->iAdjustLine += 2; + break; + + case EVENT_TYPE_CLEAR: + ClearLine(pEventSet); + break; + + case EVENT_TYPE_QUESTION: + MakeQuestion(pEventSet, args); + break; + + case EVENT_TYPE_LEFT_IMAGE: + CallMember(pEventSet->poEventHandler, "OnLeftImage", Py_BuildValue("(s)", GetArgument("src", args))); + break; + + case EVENT_TYPE_TOP_IMAGE: + CallMember(pEventSet->poEventHandler, "OnTopImage", Py_BuildValue("(s)", GetArgument("src", args))); + break; + + case EVENT_TYPE_BACKGROUND_IMAGE: + CallMember(pEventSet->poEventHandler, "OnBackgroundImage", Py_BuildValue("(s)", GetArgument("src", args))); + break; + + case EVENT_TYPE_IMAGE: + { + int x = atoi(GetArgument("x", args)); + int y = atoi(GetArgument("y", args)); + const char* src = GetArgument("src", args); + CallMember(pEventSet->poEventHandler, "OnImage", Py_BuildValue("(iis)", x, y, src)); + break; + } + + case EVENT_TYPE_INSERT_IMAGE: + { + const std::string& imageFile = GetArgumentString("image_name", args); + const char* title = GetArgument("title", args); + const char* desc = GetArgument("desc", args); + int index = atoi(GetArgument("index", args)); + int total = atoi(GetArgument("total", args)); + + if (imageFile.empty()) + { + const char* imageType = GetArgument("image_type", args); + int iItemIndex = atoi(GetArgument("idx", args)); + CallMember(pEventSet->poEventHandler, "OnInsertItemIcon", Py_BuildValue("(sissii)", imageType, iItemIndex, title, desc, index, total)); + } + else + { + // Windows passes the title twice (underTitle, title). + CallMember(pEventSet->poEventHandler, "OnInsertImage", Py_BuildValue("(ssssii)", imageFile.c_str(), title, title, desc, index, total)); + } + pEventSet->iAdjustLine += 2; + break; + } + + case EVENT_TYPE_ADD_MAP_SIGNAL: + { + float x, y; + x = (float)atof(GetArgument("x", args)); + y = (float)atof(GetArgument("y", args)); + CPythonMiniMap::Instance().AddSignalPoint(x, y); + CPythonMiniMap::Instance().OpenAtlasWindow(); + break; + } + + case EVENT_TYPE_CLEAR_MAP_SIGNAL: + CPythonMiniMap::Instance().ClearAllSignalPoint(); + break; + + // HIDE_QUEST_LETTER + case EVENT_TYPE_QUEST_BUTTON_CLOSE: + CallMember(m_poInterface, "BINARY_ClearQuest", Py_BuildValue("(i)", atoi(GetArgument("idx", args)))); + break; + // END_OF_HIDE_QUEST_LETTER + + case EVENT_TYPE_QUEST_BUTTON: + { + const std::string& c_rstType = GetArgumentString("icon_type", args); + const std::string& c_rstFile = GetArgumentString("icon_name", args); + + int idx = atoi(GetArgument("idx", args)); + const char* name = GetArgument("name", args); + + // cp949 "조각난 용호석?....": that quest letter is highlighted (by chrislee). + if (!std::strcmp(name, "\xc1\xb6\xb0\xa2\xb3\xad \xbf\xeb\xc8\xa5\xbc\xae?....")) + CallMember(m_poInterface, "BINARY_RecvQuest", Py_BuildValue("(isss)", idx, name, "highlight", "")); + else if (c_rstFile.empty()) + CallMember(m_poInterface, "RecvQuest", Py_BuildValue("(is)", idx, name)); + else + CallMember(m_poInterface, "BINARY_RecvQuest", Py_BuildValue("(isss)", idx, name, c_rstType.c_str(), c_rstFile.c_str())); + break; + } + + case EVENT_TYPE_SET_MESSAGE_POSITION: + case EVENT_TYPE_ADJUST_MESSAGE_POSITION: + break; + + case EVENT_TYPE_SET_CENTER_MAP_POSITION: + CPythonMiniMap::Instance().SetAtlasCenterPosition(atoi(GetArgument("x", args)), atoi(GetArgument("y", args))); + break; + + case EVENT_TYPE_SLEEP: + pEventSet->lLastDelayTime = atoi(GetArgument("value", args)); + break; + + case EVENT_TYPE_SET_CAMERA: + case EVENT_TYPE_BLEND_CAMERA: + case EVENT_TYPE_RESTORE_CAMERA: + // IAbstractApplication::SetEventCamera / BlendEventCamera / SetDefaultCamera: the port's + // camera has no event camera yet. + break; + + case EVENT_TYPE_FADE_OUT: + { + float fSpeed = float(atof(GetArgument("speed", args))); + CallMember(pEventSet->poEventHandler, "FadeOut", Py_BuildValue("(f)", fSpeed)); + pEventSet->isWaitFlag = true; + break; + } + + case EVENT_TYPE_FADE_IN: + CallMember(pEventSet->poEventHandler, "FadeIn", Py_BuildValue("(f)", atof(GetArgument("speed", args)))); + pEventSet->isWaitFlag = true; + break; + + case EVENT_TYPE_WHITE_OUT: + CallMember(pEventSet->poEventHandler, "WhiteOut", Py_BuildValue("(f)", atof(GetArgument("speed", args)))); + pEventSet->isWaitFlag = true; + break; + + case EVENT_TYPE_WHITE_IN: + CallMember(pEventSet->poEventHandler, "WhiteIn", Py_BuildValue("(f)", atof(GetArgument("speed", args)))); + pEventSet->isWaitFlag = true; + break; + + case EVENT_TYPE_CLEAR_TEXT: + ClearLine(pEventSet); + break; + + case EVENT_TYPE_TEXT_HORIZONTAL_ALIGN_CENTER: + pEventSet->isTextCenterMode = true; + if (pEventSet->pCurrentTextLine) + pEventSet->pCurrentTextLine->SetHorizonalAlign(CGraphicTextInstance::HORIZONTAL_ALIGN_CENTER); + break; + + case EVENT_TYPE_TITLE_IMAGE: + CallMember(pEventSet->poEventHandler, "OnTitleImage", Py_BuildValue("(s)", GetArgument("src", args))); + break; + + case EVENT_TYPE_DUNGEON_RESULT: + { + int killstone_count = atoi(GetArgument("killstone_count", args)); + int killmob_count = atoi(GetArgument("killmob_count", args)); + int find_hidden = atoi(GetArgument("find_hidden", args)); + int hidden_total = atoi(GetArgument("hidden_total", args)); + int use_potion = atoi(GetArgument("use_potion", args)); + int is_revived = atoi(GetArgument("is_revived", args)); + int killallmob = atoi(GetArgument("killallmob", args)); + int total_time = atoi(GetArgument("total_time", args)); + int bonus_exp = atoi(GetArgument("bonus_exp", args)); + + CallMember(m_poInterface, "ShowDungeonResult", + Py_BuildValue("(iiiiiiiii)", killstone_count, killmob_count, find_hidden, hidden_total, + use_potion, is_revived, killallmob, total_time, bonus_exp)); + break; + } + + case EVENT_TYPE_ITEM_NAME: + { + int iIndex = atoi(GetArgument("value", args)); + std::string strName; + int iType; + if (GetItemNameAndType(uint32_t(iIndex), &strName, &iType)) + { + pEventSet->strCurrentLine.append(strName); + pEventSet->pCurrentTextLine->SetValue(pEventSet->strCurrentLine.c_str()); + pEventSet->pCurrentTextLine->SetColor(1.0f, 0.2f, 0.2f); + pEventSet->iCurrentLetter += int(std::strlen(strName.c_str())); + + if (pEventSet->iCurrentLetter >= pEventSet->iRestrictedCharacterCount) + __InsertLine(*pEventSet); + + pEventSet->lLastDelayTime = pEventSet->lWaitingTime; + } + break; + } + + case EVENT_TYPE_MONSTER_NAME: + { + int iIndex = atoi(GetArgument("value", args)); + std::string strName; + if (GetNonPlayerName(uint32_t(iIndex), strName)) + { + pEventSet->strCurrentLine.append(strName.c_str()); + pEventSet->pCurrentTextLine->SetValue(pEventSet->strCurrentLine.c_str()); + pEventSet->iCurrentLetter += int(std::strlen(strName.c_str())); + + if (pEventSet->iCurrentLetter >= pEventSet->iRestrictedCharacterCount) + __InsertLine(*pEventSet); + + pEventSet->lLastDelayTime = pEventSet->lWaitingTime; + } + break; + } + + case EVENT_TYPE_WINDOW_SIZE: + { + int iWidth = atoi(GetArgument("width", args)); + int iHeight = atoi(GetArgument("height", args)); + CallMember(pEventSet->poEventHandler, "OnSize", Py_BuildValue("(ii)", iWidth, iHeight)); + break; + } + + case EVENT_TYPE_INPUT: + __InsertLine(*pEventSet); + CallMember(pEventSet->poEventHandler, "OnInput", Py_BuildValue("()")); + break; + + case EVENT_TYPE_CONFIRM_WAIT: + { + int iTimeOut = atoi(GetArgument("timeout", args)); + pEventSet->isConfirmWait = true; + pEventSet->pConfirmTimeTextLine = pEventSet->pCurrentTextLine; + pEventSet->iConfirmEndTime = int(GetLocalMSec() / 1000 + iTimeOut); + __InsertLine(*pEventSet, true); + MakeNextButton(pEventSet, BUTTON_TYPE_CANCEL); + break; + } + + case EVENT_TYPE_END_CONFIRM_WAIT: + { + for (TEventSet* pSet : m_EventSetVector) + { + if (!pSet || !pSet->isConfirmWait) + continue; + + pSet->isConfirmWait = false; + pSet->pConfirmTimeTextLine = nullptr; + pSet->iConfirmEndTime = 0; + + CallMember(pSet->poEventHandler, "CloseSelf", Py_BuildValue("()")); + } + break; + } + + case EVENT_TYPE_SELECT_ITEM: + CallMember(m_poInterface, "BINARY_OpenSelectItemWindow", Py_BuildValue("()")); + break; + } + + return true; +} + +void CPythonEventManager::RenderEventSet(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + if (!pEventSet) + return; + + int iCount = 0; + for (auto itor = pEventSet->ScriptTextLineList.begin(); itor != pEventSet->ScriptTextLineList.end(); ++itor, ++iCount) + { + if (iCount < pEventSet->iVisibleStartLine) + continue; + if (iCount >= pEventSet->iVisibleStartLine + pEventSet->iVisibleLineCount) + continue; + + CGraphicTextInstance* pInstance = itor->pInstance; + pInstance->Update(); + pInstance->Render(); + } + + if (iCount >= pEventSet->iVisibleStartLine && iCount < pEventSet->iVisibleStartLine + pEventSet->iVisibleLineCount) + { + pEventSet->pCurrentTextLine->Update(); + pEventSet->pCurrentTextLine->Render(); + } +} + +void CPythonEventManager::Skip(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + if (!pEventSet) + return; + + if (pEventSet->isLock) + { + pEventSet->lLastDelayTime = 0; + pEventSet->isLock = false; + } + else + { + pEventSet->lLastDelayTime = -1000; + } +} + +bool CPythonEventManager::IsWait(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + return pEventSet ? pEventSet->isLock : false; +} + +void CPythonEventManager::EndEventProcess(int iIndex) +{ + if (TEventSet* pEventSet = __GetEventSet(iIndex)) + pEventSet->isWaitFlag = false; +} + +void CPythonEventManager::MakeNextButton(TEventSet* pEventSet, int iButtonType) +{ + __AddSpace(*pEventSet, c_fLine_Temp + 5); + CallMember(pEventSet->poEventHandler, "MakeNextButton", Py_BuildValue("(i)", iButtonType)); +} + +void CPythonEventManager::MakeQuestion(TEventSet* pEventSet, script::TArgList& rArgumentList) +{ + if (rArgumentList.empty()) + return; + + CallMember(pEventSet->poEventHandler, "MakeQuestion", Py_BuildValue("(i)", int(rArgumentList.size()))); + pEventSet->nAnswer = int(rArgumentList.size()); + + int iIndex = 0; + for (script::TArg& rArgument : rArgumentList) + { + CallMember(pEventSet->poEventHandler, "AppendQuestion", Py_BuildValue("(si)", rArgument.strValue.c_str(), iIndex)); + ++iIndex; + } +} + +void CPythonEventManager::SelectAnswer(int iIndex, int iAnswer) +{ + if (!CheckEventSetIndex(iIndex)) + return; + + PythonNetworkStream::Instance().SendScriptAnswerPacket(iAnswer); +} + +void CPythonEventManager::SetVisibleStartLine(int iIndex, int iStartLine) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + if (!pEventSet) + return; + + if (uint32_t(iStartLine) > pEventSet->ScriptTextLineList.size()) + return; + + pEventSet->iVisibleStartLine = iStartLine; +} + +int CPythonEventManager::GetVisibleStartLine(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + return pEventSet ? pEventSet->iVisibleStartLine : 0; +} + +void CPythonEventManager::AllProcessEventSet(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + if (!pEventSet) + return; + + do {} while (ProcessEventSet(pEventSet)); +} + +int CPythonEventManager::GetProcessedLineCount(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + return pEventSet ? int(pEventSet->ScriptTextLineList.size()) : 0; +} + +void CPythonEventManager::SetYPosition(int iIndex, int iY) +{ + if (TEventSet* pEventSet = __GetEventSet(iIndex)) + pEventSet->iy = iY; +} + +int CPythonEventManager::GetLineCount(int iIndex) +{ + TEventSet* pEventSet = __GetEventSet(iIndex); + return pEventSet ? int(pEventSet->ScriptTextLineList.size()) + pEventSet->iAdjustLine : 0; +} + +void CPythonEventManager::ClearLine(TEventSet* pEventSet) +{ + if (!pEventSet) + return; + + // Windows destroys the instances without returning them to the pool; Destroy() frees them. + for (TTextLine& rkLine : pEventSet->ScriptTextLineList) + { + rkLine.pInstance->Destroy(); + rkLine.pInstance->Update(); + } + + pEventSet->pCurrentTextLine->Destroy(); + pEventSet->pCurrentTextLine->Update(); + + pEventSet->pCurrentTextLine = nullptr; + pEventSet->ScriptTextLineList.clear(); + + __InsertLine(*pEventSet); +} + +void CPythonEventManager::__InsertLine(TEventSet& rEventSet, bool isCenter, int iX_pos) +{ + if (rEventSet.pCurrentTextLine) + { + TTextLine kLine; + if (CGraphicTextInstance::HORIZONTAL_ALIGN_CENTER == rEventSet.pCurrentTextLine->GetHorizontalAlign()) + { + kLine.ixLocal = rEventSet.iWidth / 2; + kLine.iyLocal = rEventSet.iyLocal; + } + else + { + int textWidth; + int textHeight; + rEventSet.pCurrentTextLine->GetTextSize(&textWidth, &textHeight); + if (GetDefaultCodePage() == CP_1256) + { + kLine.ixLocal = rEventSet.iWidth; + if (iX_pos != 0) + { + kLine.ixLocal -= iX_pos - 20; + kLine.ixLocal += textWidth / 2; + } + } + else + { + kLine.ixLocal = 0; + if (iX_pos != 0) + { + kLine.ixLocal += (iX_pos - 20); + kLine.ixLocal -= textWidth / 2; + } + } + kLine.iyLocal = rEventSet.iyLocal; + } + kLine.pInstance = rEventSet.pCurrentTextLine; + rEventSet.ScriptTextLineList.push_back(kLine); + __AddSpace(rEventSet, c_fLine_Temp); + } + + // DEFAULT_FONT: the port's text instances draw with the built-in debug font. + rEventSet.pCurrentTextLine = m_ScriptTextLinePool.Alloc(); + if (!rEventSet.pCurrentTextLine) + { + SDL_Log("CPythonEventManager::InsertLine - OUT_OF_TEXT_LINE"); + return; + } + // A pooled instance is reused as Free left it (Windows: Destroy before Free). + rEventSet.pCurrentTextLine->SetColor(1.0f, 1.0f, 1.0f); + rEventSet.pCurrentTextLine->SetValue(""); + + if (rEventSet.isTextCenterMode || isCenter) + { + rEventSet.pCurrentTextLine->SetHorizonalAlign(CGraphicTextInstance::HORIZONTAL_ALIGN_CENTER); + rEventSet.pCurrentTextLine->SetPosition(float(rEventSet.ix + rEventSet.iWidth / 2), float(rEventSet.iy + rEventSet.iyLocal)); + } + else if (GetDefaultCodePage() == CP_1256) + { + rEventSet.pCurrentTextLine->SetHorizonalAlign(CGraphicTextInstance::HORIZONTAL_ALIGN_LEFT); + rEventSet.pCurrentTextLine->SetPosition(float(rEventSet.ix + rEventSet.iWidth), float(rEventSet.iy + rEventSet.iyLocal)); + } + else + { + rEventSet.pCurrentTextLine->SetHorizonalAlign(CGraphicTextInstance::HORIZONTAL_ALIGN_LEFT); + rEventSet.pCurrentTextLine->SetPosition(float(rEventSet.ix), float(rEventSet.iy + rEventSet.iyLocal)); + } + + rEventSet.iCurrentLetter = 0; + rEventSet.strCurrentLine = ""; +} + +void CPythonEventManager::RefreshLinePosition(TEventSet* pEventSet) +{ + for (TTextLine& rkLine : pEventSet->ScriptTextLineList) + rkLine.pInstance->SetPosition(float(pEventSet->ix + rkLine.ixLocal), float(pEventSet->iy + rkLine.iyLocal)); + + int ixTextPos; + if (CGraphicTextInstance::HORIZONTAL_ALIGN_CENTER == pEventSet->pCurrentTextLine->GetHorizontalAlign()) + ixTextPos = pEventSet->ix + pEventSet->iWidth / 2; + else if (GetDefaultCodePage() == CP_1256) + ixTextPos = pEventSet->ix + pEventSet->iWidth; + else + ixTextPos = pEventSet->ix; + pEventSet->pCurrentTextLine->SetPosition(float(ixTextPos), float(pEventSet->iy + pEventSet->iyLocal)); +} + +void CPythonEventManager::__AddSpace(TEventSet& rEventSet, int iSpace) +{ + rEventSet.iyLocal += iSpace; +} + +bool CPythonEventManager::GetScriptEventIndex(const char* c_szName, int* pEventPosition, int* pEventType) +{ + const char* c_szEventName; + if ('/' == c_szName[0]) + { + *pEventPosition = EVENT_POSITION_END; + c_szEventName = &c_szName[1]; + } + else + { + *pEventPosition = EVENT_POSITION_START; + c_szEventName = &c_szName[0]; + } + + auto it = EventTypeMap.find(c_szEventName); + if (it == EventTypeMap.end()) + { + SDL_Log(" !! PARSING ERROR - Strange Command : %s", c_szEventName); + return false; + } + + *pEventType = it->second; + return true; +} + +bool CPythonEventManager::CheckEventSetIndex(int iIndex) const +{ + if (iIndex < 0) + return false; + if (unsigned(iIndex) >= m_EventSetVector.size()) + return false; + return true; +} + +CPythonEventManager::TEventSet* CPythonEventManager::__GetEventSet(int iIndex) +{ + return CheckEventSetIndex(iIndex) ? m_EventSetVector[iIndex] : nullptr; +} + +const CPythonEventManager::TEventSet* CPythonEventManager::GetEventSet(int iIndex) const +{ + return CheckEventSetIndex(iIndex) ? m_EventSetVector[iIndex] : nullptr; +} + +void CPythonEventManager::Destroy() +{ + m_EventSetVector.clear(); + m_EventSetPool.Destroy(); + m_ScriptTextLinePool.Destroy(); +} + +void CPythonEventManager::SetInterfaceWindow(PyObject* poInterface) +{ + m_poInterface.Reset(poInterface); +} + +void CPythonEventManager::SetLeftTimeString(const char* c_szString) +{ + m_strLeftTimeString = c_szString; +} + +CPythonEventManager::CPythonEventManager() + // cp949 "남은 시간 : %d초" + : m_strLeftTimeString("\xb3\xb2\xc0\xba \xbd\xc3\xb0\xa3 : %d\xc3\xca") +{ + EventTypeMap["LETTER"] = EVENT_TYPE_LETTER; + EventTypeMap["COLOR"] = EVENT_TYPE_COLOR; + EventTypeMap["DELAY"] = EVENT_TYPE_DELAY; + EventTypeMap["ENTER"] = EVENT_TYPE_ENTER; + EventTypeMap["WAIT"] = EVENT_TYPE_WAIT; + EventTypeMap["CLEAR"] = EVENT_TYPE_CLEAR; + EventTypeMap["QUESTION"] = EVENT_TYPE_QUESTION; + EventTypeMap["NEXT"] = EVENT_TYPE_NEXT; + EventTypeMap["DONE"] = EVENT_TYPE_DONE; + + EventTypeMap["LEFTIMAGE"] = EVENT_TYPE_LEFT_IMAGE; + EventTypeMap["TOPIMAGE"] = EVENT_TYPE_TOP_IMAGE; + EventTypeMap["BGIMAGE"] = EVENT_TYPE_BACKGROUND_IMAGE; + EventTypeMap["IMAGE"] = EVENT_TYPE_IMAGE; + + EventTypeMap["ADDMAPSIGNAL"] = EVENT_TYPE_ADD_MAP_SIGNAL; + EventTypeMap["CLEARMAPSIGNAL"] = EVENT_TYPE_CLEAR_MAP_SIGNAL; + + EventTypeMap["SETMSGPOS"] = EVENT_TYPE_SET_MESSAGE_POSITION; + EventTypeMap["ADJMSGPOS"] = EVENT_TYPE_ADJUST_MESSAGE_POSITION; + EventTypeMap["SETCMAPPOS"] = EVENT_TYPE_SET_CENTER_MAP_POSITION; + + EventTypeMap["QUESTBUTTON"] = EVENT_TYPE_QUEST_BUTTON; + EventTypeMap["QUESTBUTTON_CLOSE"] = EVENT_TYPE_QUEST_BUTTON_CLOSE; + + EventTypeMap["SLEEP"] = EVENT_TYPE_SLEEP; + EventTypeMap["SET_CAMERA"] = EVENT_TYPE_SET_CAMERA; + EventTypeMap["BLEND_CAMERA"] = EVENT_TYPE_BLEND_CAMERA; + EventTypeMap["RESTORE_CAMERA"] = EVENT_TYPE_RESTORE_CAMERA; + EventTypeMap["FADE_OUT"] = EVENT_TYPE_FADE_OUT; + EventTypeMap["FADE_IN"] = EVENT_TYPE_FADE_IN; + EventTypeMap["WHITE_OUT"] = EVENT_TYPE_WHITE_OUT; + EventTypeMap["WHITE_IN"] = EVENT_TYPE_WHITE_IN; + EventTypeMap["CLEAR_TEXT"] = EVENT_TYPE_CLEAR_TEXT; + EventTypeMap["TEXT_HORIZONTAL_ALIGN_CENTER"] = EVENT_TYPE_TEXT_HORIZONTAL_ALIGN_CENTER; + EventTypeMap["TITLE_IMAGE"] = EVENT_TYPE_TITLE_IMAGE; + + EventTypeMap["RUN_CINEMA"] = EVENT_TYPE_RUN_CINEMA; + EventTypeMap["DUNGEON_RESULT"] = EVENT_TYPE_DUNGEON_RESULT; + + EventTypeMap["ITEM"] = EVENT_TYPE_ITEM_NAME; + EventTypeMap["MOB"] = EVENT_TYPE_MONSTER_NAME; + + EventTypeMap["COLOR256"] = EVENT_TYPE_COLOR256; + EventTypeMap["WINDOW_SIZE"] = EVENT_TYPE_WINDOW_SIZE; + + EventTypeMap["INPUT"] = EVENT_TYPE_INPUT; + EventTypeMap["CONFIRM_WAIT"] = EVENT_TYPE_CONFIRM_WAIT; + EventTypeMap["END_CONFIRM_WAIT"] = EVENT_TYPE_END_CONFIRM_WAIT; + + EventTypeMap["INSERT_IMAGE"] = EVENT_TYPE_INSERT_IMAGE; + EventTypeMap["SELECT_ITEM"] = EVENT_TYPE_SELECT_ITEM; +} + +// ---- event module (PythonEventManagerMoudle.cpp) ---- +namespace { + +CPythonEventManager& Mgr() { return CPythonEventManager::Instance(); } + +PyObject* eventRegisterEventSet(PyObject*, PyObject* poArgs) +{ + char* szFileName; + if (!PyTuple_GetString(poArgs, 0, &szFileName)) + return Py_BuildException(); + return Py_BuildValue("i", Mgr().RegisterEventSet(szFileName)); +} + +PyObject* eventRegisterEventSetFromString(PyObject*, PyObject* poArgs) +{ + char* szEventString; + if (!PyTuple_GetString(poArgs, 0, &szEventString)) + return Py_BuildException(); + return Py_BuildValue("i", Mgr().RegisterEventSetFromString(szEventString)); +} + +PyObject* eventClearEventSet(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + Mgr().ClearEventSeti(iIndex); + return Py_BuildNone(); +} + +PyObject* eventSetRestrictedCount(PyObject*, PyObject* poArgs) +{ + int iIndex, iCount; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iCount)) + return Py_BuildException(); + Mgr().SetRestrictedCount(iIndex, iCount); + return Py_BuildNone(); +} + +PyObject* eventGetEventSetLocalYPosition(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + return Py_BuildValue("i", Mgr().GetEventSetLocalYPosition(iIndex)); +} + +PyObject* eventAddEventSetLocalYPosition(PyObject*, PyObject* poArgs) +{ + int iIndex, iPos; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iPos)) + return Py_BuildException(); + Mgr().AddEventSetLocalYPosition(iIndex, iPos); + return Py_BuildNone(); +} + +PyObject* eventInsertText(PyObject*, PyObject* poArgs) +{ + int iIndex; + char* szText; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetString(poArgs, 1, &szText)) + return Py_BuildException(); + Mgr().InsertText(iIndex, szText); + return Py_BuildNone(); +} + +PyObject* eventInsertTextInline(PyObject*, PyObject* poArgs) +{ + int iIndex, iXIndex; + char* szText; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetString(poArgs, 1, &szText)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 2, &iXIndex)) + return Py_BuildException(); + Mgr().InsertText(iIndex, szText, iXIndex); + return Py_BuildNone(); +} + +PyObject* eventSetVisibleLineCount(PyObject*, PyObject* poArgs) +{ + int iIndex, count; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &count)) + return Py_BuildException(); + Mgr().SetVisibleLineCount(iIndex, count); + return Py_BuildNone(); +} + +PyObject* eventUpdateEventSet(PyObject*, PyObject* poArgs) +{ + int iIndex, ix, iy; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &ix)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 2, &iy)) + return Py_BuildException(); + Mgr().UpdateEventSet(iIndex, ix, -iy); + return Py_BuildNone(); +} + +PyObject* eventRenderEventSet(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + Mgr().RenderEventSet(iIndex); + return Py_BuildNone(); +} + +PyObject* eventSetEventSetWidth(PyObject*, PyObject* poArgs) +{ + int iIndex, iWidth; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iWidth)) + return Py_BuildException(); + Mgr().SetEventSetWidth(iIndex, iWidth); + return Py_BuildNone(); +} + +PyObject* eventSkip(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + Mgr().Skip(iIndex); + return Py_BuildNone(); +} + +PyObject* eventIsWait(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + return Py_BuildValue("i", Mgr().IsWait(iIndex) ? 1 : 0); +} + +PyObject* eventEndEventProcess(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + Mgr().EndEventProcess(iIndex); + return Py_BuildNone(); +} + +PyObject* eventSetEventHandler(PyObject*, PyObject* poArgs) +{ + int iIndex; + PyObject* poEventHandler; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetObject(poArgs, 1, &poEventHandler)) + return Py_BuildException(); + Mgr().SetEventHandler(iIndex, poEventHandler); + return Py_BuildNone(); +} + +// CPythonStackController::CheckStackReference (anti-cheat caller check) is not ported. +PyObject* eventSelectAnswer(PyObject*, PyObject* poArgs) +{ + int iIndex, iAnswer; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iAnswer)) + return Py_BuildException(); + Mgr().SelectAnswer(iIndex, iAnswer); + return Py_BuildNone(); +} + +PyObject* eventGetLineCount(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + return Py_BuildValue("i", Mgr().GetLineCount(iIndex)); +} + +PyObject* eventSetVisibleStartLine(PyObject*, PyObject* poArgs) +{ + int iIndex, iStartLine; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iStartLine)) + return Py_BuildException(); + Mgr().SetVisibleStartLine(iIndex, iStartLine); + return Py_BuildNone(); +} + +PyObject* eventGetVisibleStartLine(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + return Py_BuildValue("i", Mgr().GetVisibleStartLine(iIndex)); +} + +PyObject* eventQuestButtonClick(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + PythonNetworkStream::Instance().SendScriptButtonPacket(iIndex); + return Py_BuildNone(); +} + +PyObject* eventSetInterfaceWindow(PyObject*, PyObject* poArgs) +{ + PyObject* pyHandle; + if (!PyTuple_GetObject(poArgs, 0, &pyHandle)) + return Py_BadArgument(); + Mgr().SetInterfaceWindow(pyHandle); + return Py_BuildNone(); +} + +PyObject* eventSetLeftTimeString(PyObject*, PyObject* poArgs) +{ + char* szText; + if (!PyTuple_GetString(poArgs, 0, &szText)) + return Py_BuildException(); + Mgr().SetLeftTimeString(szText); + return Py_BuildNone(); +} + +PyObject* eventDestroy(PyObject*, PyObject*) +{ + Mgr().Destroy(); + return Py_BuildNone(); +} + +PyObject* eventGetLineHeight(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + return Py_BuildValue("i", Mgr().GetLineHeight(iIndex)); +} + +PyObject* eventSetYPosition(PyObject*, PyObject* poArgs) +{ + int iIndex, iY; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iY)) + return Py_BuildException(); + Mgr().SetYPosition(iIndex, iY); + return Py_BuildNone(); +} + +PyObject* eventGetProcessedLineCount(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + return Py_BuildValue("i", Mgr().GetProcessedLineCount(iIndex)); +} + +PyObject* eventAllProcessEventSet(PyObject*, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + Mgr().AllProcessEventSet(iIndex); + return Py_BuildNone(); +} + +// ENABLE_MULTILANGUAGE_SYSTEM evetAddEvent: the translated quest text comes back from Python. +PyObject* eventAddEvent(PyObject*, PyObject* poArgs) +{ + char* iBuf; + int iSkin; + if (!PyTuple_GetString(poArgs, 0, &iBuf)) + return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &iSkin)) + return Py_BuildException(); + + int iIndex = Mgr().RegisterEventSetFromString(iBuf); + if (-1 != iIndex) + { + Mgr().SetVisibleLineCount(iIndex, 30); + PythonNetworkStream::Instance().OnScriptEventStart(iSkin, iIndex); + } + return Py_BuildNone(); +} + +} // namespace + +void initEvent() +{ + static PyMethodDef s_methods[] = + { + { "RegisterEventSet", eventRegisterEventSet, METH_VARARGS, nullptr }, + { "RegisterEventSetFromString", eventRegisterEventSetFromString, METH_VARARGS, nullptr }, + { "ClearEventSet", eventClearEventSet, METH_VARARGS, nullptr }, + + { "SetRestrictedCount", eventSetRestrictedCount, METH_VARARGS, nullptr }, + + { "GetEventSetLocalYPosition", eventGetEventSetLocalYPosition, METH_VARARGS, nullptr }, + { "AddEventSetLocalYPosition", eventAddEventSetLocalYPosition, METH_VARARGS, nullptr }, + { "InsertText", eventInsertText, METH_VARARGS, nullptr }, + { "InsertTextInline", eventInsertTextInline, METH_VARARGS, nullptr }, + + { "UpdateEventSet", eventUpdateEventSet, METH_VARARGS, nullptr }, + { "SetVisibleLineCount", eventSetVisibleLineCount, METH_VARARGS, nullptr }, + { "RenderEventSet", eventRenderEventSet, METH_VARARGS, nullptr }, + { "SetEventSetWidth", eventSetEventSetWidth, METH_VARARGS, nullptr }, + + { "Skip", eventSkip, METH_VARARGS, nullptr }, + { "IsWait", eventIsWait, METH_VARARGS, nullptr }, + { "EndEventProcess", eventEndEventProcess, METH_VARARGS, nullptr }, + + { "SelectAnswer", eventSelectAnswer, METH_VARARGS, nullptr }, + { "GetLineCount", eventGetLineCount, METH_VARARGS, nullptr }, + { "SetVisibleStartLine", eventSetVisibleStartLine, METH_VARARGS, nullptr }, + { "GetVisibleStartLine", eventGetVisibleStartLine, METH_VARARGS, nullptr }, + { "SetEventHandler", eventSetEventHandler, METH_VARARGS, nullptr }, + { "SetInterfaceWindow", eventSetInterfaceWindow, METH_VARARGS, nullptr }, + { "SetLeftTimeString", eventSetLeftTimeString, METH_VARARGS, nullptr }, + + { "QuestButtonClick", eventQuestButtonClick, METH_VARARGS, nullptr }, + { "Destroy", eventDestroy, METH_VARARGS, nullptr }, + { "GetLineHeight", eventGetLineHeight, METH_VARARGS, nullptr }, + { "SetYPosition", eventSetYPosition, METH_VARARGS, nullptr }, + { "GetProcessedLineCount", eventGetProcessedLineCount, METH_VARARGS, nullptr }, + { "AllProcessEventSet", eventAllProcessEventSet, METH_VARARGS, nullptr }, + + { "AddEvent", eventAddEvent, METH_VARARGS, nullptr }, + { nullptr, nullptr, 0, nullptr }, + }; + + PyObject* poModule = Py_InitModule("event", s_methods); + + PyModule_AddIntConstant(poModule, "BOX_VISIBLE_LINE_COUNT", CPythonEventManager::BOX_VISIBLE_LINE_COUNT); + PyModule_AddIntConstant(poModule, "BUTTON_TYPE_NEXT", CPythonEventManager::BUTTON_TYPE_NEXT); + PyModule_AddIntConstant(poModule, "BUTTON_TYPE_DONE", CPythonEventManager::BUTTON_TYPE_DONE); + PyModule_AddIntConstant(poModule, "BUTTON_TYPE_CANCEL", CPythonEventManager::BUTTON_TYPE_CANCEL); +} + +} // namespace ava2 diff --git a/src/python_event_manager.h b/src/python_event_manager.h new file mode 100644 index 00000000..26a64d06 --- /dev/null +++ b/src/python_event_manager.h @@ -0,0 +1,220 @@ +#pragma once +// CPythonEventManager: the quest / description script player behind the "event" module. +// Provenance: AVA2 UserInterface/PythonEventManager.{h,cpp} and PythonEventManagerMoudle.cpp. +#include "eter_lib/parser.h" +#include "eter_ui/PythonWindow.h" +#include "shared/common/DynamicPool.h" +#include +#include +#include +#include +#include + +namespace ava2 { + +class CPythonEventManager +{ +public: + typedef UI::CGraphicTextInstance CGraphicTextInstance; + + struct TTextLine + { + int ixLocal, iyLocal; + CGraphicTextInstance* pInstance; + }; + typedef std::list TScriptTextLineList; + + enum + { + EVENT_POSITION_START = 0, + EVENT_POSITION_END = 1, + BOX_VISIBLE_LINE_COUNT = 14, + }; + + enum EButtonType + { + BUTTON_TYPE_NEXT, + BUTTON_TYPE_DONE, + BUTTON_TYPE_CANCEL, + }; + + enum EEventType + { + EVENT_TYPE_LETTER, + EVENT_TYPE_COLOR, + EVENT_TYPE_DELAY, + EVENT_TYPE_ENTER, + EVENT_TYPE_WAIT, + EVENT_TYPE_CLEAR, + EVENT_TYPE_QUESTION, + EVENT_TYPE_NEXT, + EVENT_TYPE_DONE, + EVENT_TYPE_LEFT_IMAGE, + EVENT_TYPE_TOP_IMAGE, + EVENT_TYPE_BACKGROUND_IMAGE, + EVENT_TYPE_IMAGE, + EVENT_TYPE_ADD_MAP_SIGNAL, + EVENT_TYPE_CLEAR_MAP_SIGNAL, + EVENT_TYPE_SET_MESSAGE_POSITION, + EVENT_TYPE_ADJUST_MESSAGE_POSITION, + EVENT_TYPE_SET_CENTER_MAP_POSITION, + EVENT_TYPE_QUEST_BUTTON, + EVENT_TYPE_QUEST_BUTTON_CLOSE, + EVENT_TYPE_SLEEP, + EVENT_TYPE_SET_CAMERA, + EVENT_TYPE_BLEND_CAMERA, + EVENT_TYPE_RESTORE_CAMERA, + EVENT_TYPE_FADE_OUT, + EVENT_TYPE_FADE_IN, + EVENT_TYPE_WHITE_OUT, + EVENT_TYPE_WHITE_IN, + EVENT_TYPE_CLEAR_TEXT, + EVENT_TYPE_TEXT_HORIZONTAL_ALIGN_CENTER, + EVENT_TYPE_TITLE_IMAGE, + EVENT_TYPE_RUN_CINEMA, + EVENT_TYPE_DUNGEON_RESULT, + EVENT_TYPE_ITEM_NAME, + EVENT_TYPE_MONSTER_NAME, + EVENT_TYPE_COLOR256, + EVENT_TYPE_WINDOW_SIZE, + EVENT_TYPE_INPUT, + EVENT_TYPE_CONFIRM_WAIT, + EVENT_TYPE_END_CONFIRM_WAIT, + EVENT_TYPE_INSERT_IMAGE, + EVENT_TYPE_SELECT_ITEM, + }; + + struct TColor { float r = 1, g = 1, b = 1, a = 1; }; + + // Windows keeps the handler / interface as borrowed PyObject*; the quest dialog relies on its + // __del__ running while the event set still points at it. A weak reference (or the borrowed + // pointer for objects that cannot be weakly referenced) keeps that lifetime without dangling. + class CBorrowedObject + { + public: + CBorrowedObject() = default; + CBorrowedObject(const CBorrowedObject&) = delete; + CBorrowedObject& operator=(const CBorrowedObject&) = delete; + ~CBorrowedObject() { Reset(nullptr); } + void Reset(PyObject* object); + // A new reference, or nullptr when unset or collected. + PyObject* Get() const; + private: + PyObject* m_ref = nullptr; // owned weakref, or the borrowed object + bool m_isWeak = false; + }; + + struct TEventSet + { + int ix, iy; + int iWidth; + int iyLocal; + + bool isLock; + long lLastDelayTime; + int iCurrentLetter; + + TColor CurrentColor; + std::string strCurrentLine; + + CGraphicTextInstance* pCurrentTextLine; + TScriptTextLineList ScriptTextLineList; + + bool isConfirmWait; + CGraphicTextInstance* pConfirmTimeTextLine; + int iConfirmEndTime; + + script::Group ScriptGroup; + + char szFileName[32 + 1]; + + int iVisibleStartLine; + int iVisibleLineCount; + int iTotalLineCount; + int iAdjustLine; + + TColor DiffuseColor; + long lWaitingTime; + int iRestrictedCharacterCount; + + int nAnswer; + + bool isTextCenterMode; + bool isWaitFlag; + + CBorrowedObject poEventHandler; + }; + + static CPythonEventManager& Instance(); + + void Destroy(); + + int RegisterEventSet(const char* c_szFileName); + int RegisterEventSetFromString(const std::string& strScript); + void ClearEventSeti(int iIndex); + + void SetEventHandler(int iIndex, PyObject* poEventHandler); + void SetRestrictedCount(int iIndex, int iCount); + + int GetEventSetLocalYPosition(int iIndex); + void AddEventSetLocalYPosition(int iIndex, int iAddValue); + void InsertText(int iIndex, const char* c_szText, int iX_pos = 0); + + void UpdateEventSet(int iIndex, int ix, int iy); + void RenderEventSet(int iIndex); + void SetEventSetWidth(int iIndex, int iWidth); + + void Skip(int iIndex); + bool IsWait(int iIndex); + void EndEventProcess(int iIndex); + + void SelectAnswer(int iIndex, int iAnswer); + void SetVisibleStartLine(int iIndex, int iStartLine); + int GetVisibleStartLine(int iIndex); + int GetLineCount(int iIndex); + void SetVisibleLineCount(int iIndex, int iLineCount); + + void SetInterfaceWindow(PyObject* poInterface); + void SetLeftTimeString(const char* c_szString); + int GetLineHeight(int iIndex); + void SetYPosition(int iIndex, int iY); + int GetProcessedLineCount(int iIndex); + void AllProcessEventSet(int iIndex); + int GetTotalLineCount(int iIndex); + + // CTimer::GetElapsedMilliecond stand-in: the main loop sets the last frame's length, which every + // UpdateEventSet of that frame consumes. + void SetElapsedMillisecond(long lElapsed) { m_lElapsedMillisecond = lElapsed; } + // Test access to a set's state (nullptr for a free or out-of-range slot). + const TEventSet* GetEventSet(int iIndex) const; + +private: + CPythonEventManager(); + + void __InitEventSet(TEventSet& rEventSet); + void __InsertLine(TEventSet& rEventSet, bool isCenter = false, int iX_pos = 0); + void __AddSpace(TEventSet& rEventSet, int iSpace); + void __ClearEventSetp(TEventSet* pEventSet); + TEventSet* __GetEventSet(int iIndex); + + unsigned GetEmptyEventSetSlot(); + bool CheckEventSetIndex(int iIndex) const; + bool ProcessEventSet(TEventSet* pEventSet); + + void ClearLine(TEventSet* pEventSet); + void RefreshLinePosition(TEventSet* pEventSet); + bool GetScriptEventIndex(const char* c_szName, int* pEventPosition, int* pEventType); + + void MakeQuestion(TEventSet* pEventSet, script::TArgList& rArgumentList); + void MakeNextButton(TEventSet* pEventSet, int iButtonType); + + std::map EventTypeMap; + std::vector m_EventSetVector; + CDynamicPool m_EventSetPool; + CDynamicPool m_ScriptTextLinePool; + CBorrowedObject m_poInterface; + std::string m_strLeftTimeString; + long m_lElapsedMillisecond = 0; +}; + +} // namespace ava2 diff --git a/src/python_gameplay_modules.cpp b/src/python_gameplay_modules.cpp index 25cd957a..2ddd9d23 100644 --- a/src/python_gameplay_modules.cpp +++ b/src/python_gameplay_modules.cpp @@ -1,12 +1,20 @@ +#include "ava2_text_file.h" +#include "ava2_text_file_loader.h" +#include "python_minimap.h" +#include "item_sound.h" #include "item_proto.h" #include "python_gameplay_modules.h" #include "python_runtime.h" #include "python_app.h" +#include "shared/common/PythonUtils.h" +#include "python_native_modules.h" #include "map_coordinates.h" +#include "nonplayer_data.h" +#include "game_type.h" +#include "guild_state.h" #include "skill_cooldown.h" #include "eter_net/PythonNetworkStream.h" -#include "eter_render/Gr2ModelRenderer.h" -#include "eter_render/TextTailManager.h" +#include "eter_net/NetworkActorManager.h" #include "eter_render/TerrainHeightmap.h" #include "eter_sound/SoundManager.h" #include "eter_resource/ResourceManager.h" @@ -17,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -29,10 +38,8 @@ namespace ava2 { namespace { PyObject* dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; } PyObject* dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); } -PyObject* dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); } PyObject* dummy_str(PyObject*, PyObject*) { return PyString_FromString(""); } PyObject* dummy_tuple2(PyObject*, PyObject*) { return Py_BuildValue("ii", 0, 0); } -PyObject* dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 0, 0, 0); } struct PlayerSkill { int index = 0; int grade = 0; @@ -236,6 +243,8 @@ static PyObject* player_GetMainCharacterName(PyObject*, PyObject*) { return Py_BuildValue("s", s_playerName.c_str()); } +static PyObject* player_IsObserverMode(PyObject*,PyObject*) { return Py_BuildValue("i",int(PythonNetworkStream::Instance().IsObserverMode())); } +static PyObject* player_HasMobilePhoneNumber(PyObject*,PyObject*) { return Py_BuildValue("i",int(PythonNetworkStream::Instance().HasMobilePhoneNumber())); } static PyObject* player_GetMainCharacterIndex(PyObject*,PyObject*) { return PyLong_FromUnsignedLong(PythonNetworkStream::Instance().GetMainActorVID()); } static PyObject* player_IsMainCharacterIndex(PyObject*,PyObject* args) { unsigned long vid;if(!PyArg_ParseTuple(args,"k",&vid)) return nullptr; @@ -245,6 +254,70 @@ static PyObject* player_GetMainCharacterPosition(PyObject*, PyObject*) { return Py_BuildValue("fff", s_mainActorPos.x, s_mainActorPos.y, s_mainActorPos.z); } +// CPythonPlayer::NEW_GetMainActorPtr: the main character's instance, nullptr before it is added. +static const SNetworkActorData* player_main_actor() { + return NetworkActorManager::Instance().GetActorData(PythonNetworkStream::Instance().GetMainActorVID()); +} +// CPythonPlayer::m_dwPlayTime (player.SetPlayTime from the select phase). +static uint32_t s_playTime = 0; + +static PyObject* player_GetGuildID(PyObject*, PyObject*) { + const auto* pInstance = player_main_actor(); + if (!pInstance) + return Py_BuildValue("i", 0); + return Py_BuildValue("i", int(pInstance->m_dwGuildID)); +} +static PyObject* player_GetGuildName(PyObject*, PyObject*) { + if (const auto* pInstance = player_main_actor()) { + // CPythonGuild::GetGuildName: m_GuildNameMap lookup. + const auto& names = GetGuildState().names; + auto it = names.find(pInstance->m_dwGuildID); + if (it != names.end()) + return Py_BuildValue("s", it->second.c_str()); + } + return Py_BuildValue("s", ""); +} +static PyObject* player_GetPKMode(PyObject*, PyObject*) { + const auto* pInstance = player_main_actor(); + return Py_BuildValue("i", pInstance ? int(pInstance->m_byPKMode) : 0); +} +static PyObject* player_IsGameMaster(PyObject*, PyObject*) { + const auto* mainPlayer = player_main_actor(); + return Py_BuildValue("i", mainPlayer != nullptr ? int(IsGameMaster(*mainPlayer)) : 0); +} +// CPythonPlayer::GetRace: the main character's race (the port keeps it on the network stream). +static PyObject* player_GetRace(PyObject*, PyObject*) { + return Py_BuildValue("i", int(PythonNetworkStream::Instance().GetMainActorRace())); +} +static PyObject* player_GetJob(PyObject*, PyObject*) { + // RaceToJob, ENABLE_WOLFMAN_CHARACTER off. + const int race = int(PythonNetworkStream::Instance().GetMainActorRace()); + const int JOB_NUM = 4; + return Py_BuildValue("i", race % JOB_NUM); +} +// playerGetEXP / playerGetConquerorEXP: DWORD dwEXP = GetStatus(POINT_EXP / POINT_CONQUEROR_EXP), +// built with "l" (a 32-bit long on Windows). +template static PyObject* player_GetDWORDStatus(PyObject*, PyObject*) { + const uint32_t dwEXP = uint32_t(GetPlayerStatusPoint(Point)); + return Py_BuildValue("l", long(int32_t(dwEXP))); +} +static PyObject* player_GetPlayTime(PyObject*, PyObject*) { + return Py_BuildValue("i", int(s_playTime)); +} +static PyObject* player_SetPlayTime(PyObject*, PyObject* poArgs) { + int iTime; + if (!PyTuple_GetInteger(poArgs, 0, &iTime)) + return Py_BuildException(); + s_playTime = uint32_t(iTime); + return Py_BuildNone(); +} +static PyObject* player_SlotTypeToInvenType(PyObject*, PyObject* poArgs) { + int slotType = 0; + if (!PyTuple_GetInteger(poArgs, 0, &slotType)) + return Py_BadArgument(); + return Py_BuildValue("i", int(SlotTypeToInvenType(uint8_t(slotType)))); +} + static PyObject* player_ClickSkillSlot(PyObject*, PyObject* args) { int skillSlot = 0; if (PyArg_ParseTuple(args, "i", &skillSlot)) { @@ -281,7 +354,7 @@ struct ItemInfo { int type = 0; int subType = 0; int width = 1; - int height = 1; + int height = 0; int limitLevel = 0; int applyType = 0; int applyValue = 0; @@ -289,213 +362,45 @@ struct ItemInfo { std::string desc; std::string summary; uint32_t imageHandle = 0; + std::array scale{}; // CItemData::m_ScaleTable.tInfo (ENABLE_SASH_SYSTEM) }; static std::unordered_map s_itemMap; static uint32_t s_selectedItemVnum = 0; -static bool s_itemDatabaseLoaded = false; - +static bool s_hasSelectedItem=false; static std::array s_playerItems{}; static std::map,TItemData> s_windowItems; -static void EnsureItemDatabaseLoaded() { - if (s_itemDatabaseLoaded) return; - s_itemDatabaseLoaded = true; - - // Seed preset items - { - ItemInfo sword9{}; - sword9.vnum = 19; - sword9.name = "Sword+9"; - sword9.iconPath = "icon/item/00010.tga"; - sword9.modelPath = "ymir work/item/weapon/00010.gr2"; - sword9.type = 1; // ITEM_TYPE_WEAPON - sword9.subType = 0; // WEAPON_SWORD - sword9.width = 1; sword9.height = 2; - sword9.limitLevel = 1; - sword9.applyType = 17; sword9.applyValue = 15; - sword9.values[0] = 15; sword9.values[3] = 59; sword9.values[4] = 73; - sword9.desc = "A finely forged one-handed blade, perfectly balanced for rapid strikes."; - s_itemMap[19] = sword9; - } - { - ItemInfo nymph9{}; - nymph9.vnum = 169; - nymph9.name = "Nymph Sword+9"; - nymph9.iconPath = "icon/item/00160.tga"; - nymph9.modelPath = "ymir work/item/weapon/00160.gr2"; - nymph9.type = 1; - nymph9.subType = 0; - nymph9.width = 1; nymph9.height = 2; - nymph9.limitLevel = 65; - nymph9.applyType = 17; nymph9.applyValue = 27; - nymph9.values[0] = 27; nymph9.values[1] = 113; nymph9.values[2] = 137; nymph9.values[3] = 153; nymph9.values[4] = 177; - nymph9.desc = "A swift and deadly sword blessed with ancient nymph enchantments."; - s_itemMap[169] = nymph9; - } - { - ItemInfo glaive9{}; - glaive9.vnum = 3009; - glaive9.name = "Glaive+9"; - glaive9.iconPath = "icon/item/03000.tga"; - glaive9.modelPath = "ymir work/item/weapon/03000.gr2"; - glaive9.type = 1; - glaive9.subType = 3; // WEAPON_TWO_HANDED - glaive9.width = 1; glaive9.height = 3; - glaive9.limitLevel = 9; - glaive9.applyType = 17; glaive9.applyValue = -5; - glaive9.values[0] = -5; glaive9.values[3] = 62; glaive9.values[4] = 84; - glaive9.desc = "A heavy two-handed polearm capable of cleaving multiple foes."; - s_itemMap[3009] = glaive9; - } - { - ItemInfo bsa9{}; - bsa9.vnum = 11299; - bsa9.name = "Black Steel Armour+9"; - bsa9.iconPath = "icon/item/11290.tga"; - bsa9.type = 2; // ITEM_TYPE_ARMOR - bsa9.subType = 0; // ARMOR_BODY - bsa9.width = 1; bsa9.height = 2; - bsa9.limitLevel = 66; - bsa9.applyType = 9; bsa9.applyValue = 20; - bsa9.values[1] = 144; - bsa9.values[5] = 13; - bsa9.desc = "Legendary warrior armor forged from hardened black steel."; - s_itemMap[11299] = bsa9; - } - { - ItemInfo redPot{}; - redPot.vnum = 27003; - redPot.name = "Red Potion (L)"; - redPot.iconPath = "icon/item/27003.tga"; - redPot.type = 3; // ITEM_TYPE_USE - redPot.subType = 0; // USE_POTION - redPot.width = 1; redPot.height = 1; - redPot.limitLevel = 1; - redPot.values[0] = 1200; - redPot.desc = "Instantly recovers 1,200 Health Points."; - s_itemMap[27003] = redPot; - } - { - ItemInfo bluePot{}; - bluePot.vnum = 27006; - bluePot.name = "Blue Potion (L)"; - bluePot.iconPath = "icon/item/27006.tga"; - bluePot.type = 3; - bluePot.subType = 0; - bluePot.width = 1; bluePot.height = 1; - bluePot.limitLevel = 1; - bluePot.values[1] = 400; - bluePot.desc = "Instantly recovers 400 Spell Points."; - s_itemMap[27006] = bluePot; - } - { - ItemInfo cape{}; - cape.vnum = 70038; - cape.name = "Bravery Cape"; - cape.iconPath = "icon/item/70038.tga"; - cape.type = 3; - cape.subType = 1; - cape.width = 1; cape.height = 1; - cape.limitLevel = 1; - cape.desc = "Lures all surrounding monsters into combat."; - s_itemMap[70038] = cape; - } - - // Load additional items from item_list.txt - for (const auto& path : {"locale/en/item_list.txt"}) { - std::string packed; - try { packed=ReadPackedText(path); } catch(const std::exception&) { continue; } - std::istringstream f(packed); - { - std::string line; - while (std::getline(f, line)) { - if (line.empty()) continue; - std::stringstream ss(line); - std::string item; - std::vector tokens; - while (std::getline(ss, item, '\t')) { - while (!item.empty() && (item.back() == '\r' || item.back() == ' ')) item.pop_back(); - tokens.push_back(item); - } - if (tokens.size() >= 3 && !tokens[0].empty() && std::isdigit(tokens[0][0])) { - try { - uint32_t vnum = (uint32_t)std::stoul(tokens[0]); - auto& info = s_itemMap[vnum]; - info.vnum = vnum; - if (info.iconPath.empty()) info.iconPath = tokens[2]; - if (tokens.size() > 3 && info.modelPath.empty()) info.modelPath = tokens[3]; - if (info.type == 0) { - if (tokens[1] == "WEAPON") info.type = 1; - else if (tokens[1] == "ARMOR") info.type = 2; - else info.type = 3; - } - } catch (...) {} - } - } - break; - } - } - - // Load item names from item_names.txt - for (const auto& path : {"locale/en/item_names.txt"}) { - std::string packed; - try { packed=ReadPackedText(path); } catch(const std::exception&) { continue; } - std::istringstream f(packed); - { - std::string line; - while (std::getline(f, line)) { - if (line.empty()) continue; - std::stringstream ss(line); - std::string item; - std::vector tokens; - while (std::getline(ss, item, '\t')) { - while (!item.empty() && (item.back() == '\r' || item.back() == ' ')) item.pop_back(); - tokens.push_back(item); - } - if (tokens.size() >= 2 && !tokens[0].empty() && std::isdigit(tokens[0][0])) { - try { - uint32_t vnum = (uint32_t)std::stoul(tokens[0]); - auto it = s_itemMap.find(vnum); - if (it != s_itemMap.end()) { - if (it->second.name.empty()) it->second.name = tokens[1]; - } else { - ItemInfo info{}; - info.vnum = vnum; - info.name = tokens[1]; - s_itemMap[vnum] = info; - } - } catch (...) {} - } - } - break; - } - } +static ItemProto s_itemProto; +static bool ItemResourceExists(const std::string& path) {try {ReadPackedText(path);return true;}catch(const std::exception&){return CResourceManager::ResourceExists(path);}} +template static PyObject* item_SetSoundFileName(PyObject*,PyObject* args) { + int type;char* filename; + if(!PyTuple_GetInteger(args,0,&type)||!PyTuple_GetString(args,1,&filename))return Py_BadArgument(); + if constexpr(drop)SetItemDropSound(uint32_t(type),filename);else SetItemUseSound(uint32_t(type),filename); + Py_RETURN_NONE; +} +static PyObject* item_GetApplyPoint(PyObject*, PyObject* poArgs) { + int applyType = 0; + if (!PyTuple_GetInteger(poArgs, 0, &applyType)) + return Py_BadArgument(); + return Py_BuildValue("i", int(ApplyTypeToPointType(uint8_t(applyType)))); } -static ItemProto s_itemProto; static PyObject* item_LoadItemTable(PyObject*,PyObject* args) { const char* path;if(!PyArg_ParseTuple(args,"s",&path))return nullptr; - EnsureItemDatabaseLoaded(); - bool loaded=false;try {loaded=s_itemProto.load(ReadPackedText(path));}catch(const std::exception&){} - if(loaded)for(const auto& [id,record]:s_itemProto.records) { - auto& item=s_itemMap[id];item.vnum=id;item.name=record.name;item.type=record.type;item.subType=record.subtype;item.height=record.size; - std::copy(record.values.begin(),record.values.end(),item.values); - item.limitLevel=0;for(const auto& limit:record.limits)if(limit.first==1)item.limitLevel=limit.second; - item.applyType=record.applies[0].first;item.applyValue=record.applies[0].second; - } + LoadItemTable(path); Py_RETURN_NONE; // Original wrapper ignores native loader success. } static bool select_item_data(uint32_t id) { - if(s_itemMap.find(id)!=s_itemMap.end()){s_selectedItemVnum=id;return true;} + if(s_itemMap.find(id)!=s_itemMap.end()){s_selectedItemVnum=id;s_hasSelectedItem=true;return true;} const auto* range=s_itemProto.find(id); - if(range && s_itemMap.find(range->vnum)!=s_itemMap.end()){s_selectedItemVnum=range->vnum;return true;} + if(range && s_itemMap.find(range->vnum)!=s_itemMap.end()){s_selectedItemVnum=range->vnum;s_hasSelectedItem=true;return true;} return false; } static PyObject* item_SelectItem(PyObject*, PyObject* args) { int vnum = 0; if (!PyArg_ParseTuple(args, "i", &vnum)) return nullptr; - EnsureItemDatabaseLoaded(); + if(!select_item_data(uint32_t(vnum)))select_item_data(60001); // Original failed selection keeps the previous pointer if fallback also fails. Py_RETURN_NONE; @@ -503,9 +408,9 @@ static PyObject* item_SelectItem(PyObject*, PyObject* args) { static PyObject* item_Classify(PyObject* args,int query) { int vnum=0;if(!PyArg_ParseTuple(args,"i",&vnum))return nullptr; - EnsureItemDatabaseLoaded(); + if(!select_item_data(static_cast(vnum)))select_item_data(60001); - const auto selected=s_itemMap.find(s_selectedItemVnum); + const auto selected=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(selected==s_itemMap.end()) { PyErr_SetString(PyExc_RuntimeError,"Can't find select item data");return nullptr; } const auto& item=selected->second; if(query==0)return PyInt_FromLong(item.type==3&&item.subType==2); @@ -542,90 +447,74 @@ static PyObject* item_GetUseType(PyObject*,PyObject* args) { return item_Classif static PyObject* item_IsEquipmentVID(PyObject*,PyObject* args) { return item_Classify(args,6); } static PyObject* item_GetItemName(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); + + auto it = (s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if (it != s_itemMap.end()) { return PyString_FromString(it->second.name.c_str()); } - return PyString_FromString(""); + PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr; } + static PyObject* item_GetItemType(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); + + auto it = (s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if (it != s_itemMap.end()) { return PyInt_FromLong(it->second.type); } - return PyInt_FromLong(0); + PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr; } + static PyObject* item_GetItemSubType(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); + + auto it = (s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if (it != s_itemMap.end()) { return PyInt_FromLong(it->second.subType); } - return PyInt_FromLong(0); + PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr; } + static PyObject* item_GetIconImage(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); + + auto it = (s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if (it != s_itemMap.end()) { auto& info = it->second; if (info.imageHandle == 0 && !info.iconPath.empty()) { - std::string p = info.iconPath; + std::string p = ItemResourceExists(info.iconPath)?info.iconPath:"icon/item/27995.tga"; if (p.rfind("d:/", 0) == 0 || p.rfind("D:/", 0) == 0) p = p.substr(3); CResource* pRes = CResourceManager::Instance().GetResourcePointer(p.c_str()); if (pRes && pRes->IsType(CGraphicImage::Type())) { auto* pImg = static_cast(pRes); info.imageHandle = GrpRegisterImageHandle(pImg); - if (pImg->GetWidth() > 0 && pImg->GetHeight() > 0) { - info.width = std::max(1, pImg->GetWidth() / 32); - info.height = std::max(1, pImg->GetHeight() / 32); - } } } return PyInt_FromLong((long)info.imageHandle); } - return PyInt_FromLong(0); + PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr; } + static PyObject* item_GetIconImageFileName(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); - if (it != s_itemMap.end()) { - return PyString_FromString(it->second.iconPath.c_str()); - } - return PyString_FromString(""); + auto it=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); + if(it==s_itemMap.end()) {PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr;} + const auto& declared=it->second.iconPath; + const auto path=ItemResourceExists(declared)?declared:std::string("icon/item/27995.tga"); + if(!ItemResourceExists(path))return PyString_FromString("Noname"); + auto* resource=CResourceManager::Instance().GetResourcePointer(path.c_str()); + if(!resource||!resource->IsType(CGraphicImage::Type()))return PyString_FromString("Noname"); + return PyString_FromString(resource->GetFileName()); } - static PyObject* item_GetItemSize(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); - if (it != s_itemMap.end()) { - auto& info = it->second; - if (info.imageHandle == 0 && !info.iconPath.empty()) { - std::string p = info.iconPath; - if (p.rfind("d:/", 0) == 0 || p.rfind("D:/", 0) == 0) p = p.substr(3); - CResource* pRes = CResourceManager::Instance().GetResourcePointer(p.c_str()); - if (pRes && pRes->IsType(CGraphicImage::Type())) { - auto* pImg = static_cast(pRes); - info.imageHandle = GrpRegisterImageHandle(pImg); - if (pImg->GetWidth() > 0 && pImg->GetHeight() > 0) { - info.width = std::max(1, pImg->GetWidth() / 32); - info.height = std::max(1, pImg->GetHeight() / 32); - } - } - } - return Py_BuildValue("ii", info.width, info.height); - } - return Py_BuildValue("ii", 1, 1); + auto it=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); + if(it==s_itemMap.end()) {PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr;} + return Py_BuildValue("(ii)",1,it->second.height); } static PyObject* item_refine_field(bool set) { - EnsureItemDatabaseLoaded(); - if(s_itemMap.find(s_selectedItemVnum)==s_itemMap.end()) { + + if((s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end())==s_itemMap.end()) { PyErr_SetString(PyExc_RuntimeError,"Can't find select item data");return nullptr; } auto it=s_itemProto.records.find(s_selectedItemVnum); @@ -636,12 +525,12 @@ static PyObject* item_GetRefinedVnum(PyObject*,PyObject*) {return item_refine_fi static PyObject* item_GetRefineSet(PyObject*,PyObject*) {return item_refine_field(true);} static PyObject* item_SelectItemWiki(PyObject*,PyObject* args) { int id;if(!PyArg_ParseTuple(args,"i",&id))return nullptr; - EnsureItemDatabaseLoaded(); + return PyInt_FromLong(select_item_data(uint32_t(id))); } static const ItemProtoRecord* selected_item_record() { - EnsureItemDatabaseLoaded(); - if(s_itemMap.find(s_selectedItemVnum)==s_itemMap.end()) { + + if((s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end())==s_itemMap.end()) { PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr; } auto it=s_itemProto.records.find(s_selectedItemVnum); @@ -678,8 +567,8 @@ static PyObject* item_socket(PyObject*,PyObject* args) { static PyObject* item_table_pair(PyObject* args,bool apply) { int raw;if(!PyArg_ParseTuple(args,"i",&raw))return nullptr; - uint8_t index=uint8_t(raw);EnsureItemDatabaseLoaded(); - auto it=s_itemMap.find(s_selectedItemVnum); + uint8_t index=uint8_t(raw); + auto it=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(it==s_itemMap.end()){PyErr_SetString(PyExc_RuntimeError,"Not yet select item data");return nullptr;} if(index>=(apply?3:2)){PyErr_SetString(PyExc_RuntimeError,"Invalid item table index");return nullptr;} std::pair value{}; @@ -696,8 +585,8 @@ static PyObject* item_GetAffect(PyObject*,PyObject* args){return item_table_pair static PyObject* item_GetValue(PyObject*, PyObject* args) { int idx = 0; if (!PyArg_ParseTuple(args, "i", &idx)) return PyInt_FromLong(0); - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); + + auto it = (s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if (it != s_itemMap.end() && idx >= 0 && idx < 6) { return PyInt_FromLong(it->second.values[idx]); } @@ -705,26 +594,28 @@ static PyObject* item_GetValue(PyObject*, PyObject* args) { } static PyObject* item_GetItemDescription(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); + + auto it = (s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if (it != s_itemMap.end()) { return PyString_FromString(it->second.desc.c_str()); } - return PyString_FromString(""); + PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr; } + static PyObject* item_GetItemSummary(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); + + auto it = (s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if (it != s_itemMap.end()) { return PyString_FromString(it->second.summary.c_str()); } - return PyString_FromString(""); + PyErr_SetString(PyExc_RuntimeError,"no selected item data");return nullptr; } + static PyObject* item_GetNames(PyObject*, PyObject*) { - EnsureItemDatabaseLoaded(); - auto it = s_itemMap.find(s_selectedItemVnum); + + auto it = (s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if (it != s_itemMap.end()) { return PyString_FromString(it->second.name.c_str()); } @@ -836,9 +727,9 @@ static PyObject* player_GetItemGrade(PyObject*, PyObject* args) { else if(!PyArg_ParseTuple(args,"ii",&window,&slot))return nullptr; const auto w=static_cast(window);const auto c=static_cast(slot); const auto vnum=valid_player_item_position(w,c)?GetPlayerItemData(w,c).vnum:0; - EnsureItemDatabaseLoaded(); + if(!select_item_data(vnum))select_item_data(60001); - const auto found=s_itemMap.find(s_selectedItemVnum); + const auto found=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(found==s_itemMap.end()) { PyErr_SetString(PyExc_RuntimeError,"Can't find item data");return nullptr; } const auto& name=found->second.name; const char last=name.empty()?'0':name.back(); @@ -851,7 +742,7 @@ static PyObject* player_IsValuableItem(PyObject*,PyObject* args) { else if(!PyArg_ParseTuple(args,"ii",&window,&cell))return nullptr; const auto w=static_cast(window);const auto c=static_cast(cell); const auto data=valid_player_item_position(w,c)?GetPlayerItemData(w,c):TItemData{}; - EnsureItemDatabaseLoaded(); + if(!select_item_data(data.vnum))select_item_data(60001); if(!s_itemMap.contains(s_selectedItemVnum)) { PyErr_SetString(PyExc_RuntimeError,"Can't find item data");return nullptr; } // Original Packet.h METIN_SOCKET_COUNT is six, not the eight stored sockets. @@ -865,15 +756,15 @@ static PyObject* player_CanUnlock(PyObject*,PyObject* args) { int key=0,window=1,cell=0; if(PyTuple_Size(args)==2) { if(!PyArg_ParseTuple(args,"ii",&key,&cell))return nullptr; } else if(!PyArg_ParseTuple(args,"iii",&key,&window,&cell))return nullptr; - EnsureItemDatabaseLoaded(); + if(!select_item_data(static_cast(key)))select_item_data(60001); - auto selected=s_itemMap.find(s_selectedItemVnum); + auto selected=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(selected==s_itemMap.end()) { PyErr_SetString(PyExc_RuntimeError,"Can't find item data");return nullptr; } if(selected->second.type!=21)return PyInt_FromLong(0); const auto w=static_cast(window);const auto c=static_cast(cell); const auto vnum=valid_player_item_position(w,c)?GetPlayerItemData(w,c).vnum:0; if(!select_item_data(vnum))select_item_data(60001); - selected=s_itemMap.find(s_selectedItemVnum); + selected=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(selected==s_itemMap.end()) { PyErr_SetString(PyExc_RuntimeError,"Can't find item data");return nullptr; } return PyInt_FromLong(selected->second.type==20); } @@ -882,9 +773,9 @@ static PyObject* player_CanDetach(PyObject*,PyObject* args) { int scroll=0,window=1,cell=0; if(PyTuple_Size(args)==2) { if(!PyArg_ParseTuple(args,"ii",&scroll,&cell))return nullptr; } else if(!PyArg_ParseTuple(args,"iii",&scroll,&window,&cell))return nullptr; - EnsureItemDatabaseLoaded(); + if(!select_item_data(static_cast(scroll)))select_item_data(60001); - auto selected=s_itemMap.find(s_selectedItemVnum); + auto selected=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(selected==s_itemMap.end()) { PyErr_SetString(PyExc_RuntimeError,"Can't find item data");return nullptr; } if(selected->second.type!=3||selected->second.subType!=14)return PyInt_FromLong(0); const auto* scrollProto=s_itemProto.find(s_selectedItemVnum); @@ -892,7 +783,7 @@ static PyObject* player_CanDetach(PyObject*,PyObject* args) { const auto w=static_cast(window);const auto c=static_cast(cell); const auto data=valid_player_item_position(w,c)?GetPlayerItemData(w,c):TItemData{}; if(!select_item_data(data.vnum))select_item_data(60001); - selected=s_itemMap.find(s_selectedItemVnum); + selected=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(selected==s_itemMap.end()) { PyErr_SetString(PyExc_RuntimeError,"Can't find item data");return nullptr; } if(sashClean)return PyInt_FromLong(selected->second.type==28&&selected->second.subType==3&&data.alSockets[1]>0); const auto* target=s_itemProto.find(s_selectedItemVnum); @@ -930,13 +821,13 @@ static PyObject* player_CanRefine(PyObject*,PyObject* args) { else if(!PyArg_ParseTuple(args,"iii",&scroll,&window,&cell))return nullptr; const auto w=static_cast(window);const auto c=static_cast(cell); if((w==1||w==2)&&c>=180&&c<216)return PyInt_FromLong(6); - EnsureItemDatabaseLoaded(); + if(!select_item_data(static_cast(scroll)))select_item_data(60001); - auto selected=s_itemMap.find(s_selectedItemVnum); + auto selected=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(selected==s_itemMap.end()||selected->second.type!=3||selected->second.subType!=2)return PyInt_FromLong(0); const auto vnum=valid_player_item_position(w,c)?GetPlayerItemData(w,c).vnum:0; if(!select_item_data(vnum))select_item_data(60001); - selected=s_itemMap.find(s_selectedItemVnum); + selected=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); if(selected==s_itemMap.end())return PyInt_FromLong(0); if(selected->second.type==13)return PyInt_FromLong(7); const auto* proto=s_itemProto.find(s_selectedItemVnum); @@ -1020,6 +911,8 @@ void SetMainCharacterPosition(float x, float y, float z) { s_mainActorPos.z = z; } +const std::string& GetMainCharacterName() { return s_playerName; } + void SetMainCharacterName(const std::string& name) { s_playerName = name; } @@ -1060,10 +953,250 @@ void SetPlayerSkillLevel(int index,int grade,int level) { skill.currentPower=powers[level]/100.0f;skill.nextPower=powers[level+1]/100.0f; } +// CPythonPlayer party / PVP instance sets / kill log (AVA2 PythonPlayer.cpp). +struct PartyMemberInfo { + uint32_t vid=0,pid=0;std::string name;uint8_t state=0,hp=0;std::array affects{}; +}; +static std::map s_partyMembers; +static std::set s_challengeInstances,s_revengeInstances,s_cantFightInstances; +static std::array s_killLog{}; +static void player_trace_error(const std::string& text) { std::cerr<<"[AVA2 TraceError] "<second; +} +void AppendPartyMember(uint32_t pid,const std::string& name) { + PartyMemberInfo info;info.pid=pid;info.name=name;s_partyMembers.insert({pid,info}); +} +void LinkPartyMember(uint32_t pid,uint32_t vid) { + auto* member=find_party_member(pid); + if(!member) {player_trace_error(" CPythonPlayer::LinkPartyMember(dwPID="+std::to_string(int(pid))+", dwVID="+std::to_string(int(vid))+") - Failed to find party member");return;} + member->vid=vid; + ava2::NetworkActorManager::Instance().RefreshTextTail(vid); +} +void UnlinkPartyMember(uint32_t pid) { + auto* member=find_party_member(pid); + if(!member) {player_trace_error(" CPythonPlayer::UnlinkPartyMember(dwPID="+std::to_string(int(pid))+") - Failed to find party member");return;} + member->vid=0; +} +void UpdatePartyMemberInfo(uint32_t pid,uint8_t state,uint8_t hp) { + auto* member=find_party_member(pid); + if(!member) {player_trace_error(" CPythonPlayer::UpdatePartyMemberInfo(dwPID="+std::to_string(int(pid))+", byState="+std::to_string(state)+", byHPPercentage="+std::to_string(hp)+") - Failed to find character");return;} + member->state=state;member->hp=hp; +} +void UpdatePartyMemberAffect(uint32_t pid,uint8_t slot,int16_t affect) { + if(slot>=PARTY_AFFECT_SLOT_MAX_NUM) {player_trace_error(" CPythonPlayer::UpdatePartyMemberAffect(dwPID="+std::to_string(int(pid))+", byAffectSlotIndex="+std::to_string(slot)+", sAffectNumber="+std::to_string(affect)+") - Strange affect slot index");return;} + auto* member=find_party_member(pid); + if(!member) {player_trace_error(" CPythonPlayer::UpdatePartyMemberAffect(dwPID="+std::to_string(int(pid))+", byAffectSlotIndex="+std::to_string(slot)+", sAffectNumber="+std::to_string(affect)+") - Failed to find character");return;} + member->affects[slot]=affect; +} +bool GetPartyMemberState(uint32_t pid,uint8_t* state) { + auto* member=find_party_member(pid);if(!member) return false;*state=member->state;return true; +} +bool PartyMemberPIDToVID(uint32_t pid,uint32_t* vid) { + auto* member=find_party_member(pid);if(!member) return false;*vid=member->vid;return true; +} +static bool party_member_vid_to_pid(uint32_t vid,uint32_t* pid) { + for(const auto& [memberPid,member]:s_partyMembers) if(member.vid==vid) {*pid=memberPid;return true;} + return false; +} +// CPythonBackground::m_strMapName: only Warp() sets it (LoadMap does not), Destroy() clears it. +static std::string s_warpMapName; +bool IsPartyMemberByVID(uint32_t vid) { uint32_t pid;return party_member_vid_to_pid(vid,&pid); } +void RememberChallengeInstance(uint32_t vid) { s_revengeInstances.erase(vid);s_challengeInstances.insert(vid); } +void RememberRevengeInstance(uint32_t vid) { s_challengeInstances.erase(vid);s_revengeInstances.insert(vid); } +void RememberCantFightInstance(uint32_t vid) { s_cantFightInstances.insert(vid); } +void ForgetInstance(uint32_t vid) { s_challengeInstances.erase(vid);s_revengeInstances.erase(vid);s_cantFightInstances.erase(vid); } +void SetKillLOG(const int32_t* log) { std::copy(log,log+s_killLog.size(),s_killLog.begin()); } +// CPythonPlayer::NEW_ClearSkillData. __GetSkillType(it->first) passes the dict key +// (skill index) as a slot index, so the type is looked up on the skill in that slot. +void NEW_ClearSkillData(bool all) { + for(auto it=s_skillSlots.begin();it!=s_skillSlots.end();) { + auto slot=s_playerSkills.find(it->first); + const int type=slot==s_playerSkills.end()?0:GetSkillTypeById(uint32_t(slot->second.index)); + if(all || type==1) it=s_skillSlots.erase(it); else ++it; + } + for(auto& [slot,skill]:s_playerSkills) { skill=PlayerSkill{};skill.nextPower=0.05f; } + // Windows passes Py_BuildNone() as the args tuple: the call raises TypeError and ScriptLib prints it. + if(s_playerGameWindow) { Py_INCREF(Py_None);PyCallClassMemberFunc(s_playerGameWindow,"BINARY_CheckGameButton",Py_None); } +} +namespace { +void itemDefault(ItemInfo& item,const std::string& icon,const std::string& model) { + item.iconPath=icon;item.modelPath=model;item.desc.clear();item.summary.clear(); + auto it=s_itemProto.records.find(item.vnum);if(it!=s_itemProto.records.end())it->second.sockets.fill(0); +} +std::string itemIcon(uint32_t id) {char path[64];std::snprintf(path,sizeof(path),"icon/item/%05d.tga",std::bit_cast(id));return path;} +uint32_t itemNameHash(const std::string& name) {uint32_t result=5381;for(char c:name)result=result*33+uint32_t(int32_t(int8_t(c)));return result;} +std::string itemSnap(const std::string& source) {if(source.size()<2||source[0]!='"')return source;return source.substr(1,source.size()-1-(source.back()=='"'));} +} +void ResetItemDatabase() { + // Avoid the original Destroy() dangling selected/range pointers on locale reload. + s_itemMap.clear();s_itemProto={};s_selectedItemVnum=0;s_hasSelectedItem=false; +} +bool LoadItemList(const std::string& path) { + std::string data;try {data=ReadPackedText(path);}catch(const std::exception&){return false;} + for(const auto& line:ava2TextLines(data)) { + auto fields=ava2TabTokens(line,false);if(fields.size()!=3&&fields.size()!=4)continue; + uint32_t id=uint32_t(std::strtol(fields[0].c_str(),nullptr,10)); + auto& item=s_itemMap[id];item.vnum=id; + // AVA2 ignores the second column entirely; only item_proto supplies type. + itemDefault(item,fields[2],fields.size()==4?fields[3]:std::string{}); + } + return true; +} +// CItemManager::LoadItemScale + CItemData::SetItemScale (AVA2 GameLib, ENABLE_SASH_SYSTEM). +// MakeItemData creates empty records for vnum+0..4 when absent, as Windows does. +bool LoadItemScale(const std::string& path) { + std::string data;try {data=ReadPackedText(path);}catch(const std::exception&){return false;} + const auto lines=ava2TextLines(data); + for(size_t i=0;i=it->second.scale.size())return false; + *out=it->second.scale[pos];return true; +} +bool LoadItemDescriptions(const std::string& path) { + std::string data;try {data=ReadPackedText(path);}catch(const std::exception&){return false;} + for(const auto& line:ava2TextLines(data)) { + auto fields=ava2TabTokens(line,true);if(fields.empty())continue;fields.resize(std::max(fields.size(),size_t(4))); + uint32_t id=uint32_t(std::strtol(fields[0].c_str(),nullptr,10));auto it=s_itemMap.find(id);if(it==s_itemMap.end())continue; + it->second.desc=itemSnap(fields[2]);it->second.summary=itemSnap(fields[3]); + } + return true; +} +bool LoadItemTable(const std::string& path) { + std::string data;try {data=ReadPackedText(path);}catch(const std::exception&){return false;} + if(!s_itemProto.load(data))return false; + std::map nameMap; + for(const auto& record:s_itemProto.recentRecords) { + const auto id=record.vnum;auto it=s_itemMap.find(id); + if(it==s_itemMap.end()) { + std::string icon=itemIcon(id); + if(!ItemResourceExists(icon)) { + auto same=nameMap.find(itemNameHash(record.internalName));icon=itemIcon(same==nameMap.end()?id-id%10:same->second); + if(!ItemResourceExists(icon))icon=itemIcon(27995); + } + auto& item=s_itemMap[id];item.vnum=id;itemDefault(item,icon,{});it=s_itemMap.find(id); + } + nameMap.insert({itemNameHash(record.internalName),id}); + s_itemProto.records[id]=record; + auto& item=it->second;item.name=record.name;item.type=record.type;item.subType=record.subtype;item.height=record.size; + std::copy(record.values.begin(),record.values.end(),item.values); + item.limitLevel=0;for(const auto& limit:record.limits)if(limit.first==1)item.limitLevel=limit.second; + item.applyType=record.applies[0].first;item.applyValue=record.applies[0].second; + } + return true; +} + +bool GetItemNameAndType(uint32_t vnum,std::string* name,int* type) { + if(!vnum)return false; + + auto found=s_itemMap.find(vnum); + if(found==s_itemMap.end()) { + const auto* range=s_itemProto.find(vnum); + if(!range) return false; + found=s_itemMap.find(range->vnum); + if(found==s_itemMap.end()) return false; + } + *name=found->second.name;*type=found->second.type;return true; +} + +bool IsPlayerEquipmentItem(uint8_t window,uint16_t cell) { + // CPythonPlayer::IsEquipItemInSlot selects without the Python fallback. + if((window!=1&&window!=2)||cell<180||cell>=216)return false; + select_item_data(GetPlayerItemData(window,cell).vnum); + const auto it=(s_hasSelectedItem?s_itemMap.find(s_selectedItemVnum):s_itemMap.end()); + return it!=s_itemMap.end()&&(it->second.type==1||it->second.type==2); +} +bool GetItemTypeAndSubType(uint32_t vnum,int* type,int* subType) { + if(!vnum)return false; + + auto found=s_itemMap.find(vnum); + if(found==s_itemMap.end()) { + const auto* range=s_itemProto.find(vnum); + if(!range) return false; + found=s_itemMap.find(range->vnum); + if(found==s_itemMap.end()) return false; + } + *type=found->second.type;*subType=found->second.subType;return true; +} + +static PyObject* player_IsChallengeInstance(PyObject*,PyObject* args) { + int vid;if(!PyArg_ParseTuple(args,"i",&vid)) return nullptr;return Py_BuildValue("i",int(s_challengeInstances.count(uint32_t(vid)))); +} +static PyObject* player_IsRevengeInstance(PyObject*,PyObject* args) { + int vid;if(!PyArg_ParseTuple(args,"i",&vid)) return nullptr;return Py_BuildValue("i",int(s_revengeInstances.count(uint32_t(vid)))); +} +static PyObject* player_IsCantFightInstance(PyObject*,PyObject* args) { + int vid;if(!PyArg_ParseTuple(args,"i",&vid)) return nullptr;return Py_BuildValue("i",int(s_cantFightInstances.count(uint32_t(vid)))); +} +static PyObject* player_IsPartyMember(PyObject*,PyObject* args) { + int vid;if(!PyArg_ParseTuple(args,"i",&vid)) return nullptr;return Py_BuildValue("i",int(IsPartyMemberByVID(uint32_t(vid)))); +} +static PyObject* player_IsPartyLeader(PyObject*,PyObject* args) { + int vid;if(!PyArg_ParseTuple(args,"i",&vid)) return nullptr; + uint32_t pid;if(!party_member_vid_to_pid(uint32_t(vid),&pid)) return Py_BuildValue("i",0); + auto* member=find_party_member(pid);if(!member) return Py_BuildValue("i",0); + return Py_BuildValue("i",int(member->state==1)); // PARTY_ROLE_LEADER +} +static PyObject* player_IsPartyLeaderByPID(PyObject*,PyObject* args) { + int pid;if(!PyArg_ParseTuple(args,"i",&pid)) return nullptr; + auto* member=find_party_member(uint32_t(pid));if(!member) return Py_BuildValue("i",0); + return Py_BuildValue("i",int(member->state==1)); +} +static PyObject* player_GetPartyMemberHPPercentage(PyObject*,PyObject* args) { + int pid;if(!PyArg_ParseTuple(args,"i",&pid)) return nullptr; + auto* member=find_party_member(uint32_t(pid));if(!member) return Py_BuildValue("i",0); + return Py_BuildValue("i",int(member->hp)); +} +static PyObject* player_GetPartyMemberState(PyObject*,PyObject* args) { + int pid;if(!PyArg_ParseTuple(args,"i",&pid)) return nullptr; + auto* member=find_party_member(uint32_t(pid));if(!member) return Py_BuildValue("i",0); + return Py_BuildValue("i",int(member->state)); +} +static PyObject* player_GetPartyMemberAffects(PyObject*,PyObject* args) { + int pid;if(!PyArg_ParseTuple(args,"i",&pid)) return nullptr; + auto* member=find_party_member(uint32_t(pid));if(!member) return Py_BuildValue("i",0); + const auto& a=member->affects; + return Py_BuildValue("iiiiiii",int(a[0]),int(a[1]),int(a[2]),int(a[3]),int(a[4]),int(a[5]),int(a[6])); +} +static PyObject* player_RemovePartyMember(PyObject*,PyObject* args) { + int pid;if(!PyArg_ParseTuple(args,"i",&pid)) return nullptr; + uint32_t vid=0; + if(auto* member=find_party_member(uint32_t(pid))) vid=member->vid; + s_partyMembers.erase(uint32_t(pid)); + if(vid>0) ava2::NetworkActorManager::Instance().RefreshTextTail(vid); + Py_RETURN_NONE; +} +static PyObject* player_ExitParty(PyObject*,PyObject*) { + s_partyMembers.clear(); + ava2::NetworkActorManager::Instance().RefreshAllPCTextTail(); + Py_RETURN_NONE; +} +static PyObject* player_GetKillLOG(PyObject*,PyObject* args) { + int index;if(!PyArg_ParseTuple(args,"i",&index)) return nullptr; + // Windows indexes kill_log[] without a bounds check; out of range returns 0 here. + return Py_BuildValue("l",long(index>=0 && indexsecond; } @@ -1085,16 +1222,13 @@ void SetPlayerItem(int slot,uint32_t vnum,int count) { } std::string GetWeaponModelPathByVnum(uint32_t vnum) { - EnsureItemDatabaseLoaded(); + auto it = s_itemMap.find(vnum); if (it != s_itemMap.end() && !it->second.modelPath.empty()) { std::string p = it->second.modelPath; if (p.rfind("d:/", 0) == 0 || p.rfind("D:/", 0) == 0) p = p.substr(3); return p; } - if (vnum == 19) return "ymir work/item/weapon/00010.gr2"; - if (vnum == 169) return "ymir work/item/weapon/00160.gr2"; - if (vnum == 3009) return "ymir work/item/weapon/03000.gr2"; return ""; } @@ -1103,7 +1237,7 @@ bool UsePlayerItem(int window, int slot, std::string& outEquippedWeaponModel, st auto& itemSlot = s_playerItems[slot]; if (itemSlot.vnum == 0 || itemSlot.count <= 0) return false; - EnsureItemDatabaseLoaded(); + auto it = s_itemMap.find(itemSlot.vnum); if (it == s_itemMap.end()) return false; const auto& info = it->second; @@ -1163,7 +1297,7 @@ bool UsePlayerItem(int window, int slot, std::string& outEquippedWeaponModel, st bool MovePlayerItem(int srcWindow, int srcSlot, int dstWindow, int dstSlot, int count, std::string& outEquippedWeaponModel) { if (srcSlot < 0 || srcSlot >= (int)s_playerItems.size() || dstSlot < 0 || dstSlot >= (int)s_playerItems.size()) return false; - EnsureItemDatabaseLoaded(); + std::swap(s_playerItems[srcSlot], s_playerItems[dstSlot]); if (dstSlot == 184 || srcSlot == 184) { uint32_t eqVnum = s_playerItems[184].vnum; @@ -1189,9 +1323,10 @@ void SetSkillCoolTime(int skillIndex, float coolTime) { } void initItem() { + ResetItemDatabase(); static PyMethodDef methods[] = { - {"SetUseSoundFileName", dummy_none, METH_VARARGS, nullptr}, - {"SetDropSoundFileName", dummy_none, METH_VARARGS, nullptr}, + {"SetUseSoundFileName", item_SetSoundFileName, METH_VARARGS, nullptr}, + {"SetDropSoundFileName", item_SetSoundFileName, METH_VARARGS, nullptr}, {"SelectItem", item_SelectItem, METH_VARARGS, nullptr}, {"GetItemName", item_GetItemName, METH_VARARGS, nullptr}, {"GetItemDescription", item_GetItemDescription, METH_VARARGS, nullptr}, @@ -1231,7 +1366,7 @@ void initItem() { {"GetUnlimitedSealDate", dummy_zero, METH_VARARGS, nullptr}, {"GetNames", item_GetNames, METH_VARARGS, nullptr}, {"IsElement", dummy_zero, METH_VARARGS, nullptr}, - {"GetApplyPoint", dummy_zero, METH_VARARGS, nullptr}, + {"GetApplyPoint", item_GetApplyPoint, METH_VARARGS, nullptr}, {"GetItemsByName", dummy_str, METH_VARARGS, nullptr}, {"HasDropInfo", dummy_none, METH_VARARGS, nullptr}, {"GetDropInfo", dummy_zero, METH_VARARGS, nullptr}, @@ -1643,13 +1778,13 @@ void initPlayer() { {"IsActingEmotion", dummy_zero, METH_VARARGS, nullptr}, {"IsPVPInstance", dummy_zero, METH_VARARGS, nullptr}, {"IsSameEmpire", dummy_zero, METH_VARARGS, nullptr}, - {"IsChallengeInstance", dummy_zero, METH_VARARGS, nullptr}, - {"IsRevengeInstance", dummy_zero, METH_VARARGS, nullptr}, - {"IsCantFightInstance", dummy_zero, METH_VARARGS, nullptr}, + {"IsChallengeInstance", player_IsChallengeInstance, METH_VARARGS, nullptr}, + {"IsRevengeInstance", player_IsRevengeInstance, METH_VARARGS, nullptr}, + {"IsCantFightInstance", player_IsCantFightInstance, METH_VARARGS, nullptr}, {"GetCharacterDistance", dummy_zero, METH_VARARGS, nullptr}, {"IsInSafeArea", dummy_zero, METH_VARARGS, nullptr}, {"IsMountingHorse", dummy_zero, METH_VARARGS, nullptr}, - {"IsObserverMode", dummy_zero, METH_VARARGS, nullptr}, + {"IsObserverMode", player_IsObserverMode, METH_VARARGS, nullptr}, {"ActEmotion", dummy_none, METH_VARARGS, nullptr}, {"ShowPlayer", dummy_none, METH_VARARGS, nullptr}, {"HidePlayer", dummy_none, METH_VARARGS, nullptr}, @@ -1685,24 +1820,24 @@ void initPlayer() { {"MoveItem", dummy_none, METH_VARARGS, nullptr}, {"SendClickItemPacket", dummy_none, METH_VARARGS, nullptr}, {"GetName", player_GetName, METH_VARARGS, nullptr}, - {"IsGameMaster", dummy_zero, METH_VARARGS, nullptr}, - {"GetJob", dummy_zero, METH_VARARGS, nullptr}, - {"GetRace", dummy_zero, METH_VARARGS, nullptr}, - {"GetPlayTime", dummy_zero, METH_VARARGS, nullptr}, - {"SetPlayTime", dummy_none, METH_VARARGS, nullptr}, + {"IsGameMaster", player_IsGameMaster, METH_VARARGS, nullptr}, + {"GetJob", player_GetJob, METH_VARARGS, nullptr}, + {"GetRace", player_GetRace, METH_VARARGS, nullptr}, + {"GetPlayTime", player_GetPlayTime, METH_VARARGS, nullptr}, + {"SetPlayTime", player_SetPlayTime, METH_VARARGS, nullptr}, {"IsSkillCoolTime", player_IsSkillCoolTime, METH_VARARGS, nullptr}, {"GetSkillCoolTime", player_GetSkillCoolTime, METH_VARARGS, nullptr}, {"IsSkillActive", dummy_zero, METH_VARARGS, nullptr}, {"UseGuildSkill", dummy_none, METH_VARARGS, nullptr}, {"AffectIndexToSkillIndex", player_AffectIndexToSkillIndex, METH_VARARGS, nullptr}, - {"GetEXP", dummy_zero, METH_VARARGS, nullptr}, - {"GetConquerorEXP", dummy_zero, METH_VARARGS, nullptr}, + {"GetEXP", player_GetDWORDStatus<3 /* POINT_EXP */>, METH_VARARGS, nullptr}, + {"GetConquerorEXP", player_GetDWORDStatus<212 /* POINT_CONQUEROR_EXP */>, METH_VARARGS, nullptr}, {"GetStatus", player_GetStatus, METH_VARARGS, nullptr}, {"SetStatus", player_SetStatus, METH_VARARGS, nullptr}, {"GetElk", player_GetElk, METH_VARARGS, nullptr}, {"GetMoney", player_GetMoney, METH_VARARGS, nullptr}, - {"GetGuildID", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildName", dummy_str, METH_VARARGS, nullptr}, + {"GetGuildID", player_GetGuildID, METH_VARARGS, nullptr}, + {"GetGuildName", player_GetGuildName, METH_VARARGS, nullptr}, {"GetAlignmentData", dummy_tuple2, METH_VARARGS, nullptr}, {"RequestAddLocalQuickSlot", player_RequestAddLocalQuickSlot, METH_VARARGS, nullptr}, {"RequestAddToEmptyLocalQuickSlot", player_AddEmptyQuick, METH_VARARGS, nullptr}, @@ -1744,16 +1879,16 @@ void initPlayer() { {"Clear", dummy_none, METH_VARARGS, nullptr}, {"IsCombatZoneMap", dummy_zero, METH_VARARGS, nullptr}, {"GetCombatZonePoints", dummy_zero, METH_VARARGS, nullptr}, - {"IsPartyMember", dummy_zero, METH_VARARGS, nullptr}, - {"IsPartyLeader", dummy_zero, METH_VARARGS, nullptr}, - {"IsPartyLeaderByPID", dummy_zero, METH_VARARGS, nullptr}, - {"GetPartyMemberHPPercentage", dummy_zero, METH_VARARGS, nullptr}, - {"GetPartyMemberState", dummy_zero, METH_VARARGS, nullptr}, - {"GetPartyMemberAffects", dummy_zero, METH_VARARGS, nullptr}, - {"RemovePartyMember", dummy_none, METH_VARARGS, nullptr}, - {"ExitParty", dummy_none, METH_VARARGS, nullptr}, - {"GetPKMode", dummy_zero, METH_VARARGS, nullptr}, - {"HasMobilePhoneNumber", dummy_none, METH_VARARGS, nullptr}, + {"IsPartyMember", player_IsPartyMember, METH_VARARGS, nullptr}, + {"IsPartyLeader", player_IsPartyLeader, METH_VARARGS, nullptr}, + {"IsPartyLeaderByPID", player_IsPartyLeaderByPID, METH_VARARGS, nullptr}, + {"GetPartyMemberHPPercentage", player_GetPartyMemberHPPercentage, METH_VARARGS, nullptr}, + {"GetPartyMemberState", player_GetPartyMemberState, METH_VARARGS, nullptr}, + {"GetPartyMemberAffects", player_GetPartyMemberAffects, METH_VARARGS, nullptr}, + {"RemovePartyMember", player_RemovePartyMember, METH_VARARGS, nullptr}, + {"ExitParty", player_ExitParty, METH_VARARGS, nullptr}, + {"GetPKMode", player_GetPKMode, METH_VARARGS, nullptr}, + {"HasMobilePhoneNumber", player_HasMobilePhoneNumber, METH_VARARGS, nullptr}, {"RegisterEmotionIcon", dummy_none, METH_VARARGS, nullptr}, {"GetEmotionIconImage", dummy_zero, METH_VARARGS, nullptr}, {"SetWeaponAttackBonusFlag", dummy_none, METH_VARARGS, nullptr}, @@ -1765,14 +1900,14 @@ void initPlayer() { {"SetItemAttribute", dummy_none, METH_VARARGS, nullptr}, {"SetItemCount", dummy_none, METH_VARARGS, nullptr}, {"GetItemLink", dummy_zero, METH_VARARGS, nullptr}, - {"SlotTypeToInvenType", dummy_none, METH_VARARGS, nullptr}, + {"SlotTypeToInvenType", player_SlotTypeToInvenType, METH_VARARGS, nullptr}, {"SendDragonSoulRefine", dummy_none, METH_VARARGS, nullptr}, {"GetItemRandomAttribute", dummy_tuple2, METH_VARARGS, nullptr}, {"CanSealItem", dummy_none, METH_VARARGS, nullptr}, {"GetItemSealDate", dummy_zero, METH_VARARGS, nullptr}, {"GetItemUnSealLeftTime", dummy_zero, METH_VARARGS, nullptr}, {"GetItemNewName", player_GetItemNewName, METH_VARARGS, nullptr}, - {"GetKillLOG", dummy_zero, METH_VARARGS, nullptr}, + {"GetKillLOG", player_GetKillLOG, METH_VARARGS, nullptr}, {"GetMainCharacterPart", dummy_zero, METH_VARARGS, nullptr}, {"GetMainCharacterShiningPart", dummy_zero, METH_VARARGS, nullptr}, {"LoadNewRegen", dummy_none, METH_VARARGS, nullptr}, @@ -1781,6 +1916,37 @@ void initPlayer() { {"GetEventGame", dummy_zero, METH_VARARGS, nullptr}, {nullptr, nullptr, 0, nullptr} }; + NetworkActorManager::SetPartyMemberQuery(IsPartyMemberByVID); + NetworkActorManager::SetNPCWearQuery([](uint32_t race, uint8_t wearIndex) { + return NonPlayerData::Instance().getNPCWear(int(race), wearIndex, s_warpMapName); + }); + NetworkActorManager::SetItemScaleQuery([](uint32_t vnum, uint32_t pos, float scale[3], float position[3]) { + ItemScaleInfo info; + if (!GetItemScale(vnum, pos, &info)) return false; + scale[0] = info.scaleX; scale[1] = info.scaleY; scale[2] = info.scaleZ; + position[0] = info.positionX; position[1] = info.positionY; position[2] = info.positionZ; + return true; + }); + // CItemManager::GetItemDataPointer (vnum ranges resolve to the base row) for the model parts. + NetworkActorManager::SetItemDataQuery([](uint32_t vnum, SItemModelData* out) { + if (!vnum) return false; + auto found = s_itemMap.find(vnum); + if (found == s_itemMap.end()) { + const auto* range = s_itemProto.find(vnum); + if (!range) return false; + found = s_itemMap.find(range->vnum); + if (found == s_itemMap.end()) return false; + } + const auto& info = found->second; + out->vnum = found->first; + out->model = info.modelPath; + out->type = uint8_t(info.type); + out->subType = uint8_t(info.subType); + std::copy_n(info.values, 6, out->values); + const auto* proto = s_itemProto.find(found->first); + out->specular = proto ? float(proto->specular) / 100.0f : 0.0f; + return true; + }); auto* module = Py_InitModule("player", methods); PyModule_AddIntConstant(module, "LEVEL", 1); @@ -2100,752 +2266,8 @@ void initPlayer() { PyModule_AddIntConstant(module, "REFINE_VNUM_POTION_EXTRA", 56003); } -void initchrmgr() { - static PyMethodDef methods[] = { - {"SetRaceHeight", dummy_none, METH_VARARGS, nullptr}, - {"SetEmpireNameMode", dummy_none, METH_VARARGS, nullptr}, - {"GetVIDInfo", dummy_zero, METH_VARARGS, nullptr}, - {"GetPickedVID", dummy_zero, METH_VARARGS, nullptr}, - {"SetShapeModel", dummy_none, METH_VARARGS, nullptr}, - {"AppendShapeSkin", dummy_none, METH_VARARGS, nullptr}, - {"SetPathName", dummy_none, METH_VARARGS, nullptr}, - {"LoadRaceData", dummy_none, METH_VARARGS, nullptr}, - {"LoadLocalRaceData", dummy_none, METH_VARARGS, nullptr}, - {"CreateRace", dummy_none, METH_VARARGS, nullptr}, - {"SelectRace", dummy_none, METH_VARARGS, nullptr}, - {"RegisterAttachingBoneName", dummy_none, METH_VARARGS, nullptr}, - {"RegisterMotionMode", dummy_none, METH_VARARGS, nullptr}, - {"RegisterMotion", dummy_none, METH_VARARGS, nullptr}, - {"SetMotionRandomWeight", dummy_none, METH_VARARGS, nullptr}, - {"RegisterNormalAttack", dummy_none, METH_VARARGS, nullptr}, - {"ReserveComboAttack", dummy_none, METH_VARARGS, nullptr}, - {"RegisterComboAttack", dummy_none, METH_VARARGS, nullptr}, - {"ReserveComboAttackNew", dummy_none, METH_VARARGS, nullptr}, - {"RegisterComboAttackNew", dummy_none, METH_VARARGS, nullptr}, - {"RegisterMotionData", dummy_none, METH_VARARGS, nullptr}, - {"RegisterRaceName", dummy_none, METH_VARARGS, nullptr}, - {"RegisterRaceSrcName", dummy_none, METH_VARARGS, nullptr}, - {"RegisterCacheMotionData", dummy_none, METH_VARARGS, nullptr}, - {"SetAffect", dummy_none, METH_VARARGS, nullptr}, - {"SetEmoticon", dummy_none, METH_VARARGS, nullptr}, - {"IsPossibleEmoticon", dummy_zero, METH_VARARGS, nullptr}, - {"RegisterEffect", dummy_none, METH_VARARGS, nullptr}, - {"RegisterCacheEffect", dummy_none, METH_VARARGS, nullptr}, - {"RegisterPointEffect", dummy_none, METH_VARARGS, nullptr}, - {"ShowPointEffect", dummy_none, METH_VARARGS, nullptr}, - {"ToggleDirectionLine", dummy_none, METH_VARARGS, nullptr}, - {"SetMovingSpeed", dummy_none, METH_VARARGS, nullptr}, - {"SetDustGap", dummy_none, METH_VARARGS, nullptr}, - {"SetHorseDustGap", dummy_none, METH_VARARGS, nullptr}, - {"RegisterTitleName", dummy_none, METH_VARARGS, nullptr}, - {"RegisterNameColor", dummy_none, METH_VARARGS, nullptr}, - {"RegisterTitleColor", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("chrmgr", methods); - PyModule_AddIntConstant(module, "NAMECOLOR_SHOP", 27); - PyModule_AddIntConstant(module, "NAMECOLOR_MOB", 7); - PyModule_AddIntConstant(module, "NAMECOLOR_NPC", 8); - PyModule_AddIntConstant(module, "NAMECOLOR_PC", 9); - PyModule_AddIntConstant(module, "NAMECOLOR_EMPIRE_MOB", 14); - PyModule_AddIntConstant(module, "NAMECOLOR_EMPIRE_NPC", 15); - PyModule_AddIntConstant(module, "NAMECOLOR_EMPIRE_PC", 16); - PyModule_AddIntConstant(module, "NAMECOLOR_FUNC", 21); - PyModule_AddIntConstant(module, "NAMECOLOR_PK", 22); - PyModule_AddIntConstant(module, "NAMECOLOR_PVP", 23); - PyModule_AddIntConstant(module, "NAMECOLOR_PARTY", 24); - PyModule_AddIntConstant(module, "NAMECOLOR_WARP", 25); - PyModule_AddIntConstant(module, "NAMECOLOR_WAYPOINT", 26); - PyModule_AddIntConstant(module, "NAMECOLOR_EXTRA", 31); - PyModule_AddIntConstant(module, "NAMECOLOR_METIN", 30); - PyModule_AddIntConstant(module, "NAMECOLOR_CONQUEROR", 29); - PyModule_AddIntConstant(module, "NAMECOLOR_BOSS", 28); - PyModule_AddIntConstant(module, "NAMECOLOR_TOURNAMENT_TEAM_A", 32); - PyModule_AddIntConstant(module, "NAMECOLOR_TOURNAMENT_TEAM_B", 33); - PyModule_AddIntConstant(module, "EFFECT_ELEMENTS_WEAPON", 280); - PyModule_AddIntConstant(module, "EFFECT_SPAWN_DISAPPEAR", 10); - PyModule_AddIntConstant(module, "EFFECT_SPAWN_APPEAR", 9); - PyModule_AddIntConstant(module, "EFFECT_DUST", 0); - PyModule_AddIntConstant(module, "EFFECT_HORSE_DUST", 228); - PyModule_AddIntConstant(module, "EFFECT_STUN", 1); - PyModule_AddIntConstant(module, "EFFECT_HIT", 2); - PyModule_AddIntConstant(module, "EFFECT_FLAME_ATTACK", 3); - PyModule_AddIntConstant(module, "EFFECT_FLAME_HIT", 4); - PyModule_AddIntConstant(module, "EFFECT_FLAME_ATTACH", 5); - PyModule_AddIntConstant(module, "EFFECT_ELECTRIC_ATTACK", 6); - PyModule_AddIntConstant(module, "EFFECT_ELECTRIC_HIT", 7); - PyModule_AddIntConstant(module, "EFFECT_ELECTRIC_ATTACH", 8); - PyModule_AddIntConstant(module, "EFFECT_SELECT", 221); - PyModule_AddIntConstant(module, "EFFECT_TARGET", 222); - PyModule_AddIntConstant(module, "EFFECT_CRITICAL", 17); - PyModule_AddIntConstant(module, "EFFECT_DAMAGE_TARGET", 254); - PyModule_AddIntConstant(module, "EFFECT_DAMAGE_NOT_TARGET", 255); - PyModule_AddIntConstant(module, "EFFECT_DAMAGE_SELFDAMAGE", 256); - PyModule_AddIntConstant(module, "EFFECT_DAMAGE_SELFDAMAGE2", 257); - PyModule_AddIntConstant(module, "EFFECT_DAMAGE_POISON", 258); - PyModule_AddIntConstant(module, "EFFECT_DAMAGE_MISS", 259); - PyModule_AddIntConstant(module, "EFFECT_DAMAGE_TARGETMISS", 260); - PyModule_AddIntConstant(module, "EFFECT_DAMAGE_CRITICAL", 261); - PyModule_AddIntConstant(module, "EFFECT_LEVELUP", 11); - PyModule_AddIntConstant(module, "EFFECT_SKILLUP", 12); - PyModule_AddIntConstant(module, "EFFECT_HPUP_RED", 13); - PyModule_AddIntConstant(module, "EFFECT_SPUP_BLUE", 14); - PyModule_AddIntConstant(module, "EFFECT_SPEEDUP_GREEN", 15); - PyModule_AddIntConstant(module, "EFFECT_DXUP_PURPLE", 16); - PyModule_AddIntConstant(module, "EFFECT_PENETRATE", 18); - PyModule_AddIntConstant(module, "EFFECT_BLOCK", 19); - PyModule_AddIntConstant(module, "EFFECT_DODGE", 20); - PyModule_AddIntConstant(module, "EFFECT_FIRECRACKER", 21); - PyModule_AddIntConstant(module, "EFFECT_SPIN_TOP", 22); - PyModule_AddIntConstant(module, "EFFECT_WEAPON", 23); - PyModule_AddIntConstant(module, "EFFECT_AFFECT", 27); - PyModule_AddIntConstant(module, "EFFECT_EMOTICON", 92); - PyModule_AddIntConstant(module, "EFFECT_EMPIRE", 223); - PyModule_AddIntConstant(module, "EFFECT_REFINED", 229); - PyModule_AddIntConstant(module, "EFFECT_SUCCESS", 262); - PyModule_AddIntConstant(module, "EFFECT_FAIL", 263); - PyModule_AddIntConstant(module, "EFFECT_FR_SUCCESS", 264); - PyModule_AddIntConstant(module, "EFFECT_LEVELUP_ON_14_FOR_GERMANY", 265); - PyModule_AddIntConstant(module, "EFFECT_LEVELUP_UNDER_15_FOR_GERMANY", 266); - PyModule_AddIntConstant(module, "EFFECT_PERCENT_DAMAGE1", 267); - PyModule_AddIntConstant(module, "EFFECT_PERCENT_DAMAGE2", 268); - PyModule_AddIntConstant(module, "EFFECT_PERCENT_DAMAGE3", 269); - PyModule_AddIntConstant(module, "EFFECT_AUTO_HPUP", 270); - PyModule_AddIntConstant(module, "EFFECT_AUTO_SPUP", 271); - PyModule_AddIntConstant(module, "EFFECT_RAMADAN_RING_EQUIP", 272); - PyModule_AddIntConstant(module, "EFFECT_HALLOWEEN_CANDY_EQUIP", 273); - PyModule_AddIntConstant(module, "EFFECT_HAPPINESS_RING_EQUIP", 274); - PyModule_AddIntConstant(module, "EFFECT_LOVE_PENDANT_EQUIP", 275); - PyModule_AddIntConstant(module, "EFFECT_SASH_SUCCEDED", 277); - PyModule_AddIntConstant(module, "EFFECT_SASH_EQUIP", 278); - PyModule_AddIntConstant(module, "EFFECT_HEALER", 279); - PyModule_AddIntConstant(module, "EFFECT_SHINING_WEAPON", 280); - PyModule_AddIntConstant(module, "EFFECT_SHINING_ARMOR", 14281); - PyModule_AddIntConstant(module, "EFFECT_SHINING_SPECIAL", 14302); - PyModule_AddIntConstant(module, "EFFECT_SKILL_DAMAGE_ZONE", 14313); - PyModule_AddIntConstant(module, "EFFECT_SKILL_DAMAGE_ZONE_BUYUK", 14314); - PyModule_AddIntConstant(module, "EFFECT_SKILL_DAMAGE_ZONE_ORTA", 14315); - PyModule_AddIntConstant(module, "EFFECT_SKILL_DAMAGE_ZONE_KUCUK", 14316); - PyModule_AddIntConstant(module, "EFFECT_SKILL_SAFE_ZONE", 14317); - PyModule_AddIntConstant(module, "EFFECT_SKILL_SAFE_ZONE_BUYUK", 14318); - PyModule_AddIntConstant(module, "EFFECT_SKILL_SAFE_ZONE_KUCUK", 14320); - PyModule_AddIntConstant(module, "EFFECT_SKILL_SAFE_ZONE_ORTA", 14319); - PyModule_AddIntConstant(module, "EFFECT_METEOR", 14321); - PyModule_AddIntConstant(module, "EFFECT_BEAD_RAIN", 14322); - PyModule_AddIntConstant(module, "EFFECT_FALL_ROCK", 14323); - PyModule_AddIntConstant(module, "EFFECT_ARROW_RAIN", 14324); - PyModule_AddIntConstant(module, "EFFECT_HORSE_DROP", 14325); - PyModule_AddIntConstant(module, "EFFECT_EGG_DROP", 14326); - PyModule_AddIntConstant(module, "EFFECT_DEAPO_BOOM", 14327); -} - -namespace { - -static std::string FindChrModelPath(const std::string& path) { - std::string rel = path; - if (rel.rfind("d:/", 0) == 0 || rel.rfind("D:/", 0) == 0) { - rel = rel.substr(3); - } - if (std::filesystem::exists(rel)) return rel; - if (std::filesystem::exists("build/dev/" + rel)) return "build/dev/" + rel; - if (std::filesystem::exists("../" + rel)) return "../" + rel; - return rel; -} - -static std::string GetRaceModelPath(int race) { - switch (race) { - case 0: return FindChrModelPath("ymir work/pc/warrior/warrior_assasin1.gr2"); - case 1: return FindChrModelPath("ymir work/pc/assassin/assassin_halloween1_lod_01.gr2"); - case 2: return FindChrModelPath("ymir work/pc/sura/sura_soccer1_germany_lod_02.gr2"); - case 3: return FindChrModelPath("ymir work/pc/shaman/shaman_fencing1_germany_lod_02.gr2"); - case 4: return FindChrModelPath("ymir work/pc/plechito/summer2020_costume/warrior_w.gr2"); - case 5: return FindChrModelPath("ymir work/pc/plechito/summer2020_costume/assassin_m.gr2"); - case 6: return FindChrModelPath("ymir work/pc/plechito/summer2020_costume/sura_w.gr2"); - case 7: return FindChrModelPath("ymir work/pc/plechito/summer2020_costume/shaman_m.gr2"); - case 101: return FindChrModelPath("ymir work/npc_mount/christmas_2017_sleddog/christmas_2017_sleddog.gr2"); - case 102: return FindChrModelPath("ymir work/monster/plechi_golden_frog/plechi_golden_frog.gr2"); - case 103: return FindChrModelPath("ymir work/monster/plechi_slime_monster1/plechi_slime_monster1.gr2"); - case 2018: return FindChrModelPath("ymir work/npc_mount/halloween_2018_cerberos/halloween_2018_cerberos.gr2"); - case 8001: case 8002: case 8003: return FindChrModelPath("ymir work/monster/metinstone_02/metinstone_10.gr2"); - case 20001: case 20016: return FindChrModelPath("ymir work/npc/12zi_statue_rabbit_npc/12zi_statue_rabbit_npc.gr2"); - default: return FindChrModelPath("ymir work/pc/warrior/warrior_assasin1.gr2"); - } -} - -struct ChrInstanceState { - int id = 0; - int race = 0; - int shape = 0; - int weapon = 0; - int hair = 0; - float posX = 0.0f, posY = 0.0f, posZ = 0.0f; - float rot = 0.0f; - float anim_time = 0.0f; - bool visible = true; - std::string name; - std::shared_ptr body_model; -}; - -static std::unordered_map s_chrInstances; -static int s_selectedChrId = 0; - -PyObject* chr_create_instance(PyObject*, PyObject* args) { - int id = 0; - if (PyArg_ParseTuple(args, "i", &id)) { - s_chrInstances[id] = ChrInstanceState{}; - s_chrInstances[id].id = id; - s_selectedChrId = id; - } - Py_RETURN_NONE; -} - -PyObject* chr_delete_instance(PyObject*, PyObject* args) { - int id = 0; - if (PyArg_ParseTuple(args, "i", &id)) { - s_chrInstances.erase(id); - TextTailManager::Instance().DeleteCharacterTextTail(static_cast(id)); - } - Py_RETURN_NONE; -} - -PyObject* chr_has_instance(PyObject*, PyObject* args) { - int id = 0; - if (PyArg_ParseTuple(args, "i", &id)) { - return Py_BuildValue("i", s_chrInstances.find(id) != s_chrInstances.end() ? 1 : 0); - } - return Py_BuildValue("i", 0); -} - -PyObject* chr_select_instance(PyObject*, PyObject* args) { - int id = 0; - if (PyArg_ParseTuple(args, "i", &id)) { - s_selectedChrId = id; - } - Py_RETURN_NONE; -} - -PyObject* chr_set_race(PyObject*, PyObject* args) { - int race = 0; - if (PyArg_ParseTuple(args, "i", &race)) { - auto& inst = s_chrInstances[s_selectedChrId]; - inst.race = race; - std::string model_file = GetRaceModelPath(race); - if (std::filesystem::exists(model_file)) { - inst.body_model = Gr2ModelInstance::Load(model_file); - } - } - Py_RETURN_NONE; -} - -PyObject* chr_get_race(PyObject*, PyObject*) { - auto it = s_chrInstances.find(s_selectedChrId); - return Py_BuildValue("i", it != s_chrInstances.end() ? it->second.race : 0); -} - -PyObject* chr_change_shape(PyObject*, PyObject* args) { - int shape = 0; - if (PyArg_ParseTuple(args, "i", &shape)) { - auto& inst = s_chrInstances[s_selectedChrId]; - inst.shape = shape; - if (inst.body_model) { - if (shape > 0) { - std::string hp = FindChrModelPath("ymir work/pc/plechito/summer2020_costume/hair/warrior_m.gr2"); - if (std::filesystem::exists(hp)) { - auto hair_model = Gr2ModelInstance::Load(hp); - if (hair_model) { - inst.body_model->AttachPart(std::move(hair_model)); - } - } - } else { - std::string model_file = GetRaceModelPath(inst.race); - if (std::filesystem::exists(model_file)) { - inst.body_model = Gr2ModelInstance::Load(model_file); - if (inst.weapon > 0) { - std::string wp = FindChrModelPath("ymir work/item/weapon/set_11_sword.gr2"); - if (std::filesystem::exists(wp)) { - auto wep_model = Gr2ModelInstance::Load(wp); - if (wep_model) inst.body_model->AttachModel("equip_right_hand", std::move(wep_model)); - } - } - } - } - } - } - Py_RETURN_NONE; -} - -PyObject* chr_set_weapon(PyObject*, PyObject* args) { - int weapon = 0; - if (PyArg_ParseTuple(args, "i", &weapon)) { - auto& inst = s_chrInstances[s_selectedChrId]; - inst.weapon = weapon; - if (inst.body_model && weapon > 0) { - std::string model = GetWeaponModelPathByVnum(weapon); - if (model.empty()) model = "ymir work/item/weapon/set_11_sword.gr2"; - std::string wp = FindChrModelPath(model); - if (std::filesystem::exists(wp)) { - auto wep_model = Gr2ModelInstance::Load(wp); - if (wep_model) { - inst.body_model->AttachModel("equip_right_hand", std::move(wep_model)); - } - } - } - } - Py_RETURN_NONE; -} - -PyObject* chr_set_hair(PyObject*, PyObject* args) { - int hair = 0; - if (PyArg_ParseTuple(args, "i", &hair)) { - auto& inst = s_chrInstances[s_selectedChrId]; - inst.hair = hair; - if (inst.body_model && hair > 0) { - std::string hp = FindChrModelPath("ymir work/pc/plechito/summer2020_costume/hair/warrior_m.gr2"); - if (std::filesystem::exists(hp)) { - auto hair_model = Gr2ModelInstance::Load(hp); - if (hair_model) { - inst.body_model->AttachPart(std::move(hair_model)); - } - } - } - } - Py_RETURN_NONE; -} - -PyObject* chr_set_rotation(PyObject*, PyObject* args) { - float rot = 0.0f; - if (PyArg_ParseTuple(args, "f", &rot)) { - s_chrInstances[s_selectedChrId].rot = rot; - } - Py_RETURN_NONE; -} - -PyObject* chr_set_name_string(PyObject*, PyObject* args) { - const char* name = nullptr; - if (PyArg_ParseTuple(args, "s", &name)) { - auto& inst = s_chrInstances[s_selectedChrId]; - inst.name = name ? name : ""; - TextTailManager::Instance().SetCharacterName(static_cast(s_selectedChrId), inst.name); - } - Py_RETURN_NONE; -} - -PyObject* chr_get_name(PyObject*, PyObject*) { - auto it = s_chrInstances.find(s_selectedChrId); - if (it != s_chrInstances.end()) { - return PyString_FromString(it->second.name.c_str()); - } - return PyString_FromString(""); -} - -PyObject* chr_get_name_by_vid(PyObject*, PyObject* args) { - int vid = 0; - if (PyArg_ParseTuple(args, "i", &vid)) { - auto it = s_chrInstances.find(vid); - if (it != s_chrInstances.end()) { - return PyString_FromString(it->second.name.c_str()); - } - } - return PyString_FromString(""); -} - -PyObject* chr_get_pixel_position(PyObject*, PyObject* args) { - int vid = s_selectedChrId; - if (args && PyTuple_Size(args) > 0) { - PyArg_ParseTuple(args, "i", &vid); - } - auto it = s_chrInstances.find(vid); - if (it != s_chrInstances.end()) { - return Py_BuildValue("fff", it->second.posX, it->second.posY, it->second.posZ); - } - return Py_BuildValue("fff", 0.0f, 0.0f, 0.0f); -} - -PyObject* chr_set_pixel_position(PyObject*, PyObject* args) { - int x = 0, y = 0, z = 0; - if (PyArg_ParseTuple(args, "ii|i", &x, &y, &z)) { - auto& inst = s_chrInstances[s_selectedChrId]; - inst.posX = static_cast(x); - inst.posY = static_cast(y); - inst.posZ = static_cast(z); - TextTailManager::Instance().SetCharacterPosition(static_cast(s_selectedChrId), inst.posX, inst.posY, inst.posZ); - } - Py_RETURN_NONE; -} - -PyObject* chr_update(PyObject*, PyObject*) { - for (auto& [id, inst] : s_chrInstances) { - inst.anim_time += 0.033f; - } - Py_RETURN_NONE; -} - -PyObject* chr_show(PyObject*, PyObject*) { - s_chrInstances[s_selectedChrId].visible = true; - Py_RETURN_NONE; -} - -PyObject* chr_hide(PyObject*, PyObject*) { - s_chrInstances[s_selectedChrId].visible = false; - Py_RETURN_NONE; -} - -PyObject* chr_destroy(PyObject*, PyObject*) { - s_chrInstances.clear(); - s_selectedChrId = 0; - TextTailManager::Instance().Clear(); - Py_RETURN_NONE; -} - -} // namespace - -std::vector GetAllActiveChrDraws() { - std::vector all_draws; - for (auto& [id, inst] : s_chrInstances) { - if (!inst.visible || !inst.body_model) continue; - float world[16]; - MakeTransformMatrix(inst.rot, inst.posX, inst.posY, inst.posZ, 1.0f, world); - auto draws = inst.body_model->BuildDrawCommands(inst.anim_time, world); - for (auto& d : draws) { - all_draws.push_back(std::move(d)); - } - } - return all_draws; -} - -void initchr() { - static PyMethodDef methods[] = { - {"DismountHorse", dummy_none, METH_VARARGS, nullptr}, - {"MountHorse", dummy_none, METH_VARARGS, nullptr}, - {"SetSash", dummy_none, METH_VARARGS, nullptr}, - {"Destroy", chr_destroy, METH_VARARGS, nullptr}, - {"Update", chr_update, METH_VARARGS, nullptr}, - {"Deform", chr_update, METH_VARARGS, nullptr}, - {"Render", dummy_none, METH_VARARGS, nullptr}, - {"RenderCollision", dummy_none, METH_VARARGS, nullptr}, - {"CreateInstance", chr_create_instance, METH_VARARGS, nullptr}, - {"DeleteInstance", chr_delete_instance, METH_VARARGS, nullptr}, - {"DeleteInstanceByFade", dummy_none, METH_VARARGS, nullptr}, - {"SelectInstance", chr_select_instance, METH_VARARGS, nullptr}, - {"HasInstance", chr_has_instance, METH_VARARGS, nullptr}, - {"IsEnemy", dummy_zero, METH_VARARGS, nullptr}, - {"IsNPC", dummy_zero, METH_VARARGS, nullptr}, - {"IsGameMaster", dummy_zero, METH_VARARGS, nullptr}, - {"IsPartyMember", dummy_zero, METH_VARARGS, nullptr}, - {"Select", dummy_none, METH_VARARGS, nullptr}, - {"SetAddRenderMode", dummy_none, METH_VARARGS, nullptr}, - {"SetBlendRenderMode", dummy_none, METH_VARARGS, nullptr}, - {"Unselect", dummy_none, METH_VARARGS, nullptr}, - {"Hide", chr_hide, METH_VARARGS, nullptr}, - {"Show", chr_show, METH_VARARGS, nullptr}, - {"Pick", dummy_none, METH_VARARGS, nullptr}, - {"PickAll", dummy_none, METH_VARARGS, nullptr}, - {"SetArmor", dummy_none, METH_VARARGS, nullptr}, - {"SetWeapon", chr_set_weapon, METH_VARARGS, nullptr}, - {"ChangeShape", chr_change_shape, METH_VARARGS, nullptr}, - {"SetRace", chr_set_race, METH_VARARGS, nullptr}, - {"SetHair", chr_set_hair, METH_VARARGS, nullptr}, - {"ChangeHair", chr_set_hair, METH_VARARGS, nullptr}, - {"SetVirtualID", dummy_none, METH_VARARGS, nullptr}, - {"SetNameString", chr_set_name_string, METH_VARARGS, nullptr}, - {"SetInstanceType", dummy_none, METH_VARARGS, nullptr}, - {"RequestPetName", dummy_none, METH_VARARGS, nullptr}, - {"SetPixelPosition", chr_set_pixel_position, METH_VARARGS, nullptr}, - {"SetDirection", dummy_none, METH_VARARGS, nullptr}, - {"Refresh", dummy_none, METH_VARARGS, nullptr}, - {"Revive", dummy_none, METH_VARARGS, nullptr}, - {"Die", dummy_none, METH_VARARGS, nullptr}, - {"AttachEffectByID", dummy_none, METH_VARARGS, nullptr}, - {"AttachEffectByName", dummy_none, METH_VARARGS, nullptr}, - {"LookAt", dummy_none, METH_VARARGS, nullptr}, - {"SetMotionMode", dummy_none, METH_VARARGS, nullptr}, - {"SetLoopMotion", dummy_none, METH_VARARGS, nullptr}, - {"BlendLoopMotion", dummy_none, METH_VARARGS, nullptr}, - {"PushOnceMotion", dummy_none, METH_VARARGS, nullptr}, - {"PushLoopMotion", dummy_none, METH_VARARGS, nullptr}, - {"GetPixelPosition", chr_get_pixel_position, METH_VARARGS, nullptr}, - {"SetRotation", chr_set_rotation, METH_VARARGS, nullptr}, - {"SetRotationAll", chr_set_rotation, METH_VARARGS, nullptr}, - {"BlendRotation", dummy_none, METH_VARARGS, nullptr}, - {"GetRotation", dummy_zero, METH_VARARGS, nullptr}, - {"GetRace", chr_get_race, METH_VARARGS, nullptr}, - {"GetName", chr_get_name, METH_VARARGS, nullptr}, - {"GetNameByVID", chr_get_name_by_vid, METH_VARARGS, nullptr}, - {"GetGuildID", dummy_zero, METH_VARARGS, nullptr}, - {"GetProjectPosition", dummy_tuple3, METH_VARARGS, nullptr}, - {"GetVirtualNumber", dummy_zero, METH_VARARGS, nullptr}, - {"GetInstanceType", dummy_zero, METH_VARARGS, nullptr}, - {"GetBoundBoxOnlyXY", dummy_zero, METH_VARARGS, nullptr}, - {"RaceToJob", dummy_none, METH_VARARGS, nullptr}, - {"RaceToSex", dummy_none, METH_VARARGS, nullptr}, - {"testGetPKData", dummy_none, METH_VARARGS, nullptr}, - {"FaintTest", dummy_none, METH_VARARGS, nullptr}, - {"SetMoveSpeed", dummy_none, METH_VARARGS, nullptr}, - {"SetAttackSpeed", dummy_none, METH_VARARGS, nullptr}, - {"WeaponTraceSetTexture", dummy_none, METH_VARARGS, nullptr}, - {"WeaponTraceUseAlpha", dummy_none, METH_VARARGS, nullptr}, - {"WeaponTraceUseTexture", dummy_none, METH_VARARGS, nullptr}, - {"MoveToDestPosition", dummy_none, METH_VARARGS, nullptr}, - {"testSetComboType", dummy_none, METH_VARARGS, nullptr}, - {"testSetAddRenderMode", dummy_none, METH_VARARGS, nullptr}, - {"testSetModulateRenderMode", dummy_none, METH_VARARGS, nullptr}, - {"testSetAddRenderModeRGB", dummy_none, METH_VARARGS, nullptr}, - {"testSetModulateRenderModeRGB", dummy_none, METH_VARARGS, nullptr}, - {"testSetSpecularRenderMode", dummy_none, METH_VARARGS, nullptr}, - {"testSetSpecularRenderMode2", dummy_none, METH_VARARGS, nullptr}, - {"testRestoreRenderMode", dummy_none, METH_VARARGS, nullptr}, - {"testSetRideMan", dummy_none, METH_VARARGS, nullptr}, - {"IsStone", dummy_zero, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("chr", methods); - - PyModule_AddIntConstant(module, "PLAYER_NAME_MAX_LEN", 12); - PyModule_AddIntConstant(module, "MOTION_NONE", 0); - PyModule_AddIntConstant(module, "MOTION_SPAWN", 25); - PyModule_AddIntConstant(module, "MOTION_WAIT", 1); - PyModule_AddIntConstant(module, "MOTION_WALK", 2); - PyModule_AddIntConstant(module, "MOTION_RUN", 3); - PyModule_AddIntConstant(module, "MOTION_CHANGE_WEAPON", 4); - PyModule_AddIntConstant(module, "MOTION_DAMAGE", 5); - PyModule_AddIntConstant(module, "MOTION_DAMAGE_FLYING", 6); - PyModule_AddIntConstant(module, "MOTION_STAND_UP", 7); - PyModule_AddIntConstant(module, "MOTION_DAMAGE_BACK", 8); - PyModule_AddIntConstant(module, "MOTION_DAMAGE_FLYING_BACK", 9); - PyModule_AddIntConstant(module, "MOTION_STAND_UP_BACK", 10); - PyModule_AddIntConstant(module, "MOTION_DEAD", 11); - PyModule_AddIntConstant(module, "MOTION_DEAD_BACK", 12); - PyModule_AddIntConstant(module, "MOTION_NORMAL_ATTACK", 13); - PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_1", 14); - PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_2", 15); - PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_3", 16); - PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_4", 17); - PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_5", 18); - PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_6", 19); - PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_7", 20); - PyModule_AddIntConstant(module, "MOTION_COMBO_ATTACK_8", 21); - PyModule_AddIntConstant(module, "MOTION_INTRO_WAIT", 22); - PyModule_AddIntConstant(module, "MOTION_INTRO_SELECTED", 23); - PyModule_AddIntConstant(module, "MOTION_INTRO_NOT_SELECTED", 24); - PyModule_AddIntConstant(module, "MOTION_FISHING_THROW", 26); - PyModule_AddIntConstant(module, "MOTION_FISHING_WAIT", 27); - PyModule_AddIntConstant(module, "MOTION_FISHING_STOP", 28); - PyModule_AddIntConstant(module, "MOTION_FISHING_REACT", 29); - PyModule_AddIntConstant(module, "MOTION_FISHING_CATCH", 30); - PyModule_AddIntConstant(module, "MOTION_FISHING_FAIL", 31); - PyModule_AddIntConstant(module, "MOTION_STOP", 32); - PyModule_AddIntConstant(module, "MOTION_SKILL", 50); - PyModule_AddIntConstant(module, "MOTION_CLAP", 306); - PyModule_AddIntConstant(module, "MOTION_DANCE_1", 326); - PyModule_AddIntConstant(module, "MOTION_DANCE_2", 327); - PyModule_AddIntConstant(module, "MOTION_DANCE_3", 328); - PyModule_AddIntConstant(module, "MOTION_DANCE_4", 329); - PyModule_AddIntConstant(module, "MOTION_DANCE_5", 330); - PyModule_AddIntConstant(module, "MOTION_DANCE_6", 331); - PyModule_AddIntConstant(module, "MOTION_CONGRATULATION", 343); - PyModule_AddIntConstant(module, "MOTION_FORGIVE", 344); - PyModule_AddIntConstant(module, "MOTION_ANGRY", 345); - PyModule_AddIntConstant(module, "MOTION_ATTRACTIVE", 346); - PyModule_AddIntConstant(module, "MOTION_SAD", 347); - PyModule_AddIntConstant(module, "MOTION_SHY", 348); - PyModule_AddIntConstant(module, "MOTION_CHEERUP", 349); - PyModule_AddIntConstant(module, "MOTION_BANTER", 350); - PyModule_AddIntConstant(module, "MOTION_JOY", 351); - PyModule_AddIntConstant(module, "MOTION_CHEERS_1", 307); - PyModule_AddIntConstant(module, "MOTION_CHEERS_2", 308); - PyModule_AddIntConstant(module, "MOTION_KISS_WITH_WARRIOR", 309); - PyModule_AddIntConstant(module, "MOTION_KISS_WITH_ASSASSIN", 310); - PyModule_AddIntConstant(module, "MOTION_KISS_WITH_SURA", 311); - PyModule_AddIntConstant(module, "MOTION_KISS_WITH_SHAMAN", 312); - PyModule_AddIntConstant(module, "MOTION_FRENCH_KISS_WITH_WARRIOR", 313); - PyModule_AddIntConstant(module, "MOTION_FRENCH_KISS_WITH_ASSASSIN", 314); - PyModule_AddIntConstant(module, "MOTION_FRENCH_KISS_WITH_SURA", 315); - PyModule_AddIntConstant(module, "MOTION_FRENCH_KISS_WITH_SHAMAN", 316); - PyModule_AddIntConstant(module, "MOTION_SLAP_HIT_WITH_WARRIOR", 317); - PyModule_AddIntConstant(module, "MOTION_SLAP_HIT_WITH_ASSASSIN", 318); - PyModule_AddIntConstant(module, "MOTION_SLAP_HIT_WITH_SURA", 319); - PyModule_AddIntConstant(module, "MOTION_SLAP_HIT_WITH_SHAMAN", 320); - PyModule_AddIntConstant(module, "MOTION_SLAP_HURT_WITH_WARRIOR", 321); - PyModule_AddIntConstant(module, "MOTION_SLAP_HURT_WITH_ASSASSIN", 322); - PyModule_AddIntConstant(module, "MOTION_SLAP_HURT_WITH_SURA", 323); - PyModule_AddIntConstant(module, "MOTION_SLAP_HURT_WITH_SHAMAN", 324); - PyModule_AddIntConstant(module, "MOTION_DIG", 325); - PyModule_AddIntConstant(module, "MOTION_MODE_RESERVED", 0); - PyModule_AddIntConstant(module, "MOTION_MODE_GENERAL", 1); - PyModule_AddIntConstant(module, "MOTION_MODE_ONEHAND_SWORD", 2); - PyModule_AddIntConstant(module, "MOTION_MODE_TWOHAND_SWORD", 3); - PyModule_AddIntConstant(module, "MOTION_MODE_DUALHAND_SWORD", 4); - PyModule_AddIntConstant(module, "MOTION_MODE_BOW", 5); - PyModule_AddIntConstant(module, "MOTION_MODE_FAN", 6); - PyModule_AddIntConstant(module, "MOTION_MODE_BELL", 7); - PyModule_AddIntConstant(module, "MOTION_MODE_FISHING", 8); - PyModule_AddIntConstant(module, "MOTION_MODE_HORSE", 9); - PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_ONEHAND_SWORD", 10); - PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_TWOHAND_SWORD", 11); - PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_DUALHAND_SWORD", 12); - PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_BOW", 13); - PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_FAN", 14); - PyModule_AddIntConstant(module, "MOTION_MODE_HORSE_BELL", 15); - PyModule_AddIntConstant(module, "MOTION_MODE_WEDDING_DRESS", 16); - PyModule_AddIntConstant(module, "MOTION_MODE_CLAW", 17); - PyModule_AddIntConstant(module, "MOTION_MODE_BOW_SPECIAL", 18); - PyModule_AddIntConstant(module, "DIR_NORTH", 0); - PyModule_AddIntConstant(module, "DIR_NORTHEAST", 1); - PyModule_AddIntConstant(module, "DIR_EAST", 2); - PyModule_AddIntConstant(module, "DIR_SOUTHEAST", 3); - PyModule_AddIntConstant(module, "DIR_SOUTH", 4); - PyModule_AddIntConstant(module, "DIR_SOUTHWEST", 5); - PyModule_AddIntConstant(module, "DIR_WEST", 6); - PyModule_AddIntConstant(module, "DIR_NORTHWEST", 7); - PyModule_AddIntConstant(module, "INSTANCE_TYPE_PLAYER", 6); - PyModule_AddIntConstant(module, "INSTANCE_TYPE_NPC", 1); - PyModule_AddIntConstant(module, "INSTANCE_TYPE_ENEMY", 0); - PyModule_AddIntConstant(module, "INSTANCE_TYPE_BUILDING", 5); - PyModule_AddIntConstant(module, "INSTANCE_TYPE_OBJECT", 11); - PyModule_AddIntConstant(module, "PART_WEAPON", 1); - PyModule_AddIntConstant(module, "PART_HEAD", 2); - PyModule_AddIntConstant(module, "PART_WEAPON_LEFT", 3); - PyModule_AddIntConstant(module, "PART_SASH", 5); - PyModule_AddIntConstant(module, "AFFECT_POISON", 3); - PyModule_AddIntConstant(module, "AFFECT_SLOW", 4); - PyModule_AddIntConstant(module, "AFFECT_STUN", 5); - PyModule_AddIntConstant(module, "AFFECT_MOV_SPEED_POTION", 11); - PyModule_AddIntConstant(module, "AFFECT_ATT_SPEED_POTION", 12); - PyModule_AddIntConstant(module, "AFFECT_FISH_MIND", 13); - PyModule_AddIntConstant(module, "AFFECT_JEONGWI", 14); - PyModule_AddIntConstant(module, "AFFECT_GEOMGYEONG", 15); - PyModule_AddIntConstant(module, "AFFECT_CHEONGEUN", 16); - PyModule_AddIntConstant(module, "AFFECT_GYEONGGONG", 17); - PyModule_AddIntConstant(module, "AFFECT_EUNHYEONG", 18); - PyModule_AddIntConstant(module, "AFFECT_GWIGEOM", 19); - PyModule_AddIntConstant(module, "AFFECT_GONGPO", 20); - PyModule_AddIntConstant(module, "AFFECT_JUMAGAP", 21); - PyModule_AddIntConstant(module, "AFFECT_HOSIN", 22); - PyModule_AddIntConstant(module, "AFFECT_BOHO", 23); - PyModule_AddIntConstant(module, "AFFECT_KWAESOK", 24); - PyModule_AddIntConstant(module, "AFFECT_HEUKSIN", 25); - PyModule_AddIntConstant(module, "AFFECT_MUYEONG", 26); - PyModule_AddIntConstant(module, "AFFECT_GICHEON", 29); - PyModule_AddIntConstant(module, "AFFECT_JEUNGRYEOK", 30); - PyModule_AddIntConstant(module, "AFFECT_PABEOP", 32); - PyModule_AddIntConstant(module, "AFFECT_FALLEN_CHEONGEUN", 33); - PyModule_AddIntConstant(module, "AFFECT_CHINA_FIREWORK", 38); - PyModule_AddIntConstant(module, "AFFECT_BLEEDING", 42); - PyModule_AddIntConstant(module, "AFFECT_RED_POSSESSION", 43); - PyModule_AddIntConstant(module, "AFFECT_BLUE_POSSESSION", 44); - PyModule_AddIntConstant(module, "AFFECT_CHEONUN", 46); - PyModule_AddIntConstant(module, "NEW_AFFECT_MULTI_FARM", 704); - PyModule_AddIntConstant(module, "NEW_AFFECT_AUTO_PICK_UP", 705); - PyModule_AddIntConstant(module, "NEW_AFFECT_VOTE4BUFF", 809); - PyModule_AddIntConstant(module, "NEW_AFFECT_MALL", 510); - PyModule_AddIntConstant(module, "NEW_AFFECT_NO_DEATH_PENALTY", 511); - PyModule_AddIntConstant(module, "NEW_AFFECT_SKILL_BOOK_BONUS", 512); - PyModule_AddIntConstant(module, "NEW_AFFECT_SKILL_BOOK_NO_DELAY", 513); - PyModule_AddIntConstant(module, "NEW_AFFECT_EXP_BONUS", 500); - PyModule_AddIntConstant(module, "NEW_AFFECT_EXP_BONUS_EURO_FREE", 516); - PyModule_AddIntConstant(module, "NEW_AFFECT_EXP_BONUS_EURO_FREE_UNDER_15", 517); - PyModule_AddIntConstant(module, "NEW_AFFECT_ITEM_BONUS", 501); - PyModule_AddIntConstant(module, "NEW_AFFECT_SAFEBOX", 502); - PyModule_AddIntConstant(module, "NEW_AFFECT_AUTOLOOT", 503); - PyModule_AddIntConstant(module, "NEW_AFFECT_FISH_MIND", 504); - PyModule_AddIntConstant(module, "NEW_AFFECT_MARRIAGE_FAST", 505); - PyModule_AddIntConstant(module, "NEW_AFFECT_GOLD_BONUS", 506); - PyModule_AddIntConstant(module, "NEW_AFFECT_AUTO_HP_RECOVERY", 534); - PyModule_AddIntConstant(module, "NEW_AFFECT_AUTO_SP_RECOVERY", 535); - PyModule_AddIntConstant(module, "AFFECT_AUTO_ATTACK_SPEED_RECOVERY", 850); - PyModule_AddIntConstant(module, "AFFECT_AUTO_MOV_SPEED_RECOVERY", 851); - PyModule_AddIntConstant(module, "AFFECT_AUTO_CRITICAL_RECOVERY", 852); - PyModule_AddIntConstant(module, "AFFECT_AUTO_PENETRATE_RECOVERY", 853); - PyModule_AddIntConstant(module, "AFFECT_AUTO_VIT_RECOVERY", 854); - PyModule_AddIntConstant(module, "AFFECT_AUTO_STR_RECOVERY", 855); - PyModule_AddIntConstant(module, "AFFECT_AUTO_INT_RECOVERY", 856); - PyModule_AddIntConstant(module, "AFFECT_AUTO_DEX_RECOVERY", 857); - PyModule_AddIntConstant(module, "AFFECT_AUTO_RED_POTION_RECOVERY", 858); - PyModule_AddIntConstant(module, "AFFECT_AUTO_ORANGE_POTION_RECOVERY", 859); - PyModule_AddIntConstant(module, "AFFECT_AUTO_YELLOW_POTION_RECOVERY", 860); - PyModule_AddIntConstant(module, "AFFECT_AUTO_GREEN_POTION_RECOVERY", 861); - PyModule_AddIntConstant(module, "AFFECT_AUTO_BLUE_POTION_RECOVERY", 862); - PyModule_AddIntConstant(module, "AFFECT_AUTO_WHITE_POTION_RECOVERY", 863); - PyModule_AddIntConstant(module, "NEW_AFFECT_DRAGON_SOUL_QUALIFIED", 540); - PyModule_AddIntConstant(module, "NEW_AFFECT_DRAGON_SOUL_DECK1", 541); - PyModule_AddIntConstant(module, "NEW_AFFECT_DRAGON_SOUL_DECK2", 542); - PyModule_AddIntConstant(module, "AFFECT_POTION_1", 303); - PyModule_AddIntConstant(module, "AFFECT_POTION_2", 304); - PyModule_AddIntConstant(module, "AFFECT_POTION_3", 305); - PyModule_AddIntConstant(module, "AFFECT_POTION_4", 306); - PyModule_AddIntConstant(module, "AFFECT_POTION_5", 307); - PyModule_AddIntConstant(module, "AFFECT_POTION_6", 308); - PyModule_AddIntConstant(module, "NEW_AFFECT_DECORATION", 703); - PyModule_AddIntConstant(module, "AFFECT_STATUE1", 48); - PyModule_AddIntConstant(module, "AFFECT_STATUE2", 49); - PyModule_AddIntConstant(module, "AFFECT_STATUE3", 50); - PyModule_AddIntConstant(module, "AFFECT_STATUE4", 51); -} - -void initChat() { - static PyMethodDef methods[] = { - {"SetChatColor", dummy_none, METH_VARARGS, nullptr}, - {"Clear", dummy_none, METH_VARARGS, nullptr}, - {"Close", dummy_none, METH_VARARGS, nullptr}, - {"CreateChatSet", dummy_none, METH_VARARGS, nullptr}, - {"Update", dummy_none, METH_VARARGS, nullptr}, - {"Render", dummy_none, METH_VARARGS, nullptr}, - {"SetBoardState", dummy_none, METH_VARARGS, nullptr}, - {"SetPosition", dummy_none, METH_VARARGS, nullptr}, - {"SetHeight", dummy_none, METH_VARARGS, nullptr}, - {"SetStep", dummy_none, METH_VARARGS, nullptr}, - {"ToggleChatMode", dummy_none, METH_VARARGS, nullptr}, - {"EnableChatMode", dummy_none, METH_VARARGS, nullptr}, - {"DisableChatMode", dummy_none, METH_VARARGS, nullptr}, - {"SetEndPos", dummy_none, METH_VARARGS, nullptr}, - {"GetLineCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetVisibleLineCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetLineStep", dummy_zero, METH_VARARGS, nullptr}, - {"AppendChat", dummy_none, METH_VARARGS, nullptr}, - {"AppendChatWithDelay", dummy_none, METH_VARARGS, nullptr}, - {"ArrangeShowingChat", dummy_none, METH_VARARGS, nullptr}, - {"IgnoreCharacter", dummy_none, METH_VARARGS, nullptr}, - {"IsIgnoreCharacter", dummy_zero, METH_VARARGS, nullptr}, - {"CreateWhisper", dummy_none, METH_VARARGS, nullptr}, - {"AppendWhisper", dummy_none, METH_VARARGS, nullptr}, - {"RenderWhisper", dummy_none, METH_VARARGS, nullptr}, - {"SetWhisperBoxSize", dummy_none, METH_VARARGS, nullptr}, - {"SetWhisperPosition", dummy_none, METH_VARARGS, nullptr}, - {"ClearWhisper", dummy_none, METH_VARARGS, nullptr}, - {"InitWhisper", dummy_none, METH_VARARGS, nullptr}, - {"GetLinkFromHyperlink", dummy_zero, METH_VARARGS, nullptr}, - {"DeleteChatSet", dummy_none, METH_VARARGS, nullptr}, - {"EnableCountryMode", dummy_none, METH_VARARGS, nullptr}, - {"DisableCountryMode", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("chat", methods); - - PyModule_AddIntConstant(module, "CHAT_TYPE_TALKING", 0); - PyModule_AddIntConstant(module, "CHAT_TYPE_INFO", 1); - PyModule_AddIntConstant(module, "CHAT_TYPE_NOTICE", 2); - PyModule_AddIntConstant(module, "CHAT_TYPE_PARTY", 3); - PyModule_AddIntConstant(module, "CHAT_TYPE_GUILD", 4); - PyModule_AddIntConstant(module, "CHAT_TYPE_COMMAND", 5); - PyModule_AddIntConstant(module, "CHAT_TYPE_SHOUT", 6); - PyModule_AddIntConstant(module, "CHAT_TYPE_WHISPER", 7); - PyModule_AddIntConstant(module, "CHAT_TYPE_BIG_NOTICE", 8); - PyModule_AddIntConstant(module, "CHAT_TYPE_MONARCH_NOTICE", 9); - PyModule_AddIntConstant(module, "CHAT_TYPE_DICE_INFO", 10); - PyModule_AddIntConstant(module, "CHAT_TYPE_EXP_INFO", 11); - PyModule_AddIntConstant(module, "CHAT_TYPE_ITEM_INFO", 12); - PyModule_AddIntConstant(module, "CHAT_TYPE_MONEY_INFO", 13); - PyModule_AddIntConstant(module, "CHAT_TYPE_MISSION", 14); - PyModule_AddIntConstant(module, "WHISPER_TYPE_CHAT", 0); - PyModule_AddIntConstant(module, "WHISPER_TYPE_SYSTEM", 255); - PyModule_AddIntConstant(module, "WHISPER_TYPE_GM", 5); - PyModule_AddIntConstant(module, "BOARD_STATE_VIEW", 0); - PyModule_AddIntConstant(module, "BOARD_STATE_EDIT", 1); - PyModule_AddIntConstant(module, "BOARD_STATE_LOG", 2); - PyModule_AddIntConstant(module, "CHAT_SET_CHAT_WINDOW", 0); - PyModule_AddIntConstant(module, "CHAT_SET_LOG_WINDOW", 1); -} +// initChat: src/python_chat.cpp (CPythonChat / CWhisper port). static PyObject* snd_PlaySound(PyObject*, PyObject* args) { char* filename = nullptr; @@ -3004,6 +2426,25 @@ static void loadAtlas() { void GlobalToLocalPosition(int32_t& x,int32_t& y) { s_mapCoordinates.toLocal(x,y); } void LocalToGlobalPosition(int32_t& x,int32_t& y) { s_mapCoordinates.toGlobal(x,y); } static std::string s_currentMapName = ""; +static OutdoorMapInfo s_outdoorMap; +const OutdoorMapInfo* GetOutdoorMap() { return s_currentMapName.empty()?nullptr:&s_outdoorMap; } +// CMapOutdoor::LoadSetting: SetTerrainCount(atoi mapsize[0..1]) and the optional SetBaseXY((DWORD)atol +// baseposition[0..1]). The other required keys only feed terrain rendering and are not checked here. +static OutdoorMapInfo LoadOutdoorSetting(const std::string& mapName,const std::string& path) { + OutdoorMapInfo info; info.name=mapName; + std::ifstream f(path,std::ios::binary); if(!f) return info; + std::stringstream ss; ss<> tokens; ava2LoadMultipleTextData(ss.str(),tokens); + auto size=tokens.find("mapsize"); + if(size!=tokens.end() && size->second.size()>=2) { + info.terrainCountX=int16_t(std::atoi(size->second[0].c_str())); info.terrainCountY=int16_t(std::atoi(size->second[1].c_str())); + } + auto base=tokens.find("baseposition"); + if(base!=tokens.end() && base->second.size()>=2) { + info.baseX=uint32_t(std::atol(base->second[0].c_str())); info.baseY=uint32_t(std::atol(base->second[1].c_str())); + } + return info; +} static std::unique_ptr s_backgroundTerrain; static float s_pickingPoint[3] = {0.0f, 0.0f, 0.0f}; @@ -3073,19 +2514,21 @@ bool LoadBackgroundMap(const std::string& mapName, float x, float y, float z) { s_backgroundTerrain->LoadTextureSet(textureset_path); } - if(ok) s_currentMapName=mapName; + if(ok) { s_currentMapName=mapName; s_outdoorMap=LoadOutdoorSetting(mapName,found_base+"/setting.txt"); } return ok; } bool WarpBackgroundMap(uint32_t x,uint32_t y) { // NetworkStream::Warp destroys/recreates background before selecting the map. - s_backgroundTerrain.reset(); s_currentMapName.clear(); + s_backgroundTerrain.reset(); s_currentMapName.clear(); s_warpMapName.clear(); s_mapCoordinates.baseX=0; s_mapCoordinates.baseY=0; loadAtlas(); const auto* map=s_mapCoordinates.find(x,y); if(!map) return false; if(!LoadBackgroundMap(map->name,float(x-map->x),float(y-map->y),0)) throw std::runtime_error("AVA2 map load failed: "+map->name); + CPythonMiniMap::Instance().LoadAtlas(); s_mapCoordinates.baseX=map->x; s_mapCoordinates.baseY=map->y; + s_warpMapName=map->name; return true; } static PyObject* background_GlobalPositionToLocalPosition(PyObject*,PyObject* args) { @@ -3118,7 +2561,7 @@ static PyObject* background_LoadMap(PyObject*, PyObject* args) { static PyObject* background_Destroy(PyObject*, PyObject*) { s_backgroundTerrain.reset(); - s_currentMapName.clear(); + s_currentMapName.clear(); s_warpMapName.clear(); s_mapCoordinates.baseX=0; s_mapCoordinates.baseY=0; Py_RETURN_NONE; } diff --git a/src/python_gameplay_modules.h b/src/python_gameplay_modules.h index 04a3b82f..c79b4f84 100644 --- a/src/python_gameplay_modules.h +++ b/src/python_gameplay_modules.h @@ -3,13 +3,13 @@ #include "eter_net/Packet.h" #include #include +#include namespace ava2 { void initItem(); void initPlayer(); void initchrmgr(); void initchr(); -void initChat(); void initsnd(); void initBackground(); void GlobalToLocalPosition(int32_t& x,int32_t& y); @@ -31,6 +31,30 @@ struct PlayerItemSlot { PlayerItemSlot GetPlayerItem(int slot); void SetPlayerItem(int slot, uint32_t vnum, int count); void ResetPlayerState(); +void AppendPartyMember(uint32_t pid,const std::string& name); +void LinkPartyMember(uint32_t pid,uint32_t vid); +void UnlinkPartyMember(uint32_t pid); +void UpdatePartyMemberInfo(uint32_t pid,uint8_t state,uint8_t hp); +void UpdatePartyMemberAffect(uint32_t pid,uint8_t slot,int16_t affect); +bool GetPartyMemberState(uint32_t pid,uint8_t* state); +bool PartyMemberPIDToVID(uint32_t pid,uint32_t* vid); +bool IsPartyMemberByVID(uint32_t vid); +void RememberChallengeInstance(uint32_t vid); +void RememberRevengeInstance(uint32_t vid); +void RememberCantFightInstance(uint32_t vid); +void ForgetInstance(uint32_t vid); +void SetKillLOG(const int32_t* log); +void NEW_ClearSkillData(bool all); +void ResetItemDatabase(); +bool LoadItemList(const std::string& path); +bool LoadItemDescriptions(const std::string& path); +bool LoadItemTable(const std::string& path); +struct ItemScaleInfo { float scaleX=0,scaleY=0,scaleZ=0,positionX=0,positionY=0,positionZ=0; }; +bool LoadItemScale(const std::string& path); +bool GetItemScale(uint32_t vnum,uint32_t pos,ItemScaleInfo* out); +bool GetItemNameAndType(uint32_t vnum,std::string* name,int* type); +bool IsPlayerEquipmentItem(uint8_t window,uint16_t cell); +bool GetItemTypeAndSubType(uint32_t vnum,int* type,int* subType); void ClearPlayerPythonWindow(); void SetPlayerSkill(int slot,int index); void SetPlayerSkillLevel(int index,int grade,int level); @@ -38,6 +62,7 @@ void SetPlayerLegacySkillLevel(int index,int level); void AddPlayerQuickSlot(int index,uint8_t type,uint8_t pos); void DeletePlayerQuickSlot(int index); void SwapPlayerQuickSlots(int source,int target); +void SetPlayerItemCount(uint8_t window,uint16_t cell,uint32_t count); void SetPlayerItemData(uint8_t window, uint16_t cell, const TItemData& data); TItemData GetPlayerItemData(uint8_t window, uint16_t cell); bool UsePlayerItem(int window, int slot, std::string& outEquippedWeaponModel, std::string& outActionMessage); @@ -47,6 +72,7 @@ std::string GetWeaponModelPathByVnum(uint32_t vnum); std::vector GetAllActiveChrDraws(); void SetMainCharacterPosition(float x, float y, float z); +const std::string& GetMainCharacterName(); void SetMainCharacterName(const std::string& name); long long GetPlayerStatusPoint(int type); void SetPlayerStatusPoint(int type, long long value); @@ -55,5 +81,9 @@ class TerrainHeightmap; TerrainHeightmap* GetActiveBackgroundTerrain(); void SetActiveBackgroundTerrain(std::unique_ptr terrain); bool LoadBackgroundMap(const std::string& mapName, float x = 0.0f, float y = 0.0f, float z = 0.0f); +// CPythonBackground::IsMapOutdoor + CMapOutdoor GetName/GetBaseXY/GetTerrainCount for the loaded map +// (setting.txt "mapsize" / "baseposition"); nullptr while no map is loaded. +struct OutdoorMapInfo { std::string name; uint32_t baseX=0, baseY=0; int16_t terrainCountX=0, terrainCountY=0; }; +const OutdoorMapInfo* GetOutdoorMap(); } // namespace ava2 diff --git a/src/python_guild.cpp b/src/python_guild.cpp new file mode 100644 index 00000000..a33270ce --- /dev/null +++ b/src/python_guild.cpp @@ -0,0 +1,109 @@ +// Direct port of AVA2 UserInterface/PythonGuild.cpp. Python int results preserve +// signed Win32 DWORD conversion, including sentinel -1 and EXP subtraction wrap. +#include "guild_state.h" +#include "python_native_modules.h" +#include "python_gameplay_modules.h" +#include "shared/common/PythonUtils.h" +#include "eter_net/Packet.h" +#include "eter_image/MarkManager.h" +#include +namespace ava2 { +GuildState& GetGuildState() { static GuildState state;return state; } +GuildState::Member* GuildState::ByPID(uint32_t pid) { + auto it=std::find_if(members.begin(),members.end(),[pid](const Member& m){return m.pid==pid;}); + return it==members.end()?nullptr:&*it; +} +GuildState::Member* GuildState::ByName(const std::string& name) { + auto it=std::find_if(members.begin(),members.end(),[&name](const Member& m){return m.name==name;}); + return it==members.end()?nullptr:&*it; +} +void GuildState::RegisterMember(const Member& value) { + if(auto* m=ByPID(value.pid)) { m->general=value.general;m->grade=value.grade;m->level=value.level;m->offer=value.offer; } + else members.push_back(value); + levelSum=levelAverage=offerSum=0; + for(const auto& m:members) { levelSum+=m.level;offerSum+=m.offer; } + if(!members.empty())levelAverage=levelSum/members.size(); + std::sort(members.begin(),members.end(),[](const Member& a,const Member& b){return a.gradesecond.c_str()); +} +PyObject* master_name(PyObject*,PyObject*) {auto* m=g().ByPID(g().info.master);return PyString_FromString(m?m->name.c_str():"Noname");} +PyObject* enemy_name(PyObject*,PyObject* args) { + int slot;if(!index(args,slot))return PyString_FromString(""); + auto it=g().names.find(uint32_t(slot)second.c_str()); +} +PyObject* experience(PyObject*,PyObject*) { + // Locale.cpp INTERNATIONAL_GUILDEXP_LIST; AVA2's active service is EUROPE. + static constexpr uint32_t exp[]={0,6000,18000,36000,64000,94000,130000,172000,220000,274000,334000,400000,600000,840000,1120000,1440000,1800000,2600000,3200000,4000000}; + if(g().info.level>=20)return Py_BuildValue("ii",0,0); + return Py_BuildValue("ii",int32_t(g().info.exp),int32_t(exp[g().info.level]-g().info.exp)); +} +PyObject* member_count(PyObject*,PyObject*) {return Py_BuildValue("ii",int32_t(g().info.count),int32_t(g().info.maxCount));} +PyObject* power(PyObject*,PyObject*) {return Py_BuildValue("ii",int(g().skill.power),int(g().skill.maxPower));} +PyObject* comment(PyObject*,PyObject* args) { + int i;if(!index(args,i))return Py_BuildException(); + if(uint32_t(i)>=g().comments.size())return Py_BuildValue("iss",0,"Noname","Noname"); + const auto& c=g().comments[i];return Py_BuildValue("iss",int32_t(c.id),c.name.c_str(),c.text.c_str()); +} +PyObject* member(PyObject*,PyObject* args) { + int i;if(!index(args,i))return Py_BuildException(); + if(uint32_t(i)>=g().members.size())return Py_BuildValue("isiiiii",-1,"",0,0,0,0,0); + const auto& m=g().members[i];return Py_BuildValue("isiiiii",int32_t(m.pid),m.name.c_str(),int(m.grade),int(m.job),int(m.level),int32_t(m.offer),int(m.general)); +} +PyObject* member_pid(PyObject*,PyObject* args) {int i;if(!index(args,i))return Py_BuildException();return number(uint32_t(i)second.name.c_str(),int(it->second.authority));} +PyObject* grade_name(PyObject*,PyObject* args) {int i;if(!index(args,i))return Py_BuildException();auto it=g().grades.find(uint32_t(i));return PyString_FromString(it==g().grades.end()?"?":it->second.name.c_str());} +PyObject* authority(PyObject*,PyObject* args) { + int mask;if(!index(args,mask))return Py_BuildException();auto* m=g().ByName(GetMainCharacterName());if(!m)return number(0); + auto it=g().grades.find(m->grade);return number(it!=g().grades.end() && mask==(it->second.authority&mask)); +} +PyObject* set_skill(PyObject*,PyObject* args) {int slot,i;if(!index(args,slot)||!PyTuple_GetInteger(args,1,&i))return Py_BuildException();g().skillSlots.insert({uint32_t(slot),uint32_t(i)});Py_RETURN_NONE;} +PyObject* skill_index(PyObject*,PyObject* args) {int slot;if(!index(args,slot))return Py_BuildException();auto it=g().skillSlots.find(uint32_t(slot));return number(it==g().skillSlots.end()?0:it->second);} +PyObject* skill_level(PyObject*,PyObject* args) {int slot;if(!index(args,slot))return Py_BuildException();auto it=g().skillSlots.find(uint32_t(slot));return number(it!=g().skillSlots.end() && it->second<12?g().skill.levels[it->second]:0);} +PyObject* raw_skill_level(PyObject*,PyObject* args) {int i;if(!index(args,i))return Py_BuildException();return number(uint32_t(i)<12?g().skill.levels[i]:0);} +PyObject* destroy(PyObject*,PyObject*) {g().Destroy();g().skillSlots.clear();Py_RETURN_NONE;} +PyObject* mark_id(PyObject*,PyObject* args) {int i;if(!index(args,i))return Py_BuildException();return number(GuildMarkManager::Instance().GetMarkID(uint32_t(i)));} +PyObject* mark_file(PyObject*,PyObject* args) {int i;if(!index(args,i))return Py_BuildException();std::string path;GuildMarkManager::Instance().GetMarkImageFilename(i/int(GuildMarkImage::MARK_TOTAL_COUNT),path);return PyString_FromString(path.c_str());} +PyObject* mark_index(PyObject*,PyObject* args) {int i;if(!index(args,i))return Py_BuildException();return PyInt_FromLong(i%int(GuildMarkImage::MARK_TOTAL_COUNT));} +} +void initguild() { + static PyMethodDef methods[]={ + {"IsGuildEnable",enabled,METH_VARARGS,nullptr},{"GuildIDToMarkID",mark_id,METH_VARARGS,nullptr},{"GetMarkImageFilenameByMarkID",mark_file,METH_VARARGS,nullptr},{"GetMarkIndexByMarkID",mark_index,METH_VARARGS,nullptr}, + {"GetGuildID",id,METH_VARARGS,nullptr},{"HasGuildLand",land,METH_VARARGS,nullptr},{"GetGuildName",guild_name,METH_VARARGS,nullptr},{"GetGuildMasterName",master_name,METH_VARARGS,nullptr},{"GetEnemyGuildName",enemy_name,METH_VARARGS,nullptr}, + {"GetGuildMoney",money,METH_VARARGS,nullptr},{"GetGuildBoardCommentCount",comment_count,METH_VARARGS,nullptr},{"GetGuildBoardCommentData",comment,METH_VARARGS,nullptr},{"GetGuildLevel",level,METH_VARARGS,nullptr},{"GetGuildExperience",experience,METH_VARARGS,nullptr}, + {"GetGuildMemberCount",member_count,METH_VARARGS,nullptr},{"GetGuildMemberLevelSummary",level_sum,METH_VARARGS,nullptr},{"GetGuildMemberLevelAverage",level_average,METH_VARARGS,nullptr},{"GetGuildExperienceSummary",offer_sum,METH_VARARGS,nullptr}, + {"GetGuildSkillPoint",skill_points,METH_VARARGS,nullptr},{"GetDragonPowerPoint",power,METH_VARARGS,nullptr},{"GetGuildSkillLevel",raw_skill_level,METH_VARARGS,nullptr},{"GetSkillLevel",skill_level,METH_VARARGS,nullptr},{"GetSkillMaxLevelNew",skill_level,METH_VARARGS,nullptr}, + {"SetSkillIndex",set_skill,METH_VARARGS,nullptr},{"GetSkillIndex",skill_index,METH_VARARGS,nullptr},{"GetGradeData",grade,METH_VARARGS,nullptr},{"GetGradeName",grade_name,METH_VARARGS,nullptr},{"GetMemberCount",count,METH_VARARGS,nullptr},{"GetMemberData",member,METH_VARARGS,nullptr}, + {"MemberIndexToPID",member_pid,METH_VARARGS,nullptr},{"IsMember",is_member,METH_VARARGS,nullptr},{"IsMemberByName",is_name,METH_VARARGS,nullptr},{"MainPlayerHasAuthority",authority,METH_VARARGS,nullptr},{"Destroy",destroy,METH_VARARGS,nullptr}, + {nullptr,nullptr,0,nullptr}}; + auto* module=Py_InitModule("guild",methods); + PyModule_AddIntConstant(module,"AUTH_ADD_MEMBER",GUILD_AUTH_ADD_MEMBER);PyModule_AddIntConstant(module,"AUTH_REMOVE_MEMBER",GUILD_AUTH_REMOVE_MEMBER); + PyModule_AddIntConstant(module,"AUTH_NOTICE",GUILD_AUTH_NOTICE);PyModule_AddIntConstant(module,"AUTH_SKILL",GUILD_AUTH_SKILL); + PyModule_AddIntConstant(module,"ENEMY_GUILD_SLOT_MAX_COUNT",6); +} +} diff --git a/src/python_messenger.cpp b/src/python_messenger.cpp new file mode 100644 index 00000000..787d54d6 --- /dev/null +++ b/src/python_messenger.cpp @@ -0,0 +1,68 @@ +// Direct port of AVA2 UserInterface/PythonMessenger.cpp. Retain list membership +// on logout; do not invent separate mobile/online getters absent from Windows. +#include "messenger_state.h" +#include "python_native_modules.h" +#include "shared/common/PythonUtils.h" +namespace ava2 { +MessengerState& GetMessengerState() { static MessengerState state;return state; } +void MessengerState::SetHandler(PyObject* value) { + Py_XINCREF(value);auto* old=handler;handler=value;Py_XDECREF(old); +} +void MessengerState::Destroy() { friends.clear();guild.clear(); } +void MessengerState::Reset() { Destroy();SetHandler(nullptr); } +void MessengerState::RemoveFriend(const std::string& name) { friends.erase(name); } +bool MessengerState::IsFriend(const std::string& name) const { return friends.count(name)!=0; } +void MessengerState::FriendLogin(const std::string& name) { + friends.insert(name);PyCallClassMemberFunc(handler,"OnLogin",Py_BuildValue("(is)",0,name.c_str())); +} +void MessengerState::FriendLogout(const std::string& name) { + friends.insert(name);PyCallClassMemberFunc(handler,"OnLogout",Py_BuildValue("(is)",0,name.c_str())); +} +void MessengerState::SetMobile(const std::string& name,uint8_t state) { + friends.insert(name);PyCallClassMemberFunc(handler,"OnMobile",Py_BuildValue("(isi)",0,name.c_str(),int(state))); +} +void MessengerState::AppendGuildMember(const std::string& name) { + if(!guild.count(name))LogoutGuildMember(name); +} +void MessengerState::RemoveGuildMember(const std::string& name) { + guild.erase(name);PyCallClassMemberFunc(handler,"OnRemoveList",Py_BuildValue("(is)",1,name.c_str())); +} +void MessengerState::RemoveAllGuildMember() { + guild.clear();PyCallClassMemberFunc(handler,"OnRemoveAllList",Py_BuildValue("(i)",1)); +} +void MessengerState::LoginGuildMember(const std::string& name) { + guild[name]=1;PyCallClassMemberFunc(handler,"OnLogin",Py_BuildValue("(is)",1,name.c_str())); +} +void MessengerState::LogoutGuildMember(const std::string& name) { + guild[name]=0;PyCallClassMemberFunc(handler,"OnLogout",Py_BuildValue("(is)",1,name.c_str())); +} +void MessengerState::RefreshGuildMember() { + // Copy the ordered map so Python callbacks may safely change the native list. + const auto snapshot=guild; + for(const auto& [name,state]:snapshot) + PyCallClassMemberFunc(handler,state?"OnLogin":"OnLogout",Py_BuildValue("(is)",1,name.c_str())); +} +namespace { +PyObject* remove(PyObject*,PyObject* args) { + char* name;if(!PyTuple_GetString(args,0,&name))return Py_BuildException(); + GetMessengerState().RemoveFriend(name);Py_RETURN_NONE; +} +PyObject* is_friend(PyObject*,PyObject* args) { + char* name;if(!PyTuple_GetString(args,0,&name))return Py_BuildException(); + return PyInt_FromLong(GetMessengerState().IsFriend(name)); +} +PyObject* destroy(PyObject*,PyObject*) { GetMessengerState().Destroy();Py_RETURN_NONE; } +PyObject* refresh(PyObject*,PyObject*) { GetMessengerState().RefreshGuildMember();Py_RETURN_NONE; } +PyObject* set_handler(PyObject*,PyObject* args) { + PyObject* handler;if(!PyTuple_GetObject(args,0,&handler))return Py_BuildException(); + GetMessengerState().SetHandler(handler);Py_RETURN_NONE; +} +} +void initMessenger() { + static PyMethodDef methods[]={ + {"RemoveFriend",remove,METH_VARARGS,nullptr},{"IsFriendByName",is_friend,METH_VARARGS,nullptr}, + {"Destroy",destroy,METH_VARARGS,nullptr},{"RefreshGuildMember",refresh,METH_VARARGS,nullptr}, + {"SetMessengerHandler",set_handler,METH_VARARGS,nullptr},{nullptr,nullptr,0,nullptr}}; + Py_InitModule("messenger",methods); +} +} diff --git a/src/python_minimap.cpp b/src/python_minimap.cpp new file mode 100644 index 00000000..372126ab --- /dev/null +++ b/src/python_minimap.cpp @@ -0,0 +1,1361 @@ +// CPythonMiniMap + the "miniMap" module, ported from AVA2 UserInterface/PythonMiniMap.cpp and +// PythonMiniMapModule.cpp (see python_minimap.h for the Locale_inc.h set and what is not drawn). +// CPythonCharacterManager instances are the NetworkActorManager actors (NEW_GetPixelPosition = the +// local m_lCurX/m_lCurY), visited in VID order like the original std::map; CPythonBackground's +// IsMapOutdoor/GetName/GetBaseXY/GetTerrainCount come from GetOutdoorMap(). +#include "python_minimap.h" +#include "python_gameplay_modules.h" +#include "python_runtime.h" +#include "ava2_text_file_loader.h" +#include "guild_state.h" +#include "eter_net/NetworkActorManager.h" +#include "eter_resource/ResourceManager.h" +#include "eter_image/GrpImage.h" +#include "shared/common/PythonUtils.h" +#include +#include +#include +#include +#include +#include + +namespace ava2 { + +namespace { + +// CActorInstance::TYPE_* (GameLib/ActorInstance.h). +enum { ACTOR_TYPE_ENEMY = 0, ACTOR_TYPE_NPC = 1, ACTOR_TYPE_STONE = 2, ACTOR_TYPE_WARP = 3, ACTOR_TYPE_PC = 6 }; + +CGraphicImage* LoadImagePointer(const char* c_szFileName) +{ + CResource* pResource = CResourceManager::Instance().GetResourcePointer(c_szFileName); + return pResource && pResource->IsType(CGraphicImage::Type()) ? static_cast(pResource) : nullptr; +} + +std::vector CharacterInstances() +{ + std::vector instances; + for (const auto& [vid, actor] : NetworkActorManager::Instance().GetActorDict()) + instances.push_back(&actor); + std::sort(instances.begin(), instances.end(), [](auto* a, auto* b) { return a->m_dwVID < b->m_dwVID; }); + return instances; +} + +const SNetworkActorData* MainInstance() +{ + auto& manager = NetworkActorManager::Instance(); + return manager.GetActorData(manager.GetMainActorVID()); +} + +bool IsInvisibility(const SNetworkActorData& actor) +{ + return (actor.m_affectFlags[NetworkActorManager::AFFECT_INVISIBILITY / 32] & (1u << (NetworkActorManager::AFFECT_INVISIBILITY % 32))) != 0; +} + +// CInstanceBase::IsBoss: the race alone, whatever the actor type. +bool IsBoss(const SNetworkActorData& actor) +{ + return IsBossRace(actor.m_dwRace); +} + +uint32_t GetNameColor(const SNetworkActorData& actor) +{ + return NetworkActorManager::GetIndexedNameColor(NetworkActorManager::Instance().GetNameColorIndex(actor.m_dwVID)); +} + +// LocaleService_GetLocalePath through app.GetLocalePath, like loadAtlas in python_gameplay_modules. +std::string LocalePath() +{ + PyObject* app = PyImport_ImportModule("app"); + PyObject* path = app ? PyObject_CallMethod(app, const_cast("GetLocalePath"), nullptr) : nullptr; + Py_XDECREF(app); + std::string locale; + if (path && PyString_Check(path)) + locale = PyString_AsString(path); + Py_XDECREF(path); + PyErr_Clear(); + return locale; +} + +// PR_FLOAT_TO_INT: fistp (round to nearest) corrected down, i.e. floor. +int FloatToInt(float f) +{ + return int(std::floor(f)); +} + +} // namespace + +CPythonMiniMap& CPythonMiniMap::Instance() +{ + static CPythonMiniMap s_instance; + return s_instance; +} + +uint32_t CPythonMiniMap::__GetMSec() const +{ + if (m_now) + return m_now(); + static const auto s_start = std::chrono::steady_clock::now(); + return uint32_t(std::chrono::duration_cast(std::chrono::steady_clock::now() - s_start).count()); +} + +void CPythonMiniMap::AddObserver(uint32_t dwVID, float fSrcX, float fSrcY) +{ + SObserver& rkObserver = m_kMap_dwVID_kObserver[dwVID]; + rkObserver.dwSrcTime = __GetMSec(); + rkObserver.dwDstTime = rkObserver.dwSrcTime + 1000; + rkObserver.fSrcX = fSrcX; + rkObserver.fSrcY = fSrcY; + rkObserver.fDstX = fSrcX; + rkObserver.fDstY = fSrcY; + rkObserver.fCurX = fSrcX; + rkObserver.fCurY = fSrcY; +} + +void CPythonMiniMap::MoveObserver(uint32_t dwVID, float fDstX, float fDstY) +{ + auto f = m_kMap_dwVID_kObserver.find(dwVID); + if (m_kMap_dwVID_kObserver.end() == f) + return; + + SObserver& rkObserver = f->second; + rkObserver.dwSrcTime = __GetMSec(); + rkObserver.dwDstTime = rkObserver.dwSrcTime + 1000; + rkObserver.fSrcX = rkObserver.fCurX; + rkObserver.fSrcY = rkObserver.fCurY; + rkObserver.fDstX = fDstX; + rkObserver.fDstY = fDstY; +} + +void CPythonMiniMap::RemoveObserver(uint32_t dwVID) +{ + m_kMap_dwVID_kObserver.erase(dwVID); +} + +void CPythonMiniMap::SetCenterPosition(float fCenterX, float fCenterY) +{ + m_fCenterX = fCenterX; + m_fCenterY = fCenterY; + + // CMapOutdoor::GetCurCoordinate: the terrain the centre (the main actor) stands on. + const float fTerrainCoordX = std::floor(m_fCenterX / float(TERRAIN_SIZE)); + const float fTerrainCoordY = std::floor(m_fCenterY / float(TERRAIN_SIZE)); + + m_fCenterCellX = (m_fCenterX - fTerrainCoordX * float(TERRAIN_SIZE)) / CELLSCALE; + m_fCenterCellY = (m_fCenterY - fTerrainCoordY * float(TERRAIN_SIZE)) / CELLSCALE; + + __SetPosition(); +} + +void CPythonMiniMap::Update(float fCenterX, float fCenterY) +{ + if (!GetOutdoorMap()) + return; + + if (m_fCenterX != fCenterX || m_fCenterY != fCenterY) + SetCenterPosition(fCenterX, fCenterY); + + m_OtherPCPositionVector.clear(); + m_PartyPCPositionVector.clear(); + m_NPCPositionVector.clear(); + m_MetinPositionVector.clear(); + m_BossPositionVector.clear(); + m_MonsterPositionVector.clear(); + m_WarpPositionVector.clear(); + m_OfflineShopPositionVector.clear(); + + const float fooCellScale = 1.0f / CELLSCALE; + + const SNetworkActorData* pkInstMain = MainInstance(); + if (!pkInstMain) + return; + + const float fMarkX = (m_fWidth - (float)m_WhiteMark.GetWidth()) / 2.0f + m_fScreenX; + const float fMarkY = (m_fHeight - (float)m_WhiteMark.GetHeight()) / 2.0f + m_fScreenY; + + for (const SNetworkActorData* pkInstEach : CharacterInstances()) + { + float fDistanceFromCenterX = (float(pkInstEach->m_lCurX) - m_fCenterX) * fooCellScale * m_fScale; + float fDistanceFromCenterY = (float(pkInstEach->m_lCurY) - m_fCenterY) * fooCellScale * m_fScale; + if (std::fabs(fDistanceFromCenterX) >= m_fMiniMapRadius || std::fabs(fDistanceFromCenterY) >= m_fMiniMapRadius) + continue; + + float fDistanceFromCenter = sqrtf(fDistanceFromCenterX * fDistanceFromCenterX + fDistanceFromCenterY * fDistanceFromCenterY); + if (fDistanceFromCenter >= m_fMiniMapRadius) + continue; + + TMarkPosition aMarkPosition; + aMarkPosition.m_fX = fMarkX + fDistanceFromCenterX; + aMarkPosition.m_fY = fMarkY + fDistanceFromCenterY; + aMarkPosition.m_eNameColor = 0; + + if (pkInstEach->m_bType == ACTOR_TYPE_PC && !IsInvisibility(*pkInstEach)) + { + if (pkInstEach == pkInstMain) + continue; + + aMarkPosition.m_eNameColor = NetworkActorManager::Instance().GetNameColorIndex(pkInstEach->m_dwVID); + if (aMarkPosition.m_eNameColor == NetworkActorManager::NAMECOLOR_PARTY) + m_PartyPCPositionVector.push_back(aMarkPosition); + else + m_OtherPCPositionVector.push_back(aMarkPosition); + } + else if (pkInstEach->m_bType == ACTOR_TYPE_STONE) + { + m_MetinPositionVector.push_back(aMarkPosition); + } + else if (pkInstEach->m_bType == ACTOR_TYPE_NPC) + { + // ENABLE_GRAPHIC_ON_OFF GetRenderStatus: the port draws every NPC, so it is always true. + if (pkInstEach->m_dwRace >= 30000 && pkInstEach->m_dwRace <= 30020) // CActorInstance::IsShop + m_OfflineShopPositionVector.push_back(aMarkPosition); + else + m_NPCPositionVector.push_back(aMarkPosition); + } + else if (pkInstEach->m_bType == ACTOR_TYPE_ENEMY && !IsBoss(*pkInstEach)) + { + m_MonsterPositionVector.push_back(aMarkPosition); + } + else if (IsBoss(*pkInstEach)) + { + m_BossPositionVector.push_back(aMarkPosition); + } + else if (pkInstEach->m_bType == ACTOR_TYPE_WARP) + { + m_WarpPositionVector.push_back(aMarkPosition); + } + } + + { + uint32_t dwCurTime = __GetMSec(); + + for (auto& [dwVID, rkObserver] : m_kMap_dwVID_kObserver) + { + float fPos = float(dwCurTime - rkObserver.dwSrcTime) / float(rkObserver.dwDstTime - rkObserver.dwSrcTime); + if (fPos < 0.0f) fPos = 0.0f; + else if (fPos > 1.0f) fPos = 1.0f; + + rkObserver.fCurX = (rkObserver.fDstX - rkObserver.fSrcX) * fPos + rkObserver.fSrcX; + rkObserver.fCurY = (rkObserver.fDstY - rkObserver.fSrcY) * fPos + rkObserver.fSrcY; + + float fDistanceFromCenterX = (rkObserver.fCurX - m_fCenterX) * fooCellScale * m_fScale; + float fDistanceFromCenterY = (rkObserver.fCurY - m_fCenterY) * fooCellScale * m_fScale; + if (std::fabs(fDistanceFromCenterX) >= m_fMiniMapRadius || std::fabs(fDistanceFromCenterY) >= m_fMiniMapRadius) + continue; + + float fDistanceFromCenter = sqrtf(fDistanceFromCenterX * fDistanceFromCenterX + fDistanceFromCenterY * fDistanceFromCenterY); + if (fDistanceFromCenter >= m_fMiniMapRadius) + continue; + + TMarkPosition aMarkPosition; + aMarkPosition.m_fX = fMarkX + fDistanceFromCenterX; + aMarkPosition.m_fY = fMarkY + fDistanceFromCenterY; + aMarkPosition.m_eNameColor = NetworkActorManager::NAMECOLOR_PARTY; + m_PartyPCPositionVector.push_back(aMarkPosition); + } + } + + for (TAtlasMarkInfo& rAtlasMarkInfo : m_AtlasWayPointInfoVector) + { + if (TYPE_TARGET != rAtlasMarkInfo.m_byType) + continue; + + if (0 != rAtlasMarkInfo.m_dwChrVID) + { + if (const SNetworkActorData* pInstance = NetworkActorManager::Instance().GetActorData(rAtlasMarkInfo.m_dwChrVID)) + __UpdateWayPoint(&rAtlasMarkInfo, pInstance->m_lCurX, pInstance->m_lCurY); + } + + const float c_fMiniMapWindowRadius = 55.0f; + + float fDistanceFromCenterX = (rAtlasMarkInfo.m_fX - m_fCenterX) * fooCellScale * m_fScale; + float fDistanceFromCenterY = (rAtlasMarkInfo.m_fY - m_fCenterY) * fooCellScale * m_fScale; + float fDistanceFromCenter = sqrtf(fDistanceFromCenterX * fDistanceFromCenterX + fDistanceFromCenterY * fDistanceFromCenterY); + + if (fDistanceFromCenter >= c_fMiniMapWindowRadius) + { + float fRadianX = acosf(fDistanceFromCenterX / fDistanceFromCenter); + float fRadianY = asinf(fDistanceFromCenterY / fDistanceFromCenter); + fDistanceFromCenterX = 55.0f * cosf(fRadianX); + fDistanceFromCenterY = 55.0f * sinf(fRadianY); + rAtlasMarkInfo.m_fMiniMapX = fMarkX + fDistanceFromCenterX + 2.0f; + rAtlasMarkInfo.m_fMiniMapY = fMarkY + fDistanceFromCenterY + 2.0f; + } + else + { + rAtlasMarkInfo.m_fMiniMapX = fMarkX + fDistanceFromCenterX; + rAtlasMarkInfo.m_fMiniMapY = fMarkY + fDistanceFromCenterY; + } + } +} + +void CPythonMiniMap::Render(float fScreenX, float fScreenY) +{ + // CPythonBackground::IsMapReady is implied by GetOutdoorMap (the terrain block loaded). + if (!GetOutdoorMap()) + return; + + if (!m_bShow) + return; + + if (m_fScreenX != fScreenX || m_fScreenY != fScreenY) + { + m_fScreenX = fScreenX; + m_fScreenY = fScreenY; + __SetPosition(); + } + // The minimap texture quads, cover filter, marks and waypoint icons are not drawn. +} + +void CPythonMiniMap::SetScale(float fScale) +{ + if (fScale >= 4.0f) + fScale = 4.0f; + if (fScale <= 0.5f) + fScale = 0.5f; + m_fScale = fScale; + + __SetPosition(); +} + +void CPythonMiniMap::ScaleUp() +{ + m_fScale *= 2.0f; + if (m_fScale >= 4.0f) + m_fScale = 4.0f; + __SetPosition(); +} + +void CPythonMiniMap::ScaleDown() +{ + m_fScale *= 0.5f; + if (m_fScale <= 0.5f) + m_fScale = 0.5f; + __SetPosition(); +} + +void CPythonMiniMap::SetMiniMapSize(float fWidth, float fHeight) +{ + m_fWidth = fWidth; + m_fHeight = fHeight; +} + +bool CPythonMiniMap::Create() +{ + const std::string strImageRoot = "D:/ymir work/ui/"; + // ENABLE_MINIMAP_WHITEMARK_NEW + const std::string strPlayerMark = strImageRoot + "minimap/whitemark_new.tga"; + const std::string strWhiteMark = strImageRoot + "minimap/whitemark_new.tga"; + const std::string strBossMark = strImageRoot + "minimap/boss_mark_new.tga"; + + m_PlayerMark.SetImagePointer(LoadImagePointer(strPlayerMark.c_str())); + m_WhiteMark.SetImagePointer(LoadImagePointer(strWhiteMark.c_str())); + m_BossMark.SetImagePointer(LoadImagePointer(strBossMark.c_str())); + // The filter/camera images, waypoint/target/guild-area icons and the vertex/index buffers only + // feed Render; their sizes do not enter any position the module reports. + return true; +} + +void CPythonMiniMap::__SetPosition() +{ + m_fMiniMapRadius = std::min(6400.0f / CELLSCALE * m_fScale, 64.0f); + // m_matWorld / m_matMiniMapCover / the player-mark and camera image positions are render state. +} + +////////////////////////////////////////////////////////////////////////// +// Atlas + +void CPythonMiniMap::ClearAtlasMarkInfo() +{ + m_AtlasNPCInfoVector.clear(); + m_AtlasBossInfoVector.clear(); + m_AtlasWarpInfoVector.clear(); +} + +void CPythonMiniMap::RegisterAtlasMark(uint8_t byType, uint32_t mobVnum, const char* c_szName, long lx, long ly, int regenTime) +{ + TAtlasMarkInfo aAtlasMarkInfo{}; + + aAtlasMarkInfo.m_fX = float(lx); + aAtlasMarkInfo.m_fY = float(ly); + aAtlasMarkInfo.m_strText = c_szName; + aAtlasMarkInfo.mobVnum = mobVnum; + aAtlasMarkInfo.regenTime = regenTime; + + aAtlasMarkInfo.m_fScreenX = aAtlasMarkInfo.m_fX / m_fAtlasMaxX * m_fAtlasImageSizeX - (float)m_WhiteMark.GetWidth() / 2.0f; + aAtlasMarkInfo.m_fScreenY = aAtlasMarkInfo.m_fY / m_fAtlasMaxY * m_fAtlasImageSizeY - (float)m_WhiteMark.GetHeight() / 2.0f; + + switch (byType) + { + case ACTOR_TYPE_ENEMY: + aAtlasMarkInfo.m_fScreenX = aAtlasMarkInfo.m_fX / m_fAtlasMaxX * m_fAtlasImageSizeX - (float)m_BossMark.GetWidth() / 2.0f; + aAtlasMarkInfo.m_fScreenY = aAtlasMarkInfo.m_fY / m_fAtlasMaxY * m_fAtlasImageSizeY - (float)m_BossMark.GetHeight() / 2.0f; + aAtlasMarkInfo.m_byType = TYPE_MONSTER; + m_AtlasBossInfoVector.push_back(aAtlasMarkInfo); + break; + case ACTOR_TYPE_NPC: + aAtlasMarkInfo.m_byType = TYPE_NPC; + m_AtlasNPCInfoVector.push_back(aAtlasMarkInfo); + break; + case ACTOR_TYPE_WARP: + aAtlasMarkInfo.m_byType = TYPE_WARP; + { + // m_strText[iPos]=0: the length is kept, c_str() readers see the name cut at the space. + size_t iPos = aAtlasMarkInfo.m_strText.find(" "); + if (iPos != std::string::npos) + aAtlasMarkInfo.m_strText[iPos] = 0; + } + m_AtlasWarpInfoVector.push_back(aAtlasMarkInfo); + break; + } +} + +void CPythonMiniMap::ClearGuildArea() +{ + m_GuildAreaInfoVector.clear(); +} + +void CPythonMiniMap::RegisterGuildArea(uint32_t dwID, uint32_t dwGuildID, long x, long y, long width, long height) +{ + (void)dwID; + TGuildAreaInfo kGuildAreaInfo{}; + kGuildAreaInfo.dwGuildID = dwGuildID; + kGuildAreaInfo.lx = x; + kGuildAreaInfo.ly = y; + kGuildAreaInfo.lwidth = width; + kGuildAreaInfo.lheight = height; + m_GuildAreaInfoVector.push_back(kGuildAreaInfo); +} + +uint32_t CPythonMiniMap::GetGuildAreaID(uint32_t x, uint32_t y) +{ + // DWORD against the 32-bit Win32 long: the comparisons are unsigned. + for (const TGuildAreaInfo& rAreaInfo : m_GuildAreaInfoVector) + { + if (x >= uint32_t(rAreaInfo.lx)) + if (y >= uint32_t(rAreaInfo.ly)) + if (x <= uint32_t(rAreaInfo.lx + rAreaInfo.lwidth)) + if (y <= uint32_t(rAreaInfo.ly + rAreaInfo.lheight)) + { + return rAreaInfo.dwGuildID; + } + } + + return 0xffffffff; +} + +void CPythonMiniMap::CreateTarget(int iID, const char* c_szName) +{ + AddWayPoint(TYPE_TARGET, iID, 0.0f, 0.0f, c_szName); +} + +void CPythonMiniMap::UpdateTarget(int iID, int ix, int iy) +{ + TAtlasMarkInfo* pkInfo; + if (!__GetWayPoint(iID, &pkInfo)) + return; + + if (0 != pkInfo->m_dwChrVID) + { + if (NetworkActorManager::Instance().GetActorData(pkInfo->m_dwChrVID)) + return; + } + + // int against DWORD: unsigned comparisons, as on Windows. + if (uint32_t(ix) < m_dwAtlasBaseX) + return; + if (uint32_t(iy) < m_dwAtlasBaseY) + return; + if (uint32_t(ix) > m_dwAtlasBaseX + uint32_t(m_fAtlasMaxX)) + return; + if (uint32_t(iy) > m_dwAtlasBaseY + uint32_t(m_fAtlasMaxY)) + return; + + __UpdateWayPoint(pkInfo, ix - int(m_dwAtlasBaseX), iy - int(m_dwAtlasBaseY)); +} + +void CPythonMiniMap::CreateTarget(int iID, const char* c_szName, uint32_t dwVID) +{ + AddWayPoint(TYPE_TARGET, iID, 0.0f, 0.0f, c_szName, dwVID); +} + +void CPythonMiniMap::DeleteTarget(int iID) +{ + RemoveWayPoint(iID); +} + +void CPythonMiniMap::__LoadAtlasMarkInfo() +{ + ClearAtlasMarkInfo(); + ClearGuildArea(); + + const OutdoorMapInfo* pkMap = GetOutdoorMap(); + if (!pkMap) + return; + + // LOCALE + char szAtlasMarkInfoFileName[64 + 1]; + snprintf(szAtlasMarkInfoFileName, sizeof(szAtlasMarkInfoFileName), "%s/map/%s_point.txt", LocalePath().c_str(), pkMap->name.c_str()); + // END_OF_LOCALE + + std::map> stTokenVectorMap; + try + { + ava2LoadMultipleTextData(ReadPackedText(szAtlasMarkInfoFileName), stTokenVectorMap); + } + catch (const std::exception&) + { + return; + } + + const std::string strType[TYPE_COUNT] = { "OPC", "OPCPVP", "OPCPVPSELF", "NPC", "MONSTER", "WARP", "WAYPOINT" }; + + for (uint32_t i = 0; i < stTokenVectorMap.size(); ++i) + { + char szMarkInfoName[32 + 1]; + snprintf(szMarkInfoName, sizeof(szMarkInfoName), "%d", i); + + auto it = stTokenVectorMap.find(szMarkInfoName); + if (stTokenVectorMap.end() == it) + continue; + + const std::vector& rVector = it->second; + // Windows indexes [0..3] unchecked; a short row is undefined behaviour there. + if (rVector.size() < 4) + continue; + + const std::string& c_rstrType = rVector[0]; + const std::string& c_rstrPositionX = rVector[1]; + const std::string& c_rstrPositionY = rVector[2]; + const std::string& c_rstrText = rVector[3]; + + TAtlasMarkInfo aAtlasMarkInfo{}; + aAtlasMarkInfo.m_byType = TYPE_COUNT; // uninitialised on Windows when no type name matches + + for (int t = 0; t < TYPE_COUNT; ++t) + { + if (0 == c_rstrType.compare(strType[t])) + aAtlasMarkInfo.m_byType = (uint8_t)t; + } + aAtlasMarkInfo.m_fX = float(atof(c_rstrPositionX.c_str())); + aAtlasMarkInfo.m_fY = float(atof(c_rstrPositionY.c_str())); + aAtlasMarkInfo.m_strText = c_rstrText; + + aAtlasMarkInfo.m_fScreenX = aAtlasMarkInfo.m_fX / m_fAtlasMaxX * m_fAtlasImageSizeX - (float)m_WhiteMark.GetWidth() / 2.0f; + aAtlasMarkInfo.m_fScreenY = aAtlasMarkInfo.m_fY / m_fAtlasMaxY * m_fAtlasImageSizeY - (float)m_WhiteMark.GetHeight() / 2.0f; + + switch (aAtlasMarkInfo.m_byType) + { + case TYPE_NPC: + m_AtlasNPCInfoVector.push_back(aAtlasMarkInfo); + break; + case TYPE_WARP: + m_AtlasWarpInfoVector.push_back(aAtlasMarkInfo); + break; + } + } +} + +bool CPythonMiniMap::LoadAtlas() +{ + const OutdoorMapInfo* pkMap = GetOutdoorMap(); + if (!pkMap) + return false; + + const char* playerMarkFileName = "d:/ymir work/ui/minimap/playermark.sub"; + + char atlasFileName[1024 + 1]; + snprintf(atlasFileName, sizeof(atlasFileName), "%s/atlas.sub", pkMap->name.c_str()); + if (!CResourceManager::ResourceExists(atlasFileName)) + { + snprintf(atlasFileName, sizeof(atlasFileName), "d:/ymir work/ui/atlas/%s/atlas.sub", pkMap->name.c_str()); + } + + m_AtlasImageInstance.Destroy(); + m_AtlasPlayerMark.Destroy(); + CGraphicImage* pkGrpImgAtlas = LoadImagePointer(atlasFileName); + // Windows' resource manager hands back an empty CGraphicImage for a missing file (m_bAtlas=false); + // this one returns NULL, which is the same empty atlas. + m_AtlasImageInstance.SetImagePointer(pkGrpImgAtlas); + m_bAtlas = pkGrpImgAtlas && !pkGrpImgAtlas->IsEmpty(); + m_AtlasPlayerMark.SetImagePointer(LoadImagePointer(playerMarkFileName)); + + m_dwAtlasBaseX = pkMap->baseX; + m_dwAtlasBaseY = pkMap->baseY; + m_fAtlasMaxX = (float)pkMap->terrainCountX * TERRAIN_SIZE; + m_fAtlasMaxY = (float)pkMap->terrainCountY * TERRAIN_SIZE; + + m_fAtlasImageSizeX = (float)m_AtlasImageInstance.GetWidth(); + m_fAtlasImageSizeY = (float)m_AtlasImageInstance.GetHeight(); + + __LoadAtlasMarkInfo(); + + if (m_bShowAtlas) + OpenAtlasWindow(); + + return true; +} + +void CPythonMiniMap::__GlobalPositionToAtlasPosition(long lx, long ly, float* pfx, float* pfy) +{ + *pfx = lx / m_fAtlasMaxX * m_fAtlasImageSizeX; + *pfy = ly / m_fAtlasMaxY * m_fAtlasImageSizeY; +} + +void CPythonMiniMap::UpdateAtlas() +{ + if (const SNetworkActorData* pkInst = MainInstance()) + { + float fRotation = (540.0f - pkInst->m_fRot); + while (fRotation > 360.0f) + fRotation -= 360.0f; + while (fRotation < 0.0f) + fRotation += 360.0f; + + m_AtlasPlayerMark.SetPosition(float(pkInst->m_lCurX) / m_fAtlasMaxX * m_fAtlasImageSizeX - (float)m_AtlasPlayerMark.GetWidth() / 2.0f, + float(pkInst->m_lCurY) / m_fAtlasMaxY * m_fAtlasImageSizeY - (float)m_AtlasPlayerMark.GetHeight() / 2.0f); + (void)fRotation; // CGraphicExpandedImageInstance::SetRotation: render state only + } + + for (TGuildAreaInfo& rInfo : m_GuildAreaInfoVector) + { + __GlobalPositionToAtlasPosition(rInfo.lx, rInfo.ly, &rInfo.fsxRender, &rInfo.fsyRender); + __GlobalPositionToAtlasPosition(rInfo.lx + rInfo.lwidth, rInfo.ly + rInfo.lheight, &rInfo.fexRender, &rInfo.feyRender); + } +} + +void CPythonMiniMap::RenderAtlas(float fScreenX, float fScreenY) +{ + if (!m_bShowAtlas) + return; + + if (m_fAtlasScreenX != fScreenX || m_fAtlasScreenY != fScreenY) + { + m_fAtlasScreenX = fScreenX; + m_fAtlasScreenY = fScreenY; + } + // The atlas image, marks, waypoints, guild areas and player mark are not drawn. +} + +bool CPythonMiniMap::GetPickedInstanceInfo(float fScreenX, float fScreenY, std::string& rReturnName, float* pReturnPosX, float* pReturnPosY, uint32_t* pdwTextColor) +{ + float fDistanceFromMiniMapCenterX = fScreenX - m_fScreenX - m_fWidth * 0.5f; + float fDistanceFromMiniMapCenterY = fScreenY - m_fScreenY - m_fHeight * 0.5f; + + if (sqrtf(fDistanceFromMiniMapCenterX * fDistanceFromMiniMapCenterX + fDistanceFromMiniMapCenterY * fDistanceFromMiniMapCenterY) > m_fMiniMapRadius) + return false; + + float fRealX = m_fCenterX + fDistanceFromMiniMapCenterX / m_fScale * CELLSCALE; + float fRealY = m_fCenterY + fDistanceFromMiniMapCenterY / m_fScale * CELLSCALE; + + if (const SNetworkActorData* pkInst = MainInstance()) + { + if (std::fabs(float(pkInst->m_lCurX) - fRealX) < CELLSCALE * 6.0f / m_fScale && + std::fabs(float(pkInst->m_lCurY) - fRealY) < CELLSCALE * 6.0f / m_fScale) + { + rReturnName = pkInst->m_stName; + *pReturnPosX = float(pkInst->m_lCurX); + *pReturnPosY = float(pkInst->m_lCurY); + *pdwTextColor = GetNameColor(*pkInst); + return true; + } + } + + if (m_fScale < 1.0f) + return false; + + for (const SNetworkActorData* pkInstEach : CharacterInstances()) + { + if (IsInvisibility(*pkInstEach)) + continue; + if (m_fScale < 2.0f && (pkInstEach->m_bType == ACTOR_TYPE_ENEMY || pkInstEach->m_bType == ACTOR_TYPE_PC)) + continue; + + if (std::fabs(float(pkInstEach->m_lCurX) - fRealX) < CELLSCALE * 3.0f / m_fScale && + std::fabs(float(pkInstEach->m_lCurY) - fRealY) < CELLSCALE * 3.0f / m_fScale) + { + rReturnName = pkInstEach->m_stName; + *pReturnPosX = float(pkInstEach->m_lCurX); + *pReturnPosY = float(pkInstEach->m_lCurY); + *pdwTextColor = GetNameColor(*pkInstEach); + return true; + } + } + return false; +} + +bool CPythonMiniMap::GetAtlasInfo(float fScreenX, float fScreenY, std::string& rReturnString, float* pReturnPosX, float* pReturnPosY, uint32_t* pdwTextColor, uint32_t* pdwGuildID, int* pdiRegenTime) +{ + float fRealX = (fScreenX - m_fAtlasScreenX) * (m_fAtlasMaxX / m_fAtlasImageSizeX); + float fRealY = (fScreenY - m_fAtlasScreenY) * (m_fAtlasMaxY / m_fAtlasImageSizeY); + + float fCheckWidth = (m_fAtlasMaxX / m_fAtlasImageSizeX) * 5.0f; + float fCheckHeight = (m_fAtlasMaxY / m_fAtlasImageSizeY) * 5.0f; + + *pdiRegenTime = 0; + + if (const SNetworkActorData* pkInst = MainInstance()) + { + const float fx = float(pkInst->m_lCurX), fy = float(pkInst->m_lCurY); + if (fx - fCheckWidth < fRealX && fx + fCheckWidth > fRealX && + fy - fCheckHeight < fRealY && fy + fCheckHeight > fRealY) + { + rReturnString = pkInst->m_stName; + *pReturnPosX = fx; + *pReturnPosY = fy; + *pdwTextColor = GetNameColor(*pkInst); + return true; + } + } + + // The y test uses fCheckWidth/2 for the lower bound, as on Windows. + auto hit = [&](const TAtlasMarkInfo& rAtlasMarkInfo) { + return rAtlasMarkInfo.m_fX - fCheckWidth / 2 < fRealX && rAtlasMarkInfo.m_fX + fCheckWidth > fRealX && + rAtlasMarkInfo.m_fY - fCheckWidth / 2 < fRealY && rAtlasMarkInfo.m_fY + fCheckHeight > fRealY; + }; + + for (const TAtlasMarkInfo& rAtlasMarkInfo : m_AtlasNPCInfoVector) + { + if (hit(rAtlasMarkInfo)) + { + rReturnString = rAtlasMarkInfo.m_strText.c_str(); + *pReturnPosX = rAtlasMarkInfo.m_fX; + *pReturnPosY = rAtlasMarkInfo.m_fY; + *pdwTextColor = NetworkActorManager::GetIndexedNameColor(NetworkActorManager::NAMECOLOR_NPC); + return true; + } + } + + for (const TAtlasMarkInfo& rAtlasMarkInfo : m_AtlasBossInfoVector) + { + if (hit(rAtlasMarkInfo)) + { + rReturnString = rAtlasMarkInfo.m_strText.c_str(); + *pReturnPosX = rAtlasMarkInfo.m_fX; + *pReturnPosY = rAtlasMarkInfo.m_fY; + *pdiRegenTime = rAtlasMarkInfo.regenTime; + *pdwTextColor = 0xFFFFFFFF; + return true; + } + } + + for (const TAtlasMarkInfo& rAtlasMarkInfo : m_AtlasWarpInfoVector) + { + if (hit(rAtlasMarkInfo)) + { + // std::string copy keeps the embedded NUL; the module's "s" stops at it. + rReturnString = rAtlasMarkInfo.m_strText; + *pReturnPosX = rAtlasMarkInfo.m_fX; + *pReturnPosY = rAtlasMarkInfo.m_fY; + *pdwTextColor = NetworkActorManager::GetIndexedNameColor(NetworkActorManager::NAMECOLOR_WARP); + return true; + } + } + + for (const TAtlasMarkInfo& rAtlasMarkInfo : m_AtlasWayPointInfoVector) + { + if (rAtlasMarkInfo.m_fScreenX > 0.0f) + if (rAtlasMarkInfo.m_fScreenY > 0.0f) + if (hit(rAtlasMarkInfo)) + { + rReturnString = rAtlasMarkInfo.m_strText; + *pReturnPosX = rAtlasMarkInfo.m_fX; + *pReturnPosY = rAtlasMarkInfo.m_fY; + *pdwTextColor = NetworkActorManager::GetIndexedNameColor(NetworkActorManager::NAMECOLOR_WAYPOINT); + return true; + } + } + + for (const TGuildAreaInfo& rInfo : m_GuildAreaInfoVector) + { + if (fScreenX - m_fAtlasScreenX >= rInfo.fsxRender) + if (fScreenY - m_fAtlasScreenY >= rInfo.fsyRender) + if (fScreenX - m_fAtlasScreenX <= rInfo.fexRender) + if (fScreenY - m_fAtlasScreenY <= rInfo.feyRender) + { + // CPythonGuild::GetGuildName + const auto& names = GetGuildState().names; + auto f = names.find(rInfo.dwGuildID); + if (f != names.end()) + { + rReturnString = f->second; + *pdwGuildID = rInfo.dwGuildID; + } + else + { + rReturnString = "empty_guild_area"; + } + + *pReturnPosX = float(rInfo.lx + rInfo.lwidth / 2); + *pReturnPosY = float(rInfo.ly + rInfo.lheight / 2); + *pdwTextColor = NetworkActorManager::GetIndexedNameColor(NetworkActorManager::NAMECOLOR_PARTY); + return true; + } + } + + return false; +} + +bool CPythonMiniMap::GetAtlasSize(float* pfSizeX, float* pfSizeY) +{ + if (!GetOutdoorMap()) + return false; + + *pfSizeX = m_fAtlasImageSizeX; + *pfSizeY = m_fAtlasImageSizeY; + + return true; +} + +////////////////////////////////////////////////////////////////////////// +// WayPoint +void CPythonMiniMap::AddWayPoint(uint8_t byType, uint32_t dwID, float fX, float fY, std::string strText, uint32_t dwChrVID) +{ + for (const TAtlasMarkInfo& rAtlasMarkInfo : m_AtlasWayPointInfoVector) + { + if (rAtlasMarkInfo.m_dwID == dwID) + return; + } + + TAtlasMarkInfo aAtlasMarkInfo{}; + aAtlasMarkInfo.m_byType = byType; + aAtlasMarkInfo.m_dwID = dwID; + aAtlasMarkInfo.m_fX = fX; + aAtlasMarkInfo.m_fY = fY; + aAtlasMarkInfo.m_fScreenX = 0.0f; + aAtlasMarkInfo.m_fScreenY = 0.0f; + aAtlasMarkInfo.m_fMiniMapX = 0.0f; + aAtlasMarkInfo.m_fMiniMapY = 0.0f; + aAtlasMarkInfo.m_strText = strText; + aAtlasMarkInfo.m_dwChrVID = dwChrVID; + __UpdateWayPoint(&aAtlasMarkInfo, int(fX), int(fY)); + m_AtlasWayPointInfoVector.push_back(aAtlasMarkInfo); +} + +void CPythonMiniMap::RemoveWayPoint(uint32_t dwID) +{ + for (auto it = m_AtlasWayPointInfoVector.begin(); it != m_AtlasWayPointInfoVector.end(); ++it) + { + if (it->m_dwID == dwID) + { + m_AtlasWayPointInfoVector.erase(it); + return; + } + } +} + +bool CPythonMiniMap::__GetWayPoint(uint32_t dwID, TAtlasMarkInfo** ppkInfo) +{ + for (TAtlasMarkInfo& rInfo : m_AtlasWayPointInfoVector) + { + if (dwID == rInfo.m_dwID) + { + *ppkInfo = &rInfo; + return true; + } + } + + return false; +} + +void CPythonMiniMap::__UpdateWayPoint(TAtlasMarkInfo* pkInfo, int ix, int iy) +{ + pkInfo->m_fX = float(ix); + pkInfo->m_fY = float(iy); + pkInfo->m_fScreenX = pkInfo->m_fX / m_fAtlasMaxX * m_fAtlasImageSizeX; + pkInfo->m_fScreenY = pkInfo->m_fY / m_fAtlasMaxY * m_fAtlasImageSizeY; +} + +// WayPoint +////////////////////////////////////////////////////////////////////////// + +void CPythonMiniMap::AddSignalPoint(float fX, float fY) +{ + static unsigned int g_id = 255; + + TSignalPoint sp; + sp.id = g_id; + sp.x = fX; + sp.y = fY; + + m_SignalPointVector.push_back(sp); + + AddWayPoint(TYPE_WAYPOINT, g_id, fX, fY, ""); + + g_id++; +} + +void CPythonMiniMap::ClearAllSignalPoint() +{ + for (const TSignalPoint& sp : m_SignalPointVector) + RemoveWayPoint(sp.id); + m_SignalPointVector.clear(); +} + +void CPythonMiniMap::RegisterAtlasWindow(PyObject* poHandler) +{ + m_poHandler = poHandler; // borrowed, as on Windows +} + +void CPythonMiniMap::UnregisterAtlasWindow() +{ + m_poHandler = 0; +} + +void CPythonMiniMap::OpenAtlasWindow() +{ + if (m_poHandler) + PyCallClassMemberFunc(m_poHandler, "Show", Py_BuildValue("()")); +} + +void CPythonMiniMap::SetAtlasCenterPosition(int x, int y) +{ + if (m_poHandler) + PyCallClassMemberFunc(m_poHandler, "SetCenterPositionAdjust", Py_BuildValue("(ii)", x, y)); +} + +bool CPythonMiniMap::IsAtlas() { return m_bAtlas; } +void CPythonMiniMap::ShowAtlas() { m_bShowAtlas = true; } +void CPythonMiniMap::HideAtlas() { m_bShowAtlas = false; } +bool CPythonMiniMap::CanShowAtlas() { return m_bShowAtlas; } +bool CPythonMiniMap::CanShow() { return m_bShow; } +void CPythonMiniMap::Show() { m_bShow = true; } +void CPythonMiniMap::Hide() { m_bShow = false; } + +void CPythonMiniMap::__Initialize() +{ + m_poHandler = 0; + + SetMiniMapSize(128.0f, 128.0f); + + m_fScale = 2.0f; + + m_fCenterX = m_fWidth * 0.5f; + m_fCenterY = m_fHeight * 0.5f; + + // Left uninitialised by the Windows constructor until the first SetCenterPosition / __SetPosition. + m_fCenterCellX = 0.0f; + m_fCenterCellY = 0.0f; + m_fMiniMapRadius = 0.0f; + + m_fScreenX = 0.0f; + m_fScreenY = 0.0f; + + m_fAtlasScreenX = 0.0f; + m_fAtlasScreenY = 0.0f; + + m_dwAtlasBaseX = 0; + m_dwAtlasBaseY = 0; + + m_fAtlasMaxX = 0.0f; + m_fAtlasMaxY = 0.0f; + + m_fAtlasImageSizeX = 0.0f; + m_fAtlasImageSizeY = 0.0f; + + m_bAtlas = false; + + m_bShow = false; + m_bShowAtlas = false; +} + +void CPythonMiniMap::Destroy() +{ + ClearAllSignalPoint(); + m_poHandler = 0; + + m_PlayerMark.Destroy(); + + m_AtlasWayPointInfoVector.clear(); + m_AtlasImageInstance.Destroy(); + m_AtlasPlayerMark.Destroy(); + m_WhiteMark.Destroy(); + m_BossMark.Destroy(); + + __Initialize(); +} + +CPythonMiniMap::CPythonMiniMap() +{ + __Initialize(); +} + +CPythonMiniMap::TestView CPythonMiniMap::GetTestView() const +{ + TestView v{}; + v.scale = m_fScale; + v.radius = m_fMiniMapRadius; + v.centerCellX = m_fCenterCellX; + v.centerCellY = m_fCenterCellY; + v.partyPC = &m_PartyPCPositionVector; + v.otherPC = &m_OtherPCPositionVector; + v.npc = &m_NPCPositionVector; + v.boss = &m_BossPositionVector; + v.metin = &m_MetinPositionVector; + v.monster = &m_MonsterPositionVector; + v.warp = &m_WarpPositionVector; + v.offlineShop = &m_OfflineShopPositionVector; + v.npcMarks = m_AtlasNPCInfoVector.size(); + v.bossMarks = m_AtlasBossInfoVector.size(); + v.warpMarks = m_AtlasWarpInfoVector.size(); + v.wayPoints = m_AtlasWayPointInfoVector.size(); + v.guildAreas = m_GuildAreaInfoVector.size(); + v.observers = m_kMap_dwVID_kObserver.size(); + v.atlasMaxX = m_fAtlasMaxX; + v.atlasMaxY = m_fAtlasMaxY; + v.atlasBaseX = m_dwAtlasBaseX; + v.atlasBaseY = m_dwAtlasBaseY; + return v; +} + +bool CPythonMiniMap::GetTargetMiniMapPosition(uint32_t dwID, float* pfx, float* pfy) const +{ + for (const TAtlasMarkInfo& rInfo : m_AtlasWayPointInfoVector) + { + if (rInfo.m_dwID == dwID) + { + *pfx = rInfo.m_fMiniMapX; + *pfy = rInfo.m_fMiniMapY; + return true; + } + } + return false; +} + +////////////////////////////////////////////////////////////////////////// +// PythonMiniMapModule.cpp + +namespace { + +PyObject* miniMapSetScale(PyObject*, PyObject* poArgs) +{ + float fScale; + if (!PyTuple_GetFloat(poArgs, 0, &fScale)) + return Py_BuildException(); + + CPythonMiniMap::Instance().SetScale(fScale); + return Py_BuildNone(); +} + +PyObject* miniMapSetCenterPosition(PyObject*, PyObject* poArgs) +{ + float fCenterX; + if (!PyTuple_GetFloat(poArgs, 0, &fCenterX)) + return Py_BuildException(); + float fCenterY; + if (!PyTuple_GetFloat(poArgs, 1, &fCenterY)) + return Py_BuildException(); + + CPythonMiniMap::Instance().SetCenterPosition(fCenterX, fCenterY); + return Py_BuildNone(); +} + +PyObject* miniMapSetMiniMapSize(PyObject*, PyObject* poArgs) +{ + float fWidth; + if (!PyTuple_GetFloat(poArgs, 0, &fWidth)) + return Py_BuildException(); + float fHeight; + if (!PyTuple_GetFloat(poArgs, 1, &fHeight)) + return Py_BuildException(); + + CPythonMiniMap::Instance().SetMiniMapSize(fWidth, fHeight); + return Py_BuildNone(); +} + +PyObject* miniMapDestroy(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().Destroy(); + return Py_BuildNone(); +} + +PyObject* miniMapCreate(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().Create(); + return Py_BuildNone(); +} + +PyObject* miniMapUpdate(PyObject*, PyObject* poArgs) +{ + float fCenterX; + if (!PyTuple_GetFloat(poArgs, 0, &fCenterX)) + return Py_BuildException(); + float fCenterY; + if (!PyTuple_GetFloat(poArgs, 1, &fCenterY)) + return Py_BuildException(); + + CPythonMiniMap::Instance().Update(fCenterX, fCenterY); + return Py_BuildNone(); +} + +PyObject* miniMapRender(PyObject*, PyObject* poArgs) +{ + float fScrrenX; + if (!PyTuple_GetFloat(poArgs, 0, &fScrrenX)) + return Py_BuildException(); + float fScrrenY; + if (!PyTuple_GetFloat(poArgs, 1, &fScrrenY)) + return Py_BuildException(); + + CPythonMiniMap::Instance().Render(fScrrenX, fScrrenY); + return Py_BuildNone(); +} + +PyObject* miniMapShow(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().Show(); + return Py_BuildNone(); +} + +PyObject* miniMapHide(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().Hide(); + return Py_BuildNone(); +} + +PyObject* miniMapisShow(PyObject*, PyObject*) +{ + bool bShow = CPythonMiniMap::Instance().CanShow(); + return Py_BuildValue("b", bShow); +} + +PyObject* miniMapScaleUp(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().ScaleUp(); + return Py_BuildNone(); +} + +PyObject* miniMapScaleDown(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().ScaleDown(); + return Py_BuildNone(); +} + +PyObject* miniMapGetInfo(PyObject*, PyObject* poArgs) +{ + float fScrrenX; + if (!PyTuple_GetFloat(poArgs, 0, &fScrrenX)) + return Py_BuildException(); + float fScrrenY; + if (!PyTuple_GetFloat(poArgs, 1, &fScrrenY)) + return Py_BuildException(); + + std::string aString; + // Uninitialised on Windows when nothing is picked; zero here. + float fPosX = 0.0f, fPosY = 0.0f; + uint32_t dwTextColor = 0; + bool bFind = CPythonMiniMap::Instance().GetPickedInstanceInfo(fScrrenX, fScrrenY, aString, &fPosX, &fPosY, &dwTextColor); + int iPosX = FloatToInt(fPosX) / 100; + int iPosY = FloatToInt(fPosY) / 100; + return Py_BuildValue("isiil", (int)bFind, aString.c_str(), iPosX, iPosY, long(int32_t(dwTextColor))); +} + +////////////////////////////////////////////////////////////////////////// +// Atlas +PyObject* miniMapLoadAtlas(PyObject*, PyObject*) +{ + if (!CPythonMiniMap::Instance().LoadAtlas()) + std::cerr << "CPythonMiniMap::Instance().LoadAtlas() Failed\n"; + return Py_BuildNone(); +} + +PyObject* miniMapUpdateAtlas(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().UpdateAtlas(); + return Py_BuildNone(); +} + +PyObject* miniMapRenderAtlas(PyObject*, PyObject* poArgs) +{ + float fScrrenX; + if (!PyTuple_GetFloat(poArgs, 0, &fScrrenX)) + return Py_BuildException(); + float fScrrenY; + if (!PyTuple_GetFloat(poArgs, 1, &fScrrenY)) + return Py_BuildException(); + + CPythonMiniMap::Instance().RenderAtlas(fScrrenX, fScrrenY); + return Py_BuildNone(); +} + +PyObject* miniMapShowAtlas(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().ShowAtlas(); + return Py_BuildNone(); +} + +PyObject* miniMapHideAtlas(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().HideAtlas(); + return Py_BuildNone(); +} + +PyObject* miniMapisShowAtlas(PyObject*, PyObject*) +{ + bool bShow = CPythonMiniMap::Instance().CanShowAtlas(); + return Py_BuildValue("b", bShow); +} + +PyObject* miniMapIsAtlas(PyObject*, PyObject*) +{ + bool isData = CPythonMiniMap::Instance().IsAtlas(); + return Py_BuildValue("b", isData); +} + +PyObject* miniMapGetAtlasInfo(PyObject*, PyObject* poArgs) +{ + float fScrrenX; + if (!PyTuple_GetFloat(poArgs, 0, &fScrrenX)) + return Py_BuildException(); + float fScrrenY; + if (!PyTuple_GetFloat(poArgs, 1, &fScrrenY)) + return Py_BuildException(); + + std::string aString = ""; + float fPosX = 0.0f; + float fPosY = 0.0f; + uint32_t dwTextColor = 0; + uint32_t dwGuildID = 0; + int diRegenTime = 0; + bool bFind = CPythonMiniMap::Instance().GetAtlasInfo(fScrrenX, fScrrenY, aString, &fPosX, &fPosY, &dwTextColor, &dwGuildID, &diRegenTime); + int iPosX = FloatToInt(fPosX) / 100; + int iPosY = FloatToInt(fPosY) / 100; + return Py_BuildValue("isiilii", (int)bFind, aString.c_str(), iPosX, iPosY, long(int32_t(dwTextColor)), int(dwGuildID), diRegenTime); +} + +PyObject* miniMapGetAtlasSize(PyObject*, PyObject*) +{ + // Uninitialised on Windows when the map is not outdoor; zero here. + float fSizeX = 0.0f, fSizeY = 0.0f; + bool bGet = CPythonMiniMap::Instance().GetAtlasSize(&fSizeX, &fSizeY); + + int iSizeX = FloatToInt(fSizeX); + int iSizeY = FloatToInt(fSizeY); + + return Py_BuildValue("bii", (int)bGet, iSizeX, iSizeY); +} + +PyObject* miniMapAddWayPoint(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + float fX; + if (!PyTuple_GetFloat(poArgs, 1, &fX)) + return Py_BuildException(); + + float fY; + if (!PyTuple_GetFloat(poArgs, 2, &fY)) + return Py_BuildException(); + + char* buf; + if (!PyTuple_GetString(poArgs, 3, &buf)) + return Py_BuildException(); + + CPythonMiniMap::Instance().AddWayPoint(CPythonMiniMap::TYPE_WAYPOINT, (uint32_t)iID, fX, fY, buf); + + return Py_BuildNone(); +} + +PyObject* miniMapRemoveWayPoint(PyObject*, PyObject* poArgs) +{ + int iID; + if (!PyTuple_GetInteger(poArgs, 0, &iID)) + return Py_BuildException(); + + CPythonMiniMap::Instance().RemoveWayPoint((uint32_t)iID); + + return Py_BuildNone(); +} + +PyObject* miniMapRegisterAtlasWindow(PyObject*, PyObject* poArgs) +{ + PyObject* poHandler; + if (!PyTuple_GetObject(poArgs, 0, &poHandler)) + return Py_BuildException(); + + CPythonMiniMap::Instance().RegisterAtlasWindow(poHandler); + return Py_BuildNone(); +} + +PyObject* miniMapUnregisterAtlasWindow(PyObject*, PyObject*) +{ + CPythonMiniMap::Instance().UnregisterAtlasWindow(); + return Py_BuildNone(); +} + +PyObject* miniMapGetGuildAreaID(PyObject*, PyObject* poArgs) +{ + float fx; + if (!PyTuple_GetFloat(poArgs, 0, &fx)) + return Py_BuildException(); + float fy; + if (!PyTuple_GetFloat(poArgs, 1, &fy)) + return Py_BuildException(); + + // float -> DWORD argument conversion (truncation; Win32 cvttss2si via int64 for the high range). + uint32_t dwGuildID = CPythonMiniMap::Instance().GetGuildAreaID(uint32_t(int64_t(fx)), uint32_t(int64_t(fy))); + return Py_BuildValue("i", int(dwGuildID)); +} + +} // namespace + +void initMiniMap() +{ + static PyMethodDef s_methods[] = + { + { "SetScale", miniMapSetScale, METH_VARARGS, nullptr }, + { "ScaleUp", miniMapScaleUp, METH_VARARGS, nullptr }, + { "ScaleDown", miniMapScaleDown, METH_VARARGS, nullptr }, + { "SetMiniMapSize", miniMapSetMiniMapSize, METH_VARARGS, nullptr }, + + { "SetCenterPosition", miniMapSetCenterPosition, METH_VARARGS, nullptr }, + + { "Destroy", miniMapDestroy, METH_VARARGS, nullptr }, + { "Create", miniMapCreate, METH_VARARGS, nullptr }, + { "Update", miniMapUpdate, METH_VARARGS, nullptr }, + { "Render", miniMapRender, METH_VARARGS, nullptr }, + + { "Show", miniMapShow, METH_VARARGS, nullptr }, + { "Hide", miniMapHide, METH_VARARGS, nullptr }, + + { "isShow", miniMapisShow, METH_VARARGS, nullptr }, + + { "GetInfo", miniMapGetInfo, METH_VARARGS, nullptr }, + + { "LoadAtlas", miniMapLoadAtlas, METH_VARARGS, nullptr }, + { "UpdateAtlas", miniMapUpdateAtlas, METH_VARARGS, nullptr }, + { "RenderAtlas", miniMapRenderAtlas, METH_VARARGS, nullptr }, + { "ShowAtlas", miniMapShowAtlas, METH_VARARGS, nullptr }, + { "HideAtlas", miniMapHideAtlas, METH_VARARGS, nullptr }, + { "isShowAtlas", miniMapisShowAtlas, METH_VARARGS, nullptr }, + { "IsAtlas", miniMapIsAtlas, METH_VARARGS, nullptr }, + { "GetAtlasInfo", miniMapGetAtlasInfo, METH_VARARGS, nullptr }, + { "GetAtlasSize", miniMapGetAtlasSize, METH_VARARGS, nullptr }, + + { "AddWayPoint", miniMapAddWayPoint, METH_VARARGS, nullptr }, + { "RemoveWayPoint", miniMapRemoveWayPoint, METH_VARARGS, nullptr }, + + { "RegisterAtlasWindow", miniMapRegisterAtlasWindow, METH_VARARGS, nullptr }, + { "UnregisterAtlasWindow", miniMapUnregisterAtlasWindow, METH_VARARGS, nullptr }, + + { "GetGuildAreaID", miniMapGetGuildAreaID, METH_VARARGS, nullptr }, + + { nullptr, nullptr, 0, nullptr }, + }; + + PyObject* poModule = Py_InitModule("miniMap", s_methods); + + PyModule_AddIntConstant(poModule, "TYPE_OPC", CPythonMiniMap::TYPE_OPC); + PyModule_AddIntConstant(poModule, "TYPE_OPCPVP", CPythonMiniMap::TYPE_OPCPVP); + PyModule_AddIntConstant(poModule, "TYPE_OPCPVPSELF", CPythonMiniMap::TYPE_OPCPVPSELF); + PyModule_AddIntConstant(poModule, "TYPE_NPC", CPythonMiniMap::TYPE_NPC); + PyModule_AddIntConstant(poModule, "TYPE_MONSTER", CPythonMiniMap::TYPE_MONSTER); + PyModule_AddIntConstant(poModule, "TYPE_WARP", CPythonMiniMap::TYPE_WARP); + PyModule_AddIntConstant(poModule, "TYPE_WAYPOINT", CPythonMiniMap::TYPE_WAYPOINT); + PyModule_AddIntConstant(poModule, "TYPE_PARTY", CPythonMiniMap::TYPE_PARTY); + PyModule_AddIntConstant(poModule, "TYPE_EMPIRE", CPythonMiniMap::TYPE_EMPIRE); +} + +} // namespace ava2 diff --git a/src/python_minimap.h b/src/python_minimap.h new file mode 100644 index 00000000..35d51709 --- /dev/null +++ b/src/python_minimap.h @@ -0,0 +1,269 @@ +#pragma once +// CPythonMiniMap: the minimap / atlas state behind the "miniMap" module. +// Provenance: AVA2 UserInterface/PythonMiniMap.{h,cpp} and PythonMiniMapModule.cpp, compiled with the +// Locale_inc.h set ENABLE_MINIMAP_WHITEMARK_NEW, NAMECOLOR_BOSS_CLIENT, ENABLE_STONEMINIMAP, +// ENABLE_OFFLINESHOP_SYSTEM and ENABLE_GRAPHIC_ON_OFF; WJ_COMBAT_ZONE is off. +// The D3D minimap texture/vertex pipeline (Create's buffers, Render, RenderAtlas) is not ported: the +// state, mark lists, picking and atlas bookkeeping are, so GetInfo/GetAtlasInfo answer like Windows. +#include +#include "eter_image/GrpImageInstance.h" +#include +#include +#include +#include + +namespace ava2 { + +class CPythonMiniMap +{ +public: + enum + { + EMPIRE_NUM = 4, + + MINI_WAYPOINT_IMAGE_COUNT = 12, + WAYPOINT_IMAGE_COUNT = 15, + TARGET_MARK_IMAGE_COUNT = 2, + }; + enum + { + TYPE_OPC, + TYPE_OPCPVP, + TYPE_OPCPVPSELF, + TYPE_NPC, + TYPE_MONSTER, + TYPE_WARP, + TYPE_WAYPOINT, + TYPE_PARTY, + TYPE_EMPIRE, + TYPE_EMPIRE_END = TYPE_EMPIRE + EMPIRE_NUM, + TYPE_TARGET, + TYPE_COUNT, + }; + + // CTerrainImpl::CELLSCALE / TERRAIN_XSIZE (GameLib/TerrainImpl.h). + static constexpr float CELLSCALE = 200.0f; + static constexpr long TERRAIN_SIZE = 25600; + + static CPythonMiniMap& Instance(); + + void Destroy(); + bool Create(); + + bool IsAtlas(); + bool CanShow(); + bool CanShowAtlas(); + + void SetMiniMapSize(float fWidth, float fHeight); + void SetScale(float fScale); + void ScaleUp(); + void ScaleDown(); + + void SetCenterPosition(float fCenterX, float fCenterY); + + void Update(float fCenterX, float fCenterY); + void Render(float fScreenX, float fScreenY); + + void Show(); + void Hide(); + + bool GetPickedInstanceInfo(float fScreenX, float fScreenY, std::string& rReturnName, float* pReturnPosX, float* pReturnPosY, uint32_t* pdwTextColor); + + // Atlas + bool LoadAtlas(); + void UpdateAtlas(); + void RenderAtlas(float fScreenX, float fScreenY); + void ShowAtlas(); + void HideAtlas(); + + bool GetAtlasInfo(float fScreenX, float fScreenY, std::string& rReturnString, float* pReturnPosX, float* pReturnPosY, uint32_t* pdwTextColor, uint32_t* pdwGuildID, int* pdiRegenTime); + bool GetAtlasSize(float* pfSizeX, float* pfSizeY); + + void AddObserver(uint32_t dwVID, float fSrcX, float fSrcY); + void MoveObserver(uint32_t dwVID, float fDstX, float fDstY); + void RemoveObserver(uint32_t dwVID); + + // WayPoint + void AddWayPoint(uint8_t byType, uint32_t dwID, float fX, float fY, std::string strText, uint32_t dwChrVID = 0); + void RemoveWayPoint(uint32_t dwID); + + // SignalPoint + void AddSignalPoint(float fX, float fY); + void ClearAllSignalPoint(); + + void RegisterAtlasWindow(PyObject* poHandler); + void UnregisterAtlasWindow(); + void OpenAtlasWindow(); + void SetAtlasCenterPosition(int x, int y); + + // NPC List + void ClearAtlasMarkInfo(); + void RegisterAtlasMark(uint8_t byType, uint32_t mobVnum, const char* c_szName, long lx, long ly, int regenTime); + + // Guild + void ClearGuildArea(); + void RegisterGuildArea(uint32_t dwID, uint32_t dwGuildID, long x, long y, long width, long height); + uint32_t GetGuildAreaID(uint32_t x, uint32_t y); + + // Target + void CreateTarget(int iID, const char* c_szName); + void CreateTarget(int iID, const char* c_szName, uint32_t dwVID); + void UpdateTarget(int iID, int ix, int iy); + void DeleteTarget(int iID); + + // ELTimer_GetMSec for the observer interpolation; tests pin it. + void SetTimeSourceForTest(uint32_t (*now)()) { m_now = now; } + + // Test access to what Render would draw. + struct TMarkPosition + { + float m_fX; + float m_fY; + unsigned m_eNameColor; + }; + typedef std::vector TInstanceMarkPositionVector; + struct TestView + { + float scale, radius, centerCellX, centerCellY; + const TInstanceMarkPositionVector *partyPC, *otherPC, *npc, *boss, *metin, *monster, *warp, *offlineShop; + size_t npcMarks, bossMarks, warpMarks, wayPoints, guildAreas, observers; + float atlasMaxX, atlasMaxY; + uint32_t atlasBaseX, atlasBaseY; + }; + TestView GetTestView() const; + // m_fMiniMapX/Y of a TYPE_TARGET waypoint after Update; false when the id is unknown. + bool GetTargetMiniMapPosition(uint32_t dwID, float* pfx, float* pfy) const; + +protected: + CPythonMiniMap(); + + void __Initialize(); + void __SetPosition(); + void __LoadAtlasMarkInfo(); + + void __GlobalPositionToAtlasPosition(long lx, long ly, float* pfx, float* pfy); + +protected: + // Atlas + typedef struct + { + uint8_t m_byType; + uint32_t m_dwID; // For WayPoint + float m_fX; + float m_fY; + float m_fScreenX; + float m_fScreenY; + float m_fMiniMapX; + float m_fMiniMapY; + uint32_t m_dwChrVID; + std::string m_strText; + uint32_t mobVnum; + int regenTime; + } TAtlasMarkInfo; + + // GuildArea + typedef struct + { + uint32_t dwGuildID; + long lx, ly; + long lwidth, lheight; + + float fsxRender, fsyRender; + float fexRender, feyRender; + } TGuildAreaInfo; + + struct SObserver + { + float fCurX; + float fCurY; + float fSrcX; + float fSrcY; + float fDstX; + float fDstY; + + uint32_t dwSrcTime; + uint32_t dwDstTime; + }; + +protected: + bool __GetWayPoint(uint32_t dwID, TAtlasMarkInfo** ppkInfo); + void __UpdateWayPoint(TAtlasMarkInfo* pkInfo, int ix, int iy); + uint32_t __GetMSec() const; + +protected: + float m_fWidth; + float m_fHeight; + + float m_fScale; + + float m_fCenterX; + float m_fCenterY; + + float m_fCenterCellX; + float m_fCenterCellY; + + float m_fScreenX; + float m_fScreenY; + + float m_fMiniMapRadius; + + // 캐릭터 마크 + CGraphicImageInstance m_PlayerMark; + CGraphicImageInstance m_WhiteMark; + CGraphicImageInstance m_BossMark; + + TInstanceMarkPositionVector m_PartyPCPositionVector; + TInstanceMarkPositionVector m_OtherPCPositionVector; + TInstanceMarkPositionVector m_NPCPositionVector; + TInstanceMarkPositionVector m_BossPositionVector; + TInstanceMarkPositionVector m_MetinPositionVector; + TInstanceMarkPositionVector m_MonsterPositionVector; + TInstanceMarkPositionVector m_WarpPositionVector; + TInstanceMarkPositionVector m_OfflineShopPositionVector; + std::map m_kMap_dwVID_kObserver; + + bool m_bAtlas; + bool m_bShow; + + bool m_bShowAtlas; + CGraphicImageInstance m_AtlasImageInstance; + CGraphicImageInstance m_AtlasPlayerMark; + + float m_fAtlasScreenX; + float m_fAtlasScreenY; + + uint32_t m_dwAtlasBaseX; + uint32_t m_dwAtlasBaseY; + + float m_fAtlasMaxX; + float m_fAtlasMaxY; + + float m_fAtlasImageSizeX; + float m_fAtlasImageSizeY; + + typedef std::vector TAtlasMarkInfoVector; + typedef std::vector TGuildAreaInfoVector; + TAtlasMarkInfoVector m_AtlasNPCInfoVector; + TAtlasMarkInfoVector m_AtlasBossInfoVector; + TAtlasMarkInfoVector m_AtlasWarpInfoVector; + + // WayPoint + TAtlasMarkInfoVector m_AtlasWayPointInfoVector; + TGuildAreaInfoVector m_GuildAreaInfoVector; + + // SignalPoint + struct TSignalPoint + { + float x, y; + unsigned int id; + }; + + std::vector m_SignalPointVector; + + PyObject* m_poHandler; + uint32_t (*m_now)() = nullptr; +}; + +void initMiniMap(); + +} // namespace ava2 diff --git a/src/python_native_modules.cpp b/src/python_native_modules.cpp index 952da8d0..05e8cdb3 100644 --- a/src/python_native_modules.cpp +++ b/src/python_native_modules.cpp @@ -1,3 +1,4 @@ +#include "offline_shop_state.h" #include #include #include "Poly.h" @@ -6,9 +7,12 @@ #include #include "skill_description.h" #include "skill_constants.h" +#include "ava2_text_file_loader.h" +#include #include "python_native_modules.h" #include "python_runtime.h" #include "nonplayer_data.h" +#include "shared/common/PythonUtils.h" #include "eter_resource/ResourceManager.h" #include "eter_image/GrpImage.h" #include "eter_image/GrpImageInstance.h" @@ -29,14 +33,56 @@ #include namespace ava2 { -namespace { SkillDescriptions skillDescriptions; } +namespace { +SkillDescriptions skillDescriptions; +// CPythonSkill state the original keeps outside SSkillData (PythonSkill.cpp / GameType.cpp). +const char* const kImagePath="d:/ymir work/ui/"; // g_strImagePath +const uint32_t kSkillIndexRiding=130; // c_iSkillIndex_Riding (PythonPlayerModule.cpp) +// LocaleService_GetCodePage() == MULTI_LOCALE_CODE; no locale.cfg/LocaleService port yet, so its +// initial value. Only RegisterSkill's "%dname" style keys read it. +const int kLocaleCodePage=949; +std::string s_skillPathName; // m_strPathName +uint32_t s_timeIncreaseSkillNumber=0; // SSkillData::ms_dwTimeIncreaseSkillNumber (read only by commented-out code) + +// __RegisterGradeIconImage / __RegisterNormalIconImage, called at RegisterSkillDesc's icon step. +// m_PathNameMap is keyed by the raw, case-sensitive job column. +void register_skill_icons(uint32_t id,SkillDescription& data,const std::string& job,const std::string& icon) { + static const std::map pathNames={{"WARRIOR","warrior"},{"ASSASSIN","assassin"},{"SURA","sura"}, + {"SHAMAN","shaman"},{"PASSIVE","passive"},{"SUPPORT","common/support"},{"GUILD","common/guild"},{"HORSE","common/horse"}}; + auto grade=[&](const char* header) { + for(int j=0;jsecond.c_str()); + switch(data.type) { + case skill_constants::SKILL_TYPE_ACTIVE:grade(header);break; + case skill_constants::SKILL_TYPE_SUPPORT:case skill_constants::SKILL_TYPE_GUILD:case skill_constants::SKILL_TYPE_HORSE:normal(header);break; + } + } +} + +} // namespace bool LoadSkillTable(const std::string& path,bool cheonma) { try { return skillDescriptions.loadTable(ReadPackedText(path),cheonma); } catch(const std::exception&) {return false;} } void ResetSkillDescriptions() { skillDescriptions.records.clear(); } +// CPythonPlayer::__GetSkillType: unknown skill index -> 0 (not SKILL_TYPE_ACTIVE). +int GetSkillTypeById(uint32_t id) { auto* data=skillDescriptions.find(id);return data?data->type:0; } +const SkillDescription* FindSkillDescription(uint32_t id) { return skillDescriptions.find(id); } bool LoadSkillDescriptions(const std::string& path) { - try { return skillDescriptions.load(ReadPackedText(path)); } + try { return skillDescriptions.load(ReadPackedText(path),register_skill_icons); } catch(const std::exception&) { return false; } } namespace { @@ -50,9 +96,6 @@ PyObject* dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 0, 0, PyObject* dummy_tuple4(PyObject*, PyObject*) { return Py_BuildValue("iiii", 0, 0, 0, 0); } PyObject* dummy_bool_false(PyObject*, PyObject*) { return PyBool_FromLong(0); } PyObject* dummy_bool_true(PyObject*, PyObject*) { return PyBool_FromLong(1); } -PyObject* minimap_get_info(PyObject*, PyObject*) { return Py_BuildValue("isiil", 0, "", 0, 0, 0); } -PyObject* minimap_get_atlas_info(PyObject*, PyObject*) { return Py_BuildValue("isiilii", 0, "", 0, 0, 0, 0, 0); } -PyObject* minimap_get_atlas_size(PyObject*, PyObject*) { return Py_BuildValue("bii", 0, 0, 0); } PyObject* dummy_empty_list(PyObject*, PyObject*) { return PyList_New(0); } } // namespace @@ -103,6 +146,22 @@ PyObject* nonplayer_search(PyObject*,PyObject* args) { } return list; } +// nonplayerGetMobResist (nonplayer.GetResist): CPythonNonPlayer::GetMobResist returns the signed +// cResists entry as a DWORD, 0 without a table or for resistNum >= MOB_RESISTS_MAX_NUM. +PyObject* nonplayer_GetResist(PyObject*,PyObject* poArgs) { + int race; + if (!PyTuple_GetInteger(poArgs, 0, &race)) + return Py_BuildException(); + int resistArg; + if (!PyTuple_GetInteger(poArgs, 1, &resistArg)) + return Py_BuildException(); + const uint8_t resistNum = uint8_t(resistArg); + const auto* c_pTable = NonPlayerData::Instance().get(uint32_t(race)); + uint32_t value = 0; + if (c_pTable && resistNum < 11) + value = uint32_t(int32_t(c_pTable->resists[resistNum])); + return Py_BuildValue("i", int(value)); +} PyObject* nonplayer_resist(PyObject*,PyObject* args) { int vnum,index;if(!PyArg_ParseTuple(args,"ii",&vnum,&index)) return nullptr; const auto* m=NonPlayerData::Instance().get(uint32_t(vnum)); @@ -132,7 +191,7 @@ void initNonPlayer() { {"GetMobRegenPercent", nonplayer_value<11>, METH_VARARGS, nullptr}, {"GetMobGoldMin", nonplayer_value<12>, METH_VARARGS, nullptr}, {"GetMobGoldMax", nonplayer_value<13>, METH_VARARGS, nullptr}, - {"GetResist", dummy_zero, METH_VARARGS, nullptr}, + {"GetResist", nonplayer_GetResist, METH_VARARGS, nullptr}, {"LoadNonPlayerData", nonplayer_load, METH_VARARGS, nullptr}, {"GetMonsterPrice", nonplayer_value<14>, METH_VARARGS, nullptr}, {"GetMobsByName", nonplayer_search, METH_VARARGS, nullptr}, @@ -587,51 +646,6 @@ void initTextTail() { auto* module = Py_InitModule("textTail", methods); } -void initMiniMap() { - static PyMethodDef methods[] = { - {"SetScale", dummy_none, METH_VARARGS, nullptr}, - {"ScaleUp", dummy_none, METH_VARARGS, nullptr}, - {"ScaleDown", dummy_none, METH_VARARGS, nullptr}, - {"SetMiniMapSize", dummy_none, METH_VARARGS, nullptr}, - {"SetCenterPosition", dummy_none, METH_VARARGS, nullptr}, - {"Destroy", dummy_none, METH_VARARGS, nullptr}, - {"Create", dummy_none, METH_VARARGS, nullptr}, - {"Update", dummy_none, METH_VARARGS, nullptr}, - {"Render", dummy_none, METH_VARARGS, nullptr}, - {"Show", dummy_none, METH_VARARGS, nullptr}, - {"Hide", dummy_none, METH_VARARGS, nullptr}, - {"isShow", dummy_bool_false, METH_VARARGS, nullptr}, - {"GetInfo", minimap_get_info, METH_VARARGS, nullptr}, - {"LoadAtlas", dummy_none, METH_VARARGS, nullptr}, - {"UpdateAtlas", dummy_none, METH_VARARGS, nullptr}, - {"RenderAtlas", dummy_none, METH_VARARGS, nullptr}, - {"ShowAtlas", dummy_none, METH_VARARGS, nullptr}, - {"HideAtlas", dummy_none, METH_VARARGS, nullptr}, - {"isShowAtlas", dummy_bool_false, METH_VARARGS, nullptr}, - {"IsAtlas", dummy_bool_false, METH_VARARGS, nullptr}, - {"GetAtlasInfo", minimap_get_atlas_info, METH_VARARGS, nullptr}, - {"GetAtlasSize", minimap_get_atlas_size, METH_VARARGS, nullptr}, - {"AddWayPoint", dummy_none, METH_VARARGS, nullptr}, - {"RemoveWayPoint", dummy_none, METH_VARARGS, nullptr}, - {"RegisterAtlasWindow", dummy_none, METH_VARARGS, nullptr}, - {"UnregisterAtlasWindow", dummy_none, METH_VARARGS, nullptr}, - {"GetGuildAreaID", dummy_zero, METH_VARARGS, nullptr}, - {"RegisterColor", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("miniMap", methods); - if (!module) return; - PyModule_AddIntConstant(module, "TYPE_OPC", 0); - PyModule_AddIntConstant(module, "TYPE_OPCPVP", 1); - PyModule_AddIntConstant(module, "TYPE_OPCPVPSELF", 2); - PyModule_AddIntConstant(module, "TYPE_NPC", 3); - PyModule_AddIntConstant(module, "TYPE_MONSTER", 4); - PyModule_AddIntConstant(module, "TYPE_WARP", 5); - PyModule_AddIntConstant(module, "TYPE_WAYPOINT", 6); - PyModule_AddIntConstant(module, "TYPE_PARTY", 7); - PyModule_AddIntConstant(module, "TYPE_EMPIRE", 8); -} - void initProfiler() { static PyMethodDef methods[] = { {"Push", dummy_none, METH_VARARGS, nullptr}, @@ -641,180 +655,6 @@ void initProfiler() { auto* module = Py_InitModule("profiler", methods); } -struct EventSetState { - int id = 0; - int width = 300; - int localY = 0; - int lineCount = 0; - int lineHeight = 16; - int visibleLineCount = 14; - int visibleStartLine = 0; - int selectedAnswer = -1; - int restrictedCount = 60; - PyObject* handler = nullptr; - std::vector lines; -}; -static std::unordered_map s_eventSets; -static int s_nextEventSet = 0; - -static PyObject* event_RegisterEventSet(PyObject*, PyObject*) { - int id = ++s_nextEventSet; - EventSetState es; - es.id = id; - s_eventSets[id] = es; - return Py_BuildValue("i", id); -} - -static PyObject* event_ClearEventSet(PyObject*, PyObject* args) { - int id = 0; - if (PyArg_ParseTuple(args, "i", &id)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) { - it->second.localY = 0; - it->second.lineCount = 0; - it->second.lines.clear(); - it->second.selectedAnswer = -1; - } - } - Py_RETURN_NONE; -} - -static PyObject* event_SetRestrictedCount(PyObject*, PyObject* args) { - int id = 0, count = 0; - if (PyArg_ParseTuple(args, "ii", &id, &count)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) it->second.restrictedCount = count; - } - Py_RETURN_NONE; -} - -static PyObject* event_GetEventSetLocalYPosition(PyObject*, PyObject* args) { - int id = 0; - if (PyArg_ParseTuple(args, "i", &id)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) return Py_BuildValue("i", it->second.localY); - } - return Py_BuildValue("i", 0); -} - -static PyObject* event_AddEventSetLocalYPosition(PyObject*, PyObject* args) { - int id = 0, dy = 0; - if (PyArg_ParseTuple(args, "ii", &id, &dy)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) it->second.localY += dy; - } - Py_RETURN_NONE; -} - -static PyObject* event_InsertText(PyObject*, PyObject* args) { - int id = 0; - const char* text = nullptr; - if (PyArg_ParseTuple(args, "is", &id, &text)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) { - it->second.lines.push_back(text ? text : ""); - it->second.lineCount++; - it->second.localY += it->second.lineHeight; - } - } - Py_RETURN_NONE; -} - -static PyObject* event_InsertTextInline(PyObject*, PyObject* args) { - return event_InsertText(nullptr, args); -} - -static PyObject* event_SetEventSetWidth(PyObject*, PyObject* args) { - int id = 0, width = 0; - if (PyArg_ParseTuple(args, "ii", &id, &width)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) it->second.width = width; - } - Py_RETURN_NONE; -} - -static PyObject* event_GetLineCount(PyObject*, PyObject* args) { - int id = 0; - if (PyArg_ParseTuple(args, "i", &id)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) return Py_BuildValue("i", it->second.lineCount); - } - return Py_BuildValue("i", 0); -} - -static PyObject* event_GetLineHeight(PyObject*, PyObject* args) { - int id = 0; - if (PyArg_ParseTuple(args, "i", &id)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) return Py_BuildValue("i", it->second.lineHeight); - } - return Py_BuildValue("i", 16); -} - -static PyObject* event_SelectAnswer(PyObject*, PyObject* args) { - int id = 0, answer = 0; - if (PyArg_ParseTuple(args, "ii", &id, &answer)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) it->second.selectedAnswer = answer; - PythonNetworkStream::Instance().SendScriptAnswerPacket(answer); - } - Py_RETURN_NONE; -} - -static PyObject* event_SetEventHandler(PyObject*, PyObject* args) { - int id = 0; - PyObject* handler = nullptr; - if (PyArg_ParseTuple(args, "iO", &id, &handler)) { - auto it = s_eventSets.find(id); - if (it != s_eventSets.end()) { - Py_XINCREF(handler); - if (it->second.handler) Py_XDECREF(it->second.handler); - it->second.handler = handler; - } - } - Py_RETURN_NONE; -} - -void initEvent() { - static PyMethodDef methods[] = { - {"RegisterEventSet", event_RegisterEventSet, METH_VARARGS, nullptr}, - {"RegisterEventSetFromString", event_RegisterEventSet, METH_VARARGS, nullptr}, - {"ClearEventSet", event_ClearEventSet, METH_VARARGS, nullptr}, - {"SetRestrictedCount", event_SetRestrictedCount, METH_VARARGS, nullptr}, - {"GetEventSetLocalYPosition", event_GetEventSetLocalYPosition, METH_VARARGS, nullptr}, - {"AddEventSetLocalYPosition", event_AddEventSetLocalYPosition, METH_VARARGS, nullptr}, - {"InsertText", event_InsertText, METH_VARARGS, nullptr}, - {"InsertTextInline", event_InsertTextInline, METH_VARARGS, nullptr}, - {"UpdateEventSet", dummy_none, METH_VARARGS, nullptr}, - {"SetVisibleLineCount", dummy_none, METH_VARARGS, nullptr}, - {"RenderEventSet", dummy_none, METH_VARARGS, nullptr}, - {"SetEventSetWidth", event_SetEventSetWidth, METH_VARARGS, nullptr}, - {"Skip", dummy_none, METH_VARARGS, nullptr}, - {"IsWait", dummy_zero, METH_VARARGS, nullptr}, - {"EndEventProcess", dummy_none, METH_VARARGS, nullptr}, - {"SelectAnswer", event_SelectAnswer, METH_VARARGS, nullptr}, - {"GetLineCount", event_GetLineCount, METH_VARARGS, nullptr}, - {"SetVisibleStartLine", dummy_none, METH_VARARGS, nullptr}, - {"GetVisibleStartLine", dummy_zero, METH_VARARGS, nullptr}, - {"SetEventHandler", event_SetEventHandler, METH_VARARGS, nullptr}, - {"SetInterfaceWindow", dummy_none, METH_VARARGS, nullptr}, - {"SetLeftTimeString", dummy_none, METH_VARARGS, nullptr}, - {"QuestButtonClick", dummy_none, METH_VARARGS, nullptr}, - {"Destroy", dummy_none, METH_VARARGS, nullptr}, - {"GetLineHeight", event_GetLineHeight, METH_VARARGS, nullptr}, - {"SetYPosition", dummy_none, METH_VARARGS, nullptr}, - {"GetProcessedLineCount", event_GetLineCount, METH_VARARGS, nullptr}, - {"AllProcessEventSet", dummy_none, METH_VARARGS, nullptr}, - {"AddEvent", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("event", methods); - PyModule_AddIntConstant(module, "BOX_VISIBLE_LINE_COUNT", 14); - PyModule_AddIntConstant(module, "BUTTON_TYPE_CANCEL", 0); - PyModule_AddIntConstant(module, "BUTTON_TYPE_DONE", 1); - PyModule_AddIntConstant(module, "BUTTON_TYPE_NEXT", 2); -} - static PyObject* effect_RegisterEffect(PyObject*, PyObject* args) { const char* filename = nullptr; if (!PyArg_ParseTuple(args, "s", &filename)) { @@ -1010,8 +850,9 @@ PyObject* shop_tab_coin(PyObject*,PyObject* args) { return PyInt_FromLong(tab(index/40); if(tab<3)shopItems[tab*40+index%40]=item; @@ -1037,33 +878,6 @@ void initshop() { {"GetTabCoinType", shop_tab_coin, METH_VARARGS, nullptr}, {"GetVnumBuy", shop_item_buy_vnum, METH_VARARGS, nullptr}, {"GetCountBuy", shop_item_buy_count, METH_VARARGS, nullptr}, - {"IsOfflineShop", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopItemID", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopItemCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopItemVnum", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopItemPrice", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopItemMetinSocket", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopItemAttribute", dummy_zero, METH_VARARGS, nullptr}, - {"GetSign", dummy_zero, METH_VARARGS, nullptr}, - {"ClearOfflineShopStock", dummy_none, METH_VARARGS, nullptr}, - {"AddOfflineShopItemStock", dummy_none, METH_VARARGS, nullptr}, - {"DelOfflineShopItemStock", dummy_none, METH_VARARGS, nullptr}, - {"GetOfflineShopItemPriceReal", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopItemStatus", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopItemBuyerName", dummy_str, METH_VARARGS, nullptr}, - {"BuildOfflineShop", dummy_none, METH_VARARGS, nullptr}, - {"GetDisplayedCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetOfflineShopID", dummy_zero, METH_VARARGS, nullptr}, - {"GetCurrentOfflineShopMoney", dummy_zero, METH_VARARGS, nullptr}, - {"HasOfflineShop", dummy_none, METH_VARARGS, nullptr}, - {"GetRealWatcherCount", dummy_zero, METH_VARARGS, nullptr}, - {"ChangeDecoration", dummy_none, METH_VARARGS, nullptr}, - {"GetShopFlag", dummy_zero, METH_VARARGS, nullptr}, - {"SetShopFlag", dummy_none, METH_VARARGS, nullptr}, - {"GetShopType", dummy_zero, METH_VARARGS, nullptr}, - {"SetShopType", dummy_none, METH_VARARGS, nullptr}, - {"GetShopTime", dummy_zero, METH_VARARGS, nullptr}, - {"SetShopTime", dummy_none, METH_VARARGS, nullptr}, {"GetItemRandomAttribute", shop_item_glove, METH_VARARGS, nullptr}, {"GetOfflineShopItemTransmutation", dummy_zero, METH_VARARGS, nullptr}, {"GetItemElements", dummy_tuple4, METH_VARARGS, nullptr}, @@ -1075,87 +889,255 @@ void initshop() { PyModule_AddIntConstant(module, "SHOP_COIN_TYPE_SECONDARY_COIN", 1); PyModule_AddIntConstant(module, "SHOP_COIN_TYPE_COMBAT_ZONE", 2); PyModule_AddIntConstant(module, "OFFLINE_SHOP_SLOT_COUNT", 80); + InitOfflineShopMethods(); } namespace { -static PyObject* skill_GetIconImageNew(PyObject*, PyObject* args) { - int skillIndex = 0; - int skillGrade = 0; - if (!PyArg_ParseTuple(args, "ii", &skillIndex, &skillGrade)) - return Py_BuildValue("i", 0); - - static std::unordered_map> skillMap; - if (skillMap.empty()) { - std::vector paths = { - "locale/en/skilldesc.txt", - "../locale/en/skilldesc.txt", - "build/dev/locale/en/skilldesc.txt" - }; - for (const auto& path : paths) { - std::ifstream f(path); - if (f.is_open()) { - std::string line; - while (std::getline(f, line)) { - std::stringstream ss(line); - std::string item; - std::vector tokens; - while (std::getline(ss, item, '\t')) { - tokens.push_back(item); - } - if (tokens.size() >= 13 && !tokens[0].empty() && std::isdigit(tokens[0][0])) { - try { - int idx = std::stoi(tokens[0]); - std::string job = tokens[1]; - for (auto& c : job) c = (char)std::tolower(c); - std::string icon = tokens[12]; - while (!icon.empty() && (icon.back() == '\r' || icon.back() == ' ')) icon.pop_back(); - if (!icon.empty()) { - skillMap[idx] = { job, icon }; - } - } catch (...) {} - } - } - break; - } - } - if (skillMap.empty()) { - skillMap[1] = { "warrior", "samyeon" }; - skillMap[2] = { "warrior", "palbang" }; - skillMap[3] = { "warrior", "jeongwi" }; - skillMap[4] = { "warrior", "geomgyeong" }; - skillMap[5] = { "warrior", "tanhwan" }; - skillMap[6] = { "warrior", "gihyeol" }; - } - } - - auto it = skillMap.find(skillIndex); - if (it == skillMap.end()) - return Py_BuildValue("i", 0); - - int gradeSuffix = (skillGrade >= 2) ? 3 : (skillGrade == 1 ? 2 : 1); - char buf[256]; - std::snprintf(buf, sizeof(buf), "d:/ymir work/ui/skill/%s/%s_%02d.sub", - it->second.first.c_str(), it->second.second.c_str(), gradeSuffix); - - CResource* pRes = CResourceManager::Instance().GetResourcePointer(buf); - if (!pRes || !pRes->IsType(CGraphicImage::Type())) { - std::snprintf(buf, sizeof(buf), "ymir work/ui/skill/%s/%s_01.sub", - it->second.first.c_str(), it->second.second.c_str()); - pRes = CResourceManager::Instance().GetResourcePointer(buf); - } - - if (pRes && pRes->IsType(CGraphicImage::Type())) { - uint32_t handle = GrpRegisterImageHandle(static_cast(pRes)); - return Py_BuildValue("i", (int)handle); - } - return Py_BuildValue("i", 0); -} - static const SkillDescription* require_skill(int id,const char* method) { auto* data=skillDescriptions.find(uint32_t(id)); if(!data)PyErr_Format(PyExc_RuntimeError,"skill.%s - Failed to find skill by %d",method,id); return data; } +// CGraphicImage* as Python sees it: the cross-platform image handle, 0 for NULL. +CGraphicImage* skill_image(const std::string& file) { + if(file.empty())return nullptr; + auto* resource=CResourceManager::Instance().GetResourcePointer(file.c_str()); + return resource&&resource->IsType(CGraphicImage::Type())?static_cast(resource):nullptr; +} +PyObject* image_handle(const std::string& file) { return PyInt_FromLong(long(GrpRegisterImageHandle(skill_image(file)))); } +PyObject* image_instance_handle(const std::string& file) { + CGraphicImageInstance* instance=CGraphicImageInstance::New(); + instance->SetImagePointer(skill_image(file)); + return PyInt_FromLong(long(GrpRegisterImageInstanceHandle(instance))); +} +int clamp_grade(int grade) { return grade<0?0:grade>=skill_constants::SKILL_GRADE_COUNT?skill_constants::SKILL_GRADE_COUNT-1:grade; } + +// CPythonSkill::GetSkillDataByName: first skill (by index) whose name matches. +const SkillDescription* skill_by_name(const std::string& name) { + for(const auto& [id,data]:skillDescriptions.records)if(data.name==name)return &data; + return nullptr; +} + +// CPythonSkill::RegisterSkill: a per-skill CTextFileLoader file. std::map::insert keeps an +// existing entry; the time-increase number is still updated. +bool register_skill_file(uint32_t index,const std::string& fileName) { + std::string text; + try { text=ReadPackedText(fileName); } catch(const std::exception&) { return false; } + TextFileLoader loader; + if(!loader.load(text))return false; + loader.setTop(); + const std::string cp=std::to_string(kLocaleCodePage); + SkillDescription data;data.skillIndex=index;data.type=skill_constants::SKILL_TYPE_ACTIVE; + std::string type; + if(!loader.tokenString("type",&type))return false; + ava2Lowers(type); + auto typeIt=SkillDescriptions::typeMap().find(type); + if(typeIt==SkillDescriptions::typeMap().end())return false; + data.type=typeIt->second; + if(auto* tokens=loader.tokenVector("attribute")) + for(const auto& token:*tokens) { + const auto& names=SkillDescriptions::attributeNames(); + for(size_t bit=0;bitsecond; + } + if(!loader.tokenString(cp+"name",&data.name)&&!loader.tokenString("name",&data.name))return false; + if(!loader.tokenString(cp+"description",&data.description))loader.tokenString("description",&data.description); + if(!loader.tokenString("iconfilename",&data.iconFileName))return false; + const auto* conditions=loader.tokenVector(cp+"conditiondata"); + if(!conditions)conditions=loader.tokenVector("conditiondata"); + if(conditions)data.conditions=*conditions; + const auto* affects=loader.tokenVector(cp+"affectdata"); + if(!affects)affects=loader.tokenVector("affectdata"); + if(affects) { + data.affects.clear(); + for(size_t i=0;isize()/3;++i)data.affects.push_back({(*affects)[i*3],(*affects)[i*3+1],(*affects)[i*3+2]}); + } + if(const auto* grades=loader.tokenVector(cp+"gradedata")) + for(size_t i=0;i(skill_constants::SKILL_GRADE_COUNT,grades->size()/2);++i) { + data.gradeNames[i]=(*grades)[i*2]; + data.gradeImageFiles[i]=kImagePath+(*grades)[i*2+1]; + } + loader.tokenString("cooltimeformula",&data.cooldownFormula); + loader.tokenString("targetcountformula",&data.targetCountFormula); + loader.tokenString("motionloopcountformula",&data.motionLoopCountFormula); + loader.tokenString("needspformula",&data.needSPFormula); + loader.tokenString("continuationspformula",&data.continuationSPFormula); + int value; + if(loader.tokenInteger("range",&value))data.targetRange=uint32_t(value); + if(loader.tokenInteger("maxlevel",&value))data.maxLevel=uint8_t(value); + if(loader.tokenInteger("leveluppoint",&value))data.levelUpPoint=uint8_t(value); + data.motion=loader.tokenInteger("motionindex",&value)?uint16_t(value):0; + data.motionForMe=loader.tokenInteger("motionindexforme",&value)?uint16_t(value):0; + data.iconFileName=kImagePath+data.iconFileName; + data.imageFile=data.iconFileName; + const bool timeIncrease=(data.attributes&(1u<<15))!=0; // SKILL_ATTRIBUTE_TIME_INCREASE_SKILL + skillDescriptions.records.insert({index,std::move(data)}); + if(timeIncrease)s_timeIncreaseSkillNumber=index; + return true; +} + +// CPythonSkill::TEST: dumps every skill as a skilldesc-style row to test.txt in the working directory. +void dump_skill_test() { + std::FILE* file=std::fopen("test.txt","w"); + if(!file)return; // the original fprintf()s through a NULL FILE* + std::map attributeMap; + for(size_t bit=0;biti)line+=data.conditions[i];} + line+="\t"+joined(attributeMap,data.attributes); + line+="\t"+joined(SkillDescriptions::weaponMap(),data.needWeapon); + line+="\t"; + std::string iconName=data.iconFileName; + const int pos=int(iconName.find_last_of('/')); + if(pos>0)iconName=iconName.substr(pos+1,iconName.size()-pos-4-1); + line+=iconName; + line+="\t"+std::to_string(data.motion); + line+="\t"; + if(data.motionForMe>1)line+=std::to_string(data.motionForMe); + for(size_t i=0;i<3;++i) { + line+="\t"; + if(data.affects.size()>i)line+=data.affects[i].description+"\t"+data.affects[i].minFormula+"\t"+data.affects[i].maxFormula; + } + std::fprintf(file,"%s\n",line.c_str()); + } + std::fclose(file); +} + +PyObject* skill_SetPathName(PyObject*,PyObject* args) { + char* path;if(!PyTuple_GetString(args,0,&path))return Py_BadArgument(); + s_skillPathName=path;Py_RETURN_NONE; +} +PyObject* skill_RegisterSkill(PyObject*,PyObject* args) { + int index;char* fileName; + if(!PyTuple_GetInteger(args,0,&index)||!PyTuple_GetString(args,1,&fileName))return Py_BadArgument(); + const std::string full=s_skillPathName+fileName; + if(!register_skill_file(uint32_t(index),full)) { + PyErr_Format(PyExc_RuntimeError,"skill.RegisterSkill - Failed to find skill data file : %d, %s",index,full.c_str()); + return nullptr; + } + Py_RETURN_NONE; +} +PyObject* skill_ClearSkillData(PyObject*,PyObject*) { s_timeIncreaseSkillNumber=0;Py_RETURN_NONE; } +PyObject* skill_TEST(PyObject*,PyObject*) { dump_skill_test();Py_RETURN_NONE; } +// The skill argument every lookup below starts with; Py_BadArgument on a non-int. +const SkillDescription* skill_arg(PyObject* args,const char* method) { + int id;if(!PyTuple_GetInteger(args,0,&id))return Py_BadArgument(),nullptr; + return require_skill(id,method); +} +// No AVA2 loader ever sets SSkillData::isRequirement, strRequireSkillName, byRequireSkillLevel or +// RequireStatDataVector (constructor: FALSE / "" / 0 / empty), so the requirement branches below +// reduce to their constructor-state results; CPythonPlayer is never consulted. +PyObject* skill_IsSkillRequirement(PyObject*,PyObject* args) { + if(!skill_arg(args,"IsSkillRequirement"))return nullptr; + return PyInt_FromLong(0); +} +PyObject* skill_GetSkillRequirementData(PyObject*,PyObject* args) { + auto* data=skill_arg(args,"GetSkillRequirementData");if(!data)return nullptr; + auto* required=skill_by_name(""); // strRequireSkillName + // Original: Py_BuildValue("si", 0, "None", 0) -> (None,
); the address is 0 here. + if(!required)return Py_BuildValue("Oi",Py_None,0); + // ceil(byRequireSkillLevel / max(1, byLevelUpPoint)) with byRequireSkillLevel == 0. + return Py_BuildValue("si","",int(std::ceil(0.0f/float(std::max(1,required->levelUpPoint))))); +} +PyObject* skill_GetSkillRequireStatCount(PyObject*,PyObject* args) { + if(!skill_arg(args,"GetSkillRequireStatCount"))return nullptr; + return PyInt_FromLong(0); +} +PyObject* skill_GetSkillRequireStatData(PyObject*,PyObject* args) { + int id,stat; + if(!PyTuple_GetInteger(args,0,&id)||!PyTuple_GetInteger(args,1,&stat))return Py_BadArgument(); + if(!require_skill(id,"GetSkillRequireStatData"))return nullptr; + return Py_BuildValue("ii",0,0); // iStatIndex >= RequireStatDataVector.size() for every index +} +PyObject* skill_CanLevelUpSkill(PyObject*,PyObject* args) { + int id,level; + if(!PyTuple_GetInteger(args,0,&id)||!PyTuple_GetInteger(args,1,&level))return Py_BadArgument(); + auto* data=require_skill(id,"CanLevelUpSkill");if(!data)return nullptr; + if(level>=data->maxLevel)return PyInt_FromLong(0); + if(data->attributes&(1u<<18))return PyInt_FromLong(0); // SKILL_ATTRIBUTE_CANNOT_LEVEL_UP + return PyInt_FromLong(1); +} +PyObject* skill_IsLevelUpSkill(PyObject*,PyObject* args) { + if(!skill_arg(args,"IsLevelUpSkill"))return nullptr; + return PyInt_FromLong(1); +} +PyObject* skill_CheckRequirementSueccess(PyObject*,PyObject* args) { + if(!skill_arg(args,"CheckRequirementSueccess"))return nullptr; + return PyInt_FromLong(1); +} +PyObject* skill_GetNeedCharacterLevel(PyObject*,PyObject* args) { + if(!skill_arg(args,"GetNeedCharacterLevel"))return nullptr; + return PyInt_FromLong(0); // no POINT_LEVEL entry in an empty RequireStatDataVector +} +PyObject* skill_CanUseSkill(PyObject*,PyObject* args) { + auto* data=skill_arg(args,"CanUseSkill");if(!data)return nullptr; + return PyInt_FromLong((data->attributes&(1u<<17))==0); // IsCanUseSkill: !SKILL_ATTRIBUTE_PASSIVE +} +PyObject* skill_GetIconName(PyObject*,PyObject* args) { + int id;if(!PyTuple_GetInteger(args,0,&id))return Py_BadArgument(); + auto* data=skillDescriptions.find(uint32_t(id)); + return PyString_FromString(data?data->iconFileName.c_str():""); +} +PyObject* skill_GetIconImage(PyObject*,PyObject* args) { + int id;if(!PyTuple_GetInteger(args,0,&id))return Py_BadArgument(); + auto* data=skillDescriptions.find(uint32_t(id)); + if(!data)return PyInt_FromLong(0); // 0 instead of an exception + return image_handle(data->imageFile); +} +PyObject* skill_GetIconImageNew(PyObject*,PyObject* args) { + int id,grade; + if(!PyTuple_GetInteger(args,0,&id)||!PyTuple_GetInteger(args,1,&grade))return Py_BadArgument(); + auto* data=skillDescriptions.find(uint32_t(id)); + if(!data)return PyInt_FromLong(0); + return image_handle(data->gradeImageFiles[clamp_grade(grade)]); +} +PyObject* skill_GetIconInstance(PyObject*,PyObject* args) { + auto* data=skill_arg(args,"GetIconInstance");if(!data)return nullptr; + return image_instance_handle(data->imageFile); +} +PyObject* skill_GetIconInstanceNew(PyObject*,PyObject* args) { + int id,grade; + if(!PyTuple_GetInteger(args,0,&id)||!PyTuple_GetInteger(args,1,&grade))return Py_BadArgument(); + auto* data=require_skill(id,"GetIconInstanceNew");if(!data)return nullptr; + return image_instance_handle(data->gradeImageFiles[clamp_grade(grade)]); +} +PyObject* skill_DeleteIconInstance(PyObject*,PyObject* args) { + int handle;if(!PyTuple_GetInteger(args,0,&handle))return Py_BadArgument(); + // Unknown handles are ignored (the original deletes whatever the int points at). + CGraphicImageInstance::Delete(GrpReleaseImageInstanceHandle(uint32_t(handle))); + Py_RETURN_NONE; +} +PyObject* skill_GetGradeData(PyObject*,PyObject* args) { + int id,grade; + if(!PyTuple_GetInteger(args,0,&id)||!PyTuple_GetInteger(args,1,&grade))return Py_BadArgument(); + auto* data=require_skill(id,"GetGradeData");if(!data)return nullptr; + if(grade<0||grade>=skill_constants::SKILL_GRADE_COUNT) { + // The format prints the skill index (the grade argument is unused). + PyErr_Format(PyExc_RuntimeError,"Strange grade index [%d]",id);return nullptr; + } + // Py_BuildValue("i", GradeData[i]) passes the TGradeData struct through varargs; "i" reads its + // first four bytes, the start of the MSVC x86 std::string strName: the inline buffer for names + // shorter than 16 bytes (bytes past the terminator read as 0 here) or a heap pointer (0 here). + const std::string& name=data->gradeNames[grade]; + uint32_t value=0; + if(name.size()<16)for(size_t i=0;i<4&&i(value)); +} +// ENABLE_NEW_PET_SYSTEM: any image resource by file name. +PyObject* skill_GetIconImageNewEx(PyObject*,PyObject* args) { + char* file;if(!PyTuple_GetString(args,0,&file))return Py_BadArgument(); + return image_handle(file); +} static PyObject* skill_name(PyObject*,PyObject* args) { int id,grade=-1;if(!PyArg_ParseTuple(args,"i|i",&id,&grade))return nullptr; auto* data=skillDescriptions.find(uint32_t(id)); @@ -1277,10 +1259,10 @@ float EvaluateSkillFormula(const std::string& formula,float level) {return skill void initskill() { static PyMethodDef methods[] = { - {"SetPathName", dummy_none, METH_VARARGS, nullptr}, - {"RegisterSkill", dummy_none, METH_VARARGS, nullptr}, + {"SetPathName", skill_SetPathName, METH_VARARGS, nullptr}, + {"RegisterSkill", skill_RegisterSkill, METH_VARARGS, nullptr}, {"LoadSkillData", dummy_none, METH_VARARGS, nullptr}, - {"ClearSkillData", dummy_none, METH_VARARGS, nullptr}, + {"ClearSkillData", skill_ClearSkillData, METH_VARARGS, nullptr}, {"GetSkillName", skill_name, METH_VARARGS, nullptr}, {"GetSkillDescription", skill_description, METH_VARARGS, nullptr}, {"GetSkillType", skill_type, METH_VARARGS, nullptr}, @@ -1294,30 +1276,30 @@ void initskill() { {"GetSkillMaxLevel", skill_max_level, METH_VARARGS, nullptr}, {"GetSkillLevelUpPoint", skill_level_up, METH_VARARGS, nullptr}, {"GetSkillLevelLimit", skill_level_limit, METH_VARARGS, nullptr}, - {"IsSkillRequirement", dummy_zero, METH_VARARGS, nullptr}, - {"GetSkillRequirementData", dummy_zero, METH_VARARGS, nullptr}, - {"GetSkillRequireStatCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetSkillRequireStatData", dummy_zero, METH_VARARGS, nullptr}, - {"CanLevelUpSkill", dummy_none, METH_VARARGS, nullptr}, - {"IsLevelUpSkill", dummy_zero, METH_VARARGS, nullptr}, - {"CheckRequirementSueccess", dummy_none, METH_VARARGS, nullptr}, - {"GetNeedCharacterLevel", dummy_zero, METH_VARARGS, nullptr}, + {"IsSkillRequirement", skill_IsSkillRequirement, METH_VARARGS, nullptr}, + {"GetSkillRequirementData", skill_GetSkillRequirementData, METH_VARARGS, nullptr}, + {"GetSkillRequireStatCount", skill_GetSkillRequireStatCount, METH_VARARGS, nullptr}, + {"GetSkillRequireStatData", skill_GetSkillRequireStatData, METH_VARARGS, nullptr}, + {"CanLevelUpSkill", skill_CanLevelUpSkill, METH_VARARGS, nullptr}, + {"IsLevelUpSkill", skill_IsLevelUpSkill, METH_VARARGS, nullptr}, + {"CheckRequirementSueccess", skill_CheckRequirementSueccess, METH_VARARGS, nullptr}, + {"GetNeedCharacterLevel", skill_GetNeedCharacterLevel, METH_VARARGS, nullptr}, {"IsToggleSkill", skill_IsToggleSkill, METH_VARARGS, nullptr}, {"IsUseHPSkill", skill_IsUseHPSkill, METH_VARARGS, nullptr}, {"IsStandingSkill", skill_IsStandingSkill, METH_VARARGS, nullptr}, - {"CanUseSkill", dummy_none, METH_VARARGS, nullptr}, - {"GetIconName", dummy_str, METH_VARARGS, nullptr}, - {"GetIconImage", dummy_zero, METH_VARARGS, nullptr}, + {"CanUseSkill", skill_CanUseSkill, METH_VARARGS, nullptr}, + {"GetIconName", skill_GetIconName, METH_VARARGS, nullptr}, + {"GetIconImage", skill_GetIconImage, METH_VARARGS, nullptr}, {"GetIconImageNew", skill_GetIconImageNew, METH_VARARGS, nullptr}, - {"GetIconInstance", dummy_zero, METH_VARARGS, nullptr}, - {"GetIconInstanceNew", dummy_zero, METH_VARARGS, nullptr}, - {"DeleteIconInstance", dummy_none, METH_VARARGS, nullptr}, - {"GetGradeData", dummy_zero, METH_VARARGS, nullptr}, - {"GetIconImageNewEx", dummy_zero, METH_VARARGS, nullptr}, + {"GetIconInstance", skill_GetIconInstance, METH_VARARGS, nullptr}, + {"GetIconInstanceNew", skill_GetIconInstanceNew, METH_VARARGS, nullptr}, + {"DeleteIconInstance", skill_DeleteIconInstance, METH_VARARGS, nullptr}, + {"GetGradeData", skill_GetGradeData, METH_VARARGS, nullptr}, + {"GetIconImageNewEx", skill_GetIconImageNewEx, METH_VARARGS, nullptr}, {"GetNewAffectDataCount", skill_new_affect_count, METH_VARARGS, nullptr}, {"GetNewAffectData", skill_new_affect, METH_VARARGS, nullptr}, {"GetDuration", skill_duration, METH_VARARGS, nullptr}, - {"TEST", dummy_none, METH_VARARGS, nullptr}, + {"TEST", skill_TEST, METH_VARARGS, nullptr}, {nullptr, nullptr, 0, nullptr} }; auto* module = Py_InitModule("skill", methods); @@ -1333,43 +1315,6 @@ void initskill() { PyModule_AddIntConstant(module, "SKILL_EFFECT_COUNT", skill_constants::SKILL_EFFECT_COUNT); } -void initskillpet() { - static PyMethodDef methods[] = { - {"SetSkillSlot", dummy_none, METH_VARARGS, nullptr}, - {"GetIconImage", dummy_zero, METH_VARARGS, nullptr}, - {"GetSkillbySlot", dummy_zero, METH_VARARGS, nullptr}, - {"GetEmptySkill", dummy_zero, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("petskill", methods); -} - -void initquest() { - static PyMethodDef methods[] = { - {"GetQuestCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetQuestData", dummy_zero, METH_VARARGS, nullptr}, - {"GetQuestIndex", dummy_zero, METH_VARARGS, nullptr}, - {"GetQuestLastTime", dummy_zero, METH_VARARGS, nullptr}, - {"Clear", dummy_none, METH_VARARGS, nullptr}, - {"Add", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("quest", methods); - PyModule_AddIntConstant(module, "QUEST_MAX_NUM", 5); -} - -void initMessenger() { - static PyMethodDef methods[] = { - {"RemoveFriend", dummy_none, METH_VARARGS, nullptr}, - {"IsFriendByName", dummy_str, METH_VARARGS, nullptr}, - {"Destroy", dummy_none, METH_VARARGS, nullptr}, - {"RefreshGuildMember", dummy_none, METH_VARARGS, nullptr}, - {"SetMessengerHandler", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("messenger", methods); -} - void initSash() { static PyMethodDef methods[] = { {"SendCloseRequest", dummy_none, METH_VARARGS, nullptr}, @@ -1410,324 +1355,7 @@ void initPlayerSettingsModule() { auto* module = Py_InitModule("playerLoad", methods); } -namespace { -struct SwitchbotSlotData { - bool active = false; - bool finished = false; - struct Attr { uint8_t type = 0; int value = 0; }; - Attr alternatives[2][5]; -}; -static SwitchbotSlotData s_switchbotSlots[5]; - -static PyObject* switchbot_IsActive(PyObject*, PyObject* args) { - int slot = 0; - if (PyArg_ParseTuple(args, "i", &slot) && slot >= 0 && slot < 5) { - return Py_BuildValue("i", s_switchbotSlots[slot].active ? 1 : 0); - } - return Py_BuildValue("i", 0); -} - -static PyObject* switchbot_IsFinished(PyObject*, PyObject* args) { - int slot = 0; - if (PyArg_ParseTuple(args, "i", &slot) && slot >= 0 && slot < 5) { - return Py_BuildValue("i", s_switchbotSlots[slot].finished ? 1 : 0); - } - return Py_BuildValue("i", 0); -} - -static PyObject* switchbot_GetAttribute(PyObject*, PyObject* args) { - int slot = 0, alt = 0, attrIdx = 0; - if (PyArg_ParseTuple(args, "iii", &slot, &alt, &attrIdx) && slot >= 0 && slot < 5 && alt >= 0 && alt < 2 && attrIdx >= 0 && attrIdx < 5) { - return Py_BuildValue("ii", (int)s_switchbotSlots[slot].alternatives[alt][attrIdx].type, s_switchbotSlots[slot].alternatives[alt][attrIdx].value); - } - return Py_BuildValue("ii", 0, 0); -} - -static PyObject* switchbot_SetAttribute(PyObject*, PyObject* args) { - int slot = 0, alt = 0, attrIdx = 0, type = 0, val = 0; - if (PyArg_ParseTuple(args, "iiiii", &slot, &alt, &attrIdx, &type, &val) && slot >= 0 && slot < 5 && alt >= 0 && alt < 2 && attrIdx >= 0 && attrIdx < 5) { - s_switchbotSlots[slot].alternatives[alt][attrIdx].type = (uint8_t)type; - s_switchbotSlots[slot].alternatives[alt][attrIdx].value = val; - } - Py_RETURN_NONE; -} - -static PyObject* switchbot_ClearSlot(PyObject*, PyObject* args) { - int slot = 0; - if (PyArg_ParseTuple(args, "i", &slot) && slot >= 0 && slot < 5) { - s_switchbotSlots[slot] = SwitchbotSlotData{}; - } - Py_RETURN_NONE; -} - -static PyObject* switchbot_Start(PyObject*, PyObject* args) { - int slot = 0; - if (PyArg_ParseTuple(args, "i", &slot) && slot >= 0 && slot < 5) { - s_switchbotSlots[slot].active = true; - s_switchbotSlots[slot].finished = false; - } - Py_RETURN_NONE; -} - -static PyObject* switchbot_Stop(PyObject*, PyObject* args) { - int slot = 0; - if (PyArg_ParseTuple(args, "i", &slot) && slot >= 0 && slot < 5) { - s_switchbotSlots[slot].active = false; - } - Py_RETURN_NONE; -} - -static PyObject* switchbot_GetAttributesForSet(PyObject*, PyObject* args) { - PyObject* list = PyList_New(0); - const int commonAttrs[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 15, 16, 17, 18, 19, 20, 21, 22, 23, 27, 28, 29, 30, 31, 32, 33, 34, 37, 39, 41, 43, 44, 45, 53, 71, 72 }; - for (int attr : commonAttrs) { - PyObject* item = Py_BuildValue("i", attr); - PyList_Append(list, item); - Py_DECREF(item); - } - return list; -} - -static PyObject* switchbot_GetAttributeMaxValue(PyObject*, PyObject* args) { - int set = 0, type = 0; - if (PyArg_ParseTuple(args, "ii", &set, &type)) { - if (type == 1) return Py_BuildValue("i", 2000); - if (type == 2) return Py_BuildValue("i", 500); - if (type >= 3 && type <= 6) return Py_BuildValue("i", 12); - if (type == 7 || type == 8) return Py_BuildValue("i", 20); - if (type == 9) return Py_BuildValue("i", 20); - if (type >= 15 && type <= 22) return Py_BuildValue("i", 10); - if (type >= 29 && type <= 34) return Py_BuildValue("i", 15); - return Py_BuildValue("i", 15); - } - return Py_BuildValue("i", 10); -} - -// Wiki Data Tables -constexpr uint32_t s_wikiBossChests[][2] = { - {50070,691}, {50071,791}, {50073,2091}, {50076,2191}, {50079,2206}, {50078,1304}, {50077,1901}, {51115,4140} -}; -constexpr uint32_t s_wikiDungeonChests[][2] = { - {50082,1093}, {80030,2092}, {50186,2598}, {51110,6091}, {51111,6191}, {54705,6812}, {51116,6231} -}; -constexpr uint32_t s_wikiOtherChests[][2] = { - {77904,0}, {77910,0}, {77911,0}, {77912,0}, {77901,0}, {77902,0}, {77903,0} -}; -constexpr uint32_t s_wikiEventChests[][2] = { - {50011,0}, {77916,0}, {50928,0}, {50929,0}, {50930,0}, {50275,0}, {50276,0}, {50277,0} -}; -constexpr uint32_t s_wikiBosses[] = { - 691, 791, 2091, 2191, 2206, 1304, 1901, 1093, 2092, 2493 -}; -constexpr uint32_t s_wikiMonsters[] = { - 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115 -}; -constexpr uint32_t s_wikiMetinStones[] = { - 8001, 8002, 8003, 8004, 8005, 8006, 8007, 8008, 8009, 8010, 8011, 8012, 8013, 8014 -}; -constexpr uint32_t s_wikiCategoryWeapons[][5] = { - {10, 20, 30, 40, 50}, - {1000, 1010, 1020, 2000, 2010}, - {10, 20, 30, 40, 50}, - {5000, 5010, 5020, 7000, 7010} -}; -constexpr uint32_t s_wikiCategoryArmors[][5] = { - {11200, 11210, 11220, 11230, 11240}, - {11400, 11410, 11420, 11430, 11440}, - {11600, 11610, 11620, 11630, 11640}, - {11800, 11810, 11820, 11830, 11840} -}; - -static PyObject* wiki_GetCategorySize(PyObject*, PyObject* args) { - int charIdx = 0, catType = 0; - if (PyArg_ParseTuple(args, "ii", &charIdx, &catType)) { - if (catType == 0 || catType == 1) return Py_BuildValue("i", 5); - return Py_BuildValue("i", 3); - } - return Py_BuildValue("i", 0); -} - -static PyObject* wiki_GetCategoryData(PyObject*, PyObject* args) { - int charIdx = 0, catType = 0, listIdx = 0; - if (PyArg_ParseTuple(args, "iii", &charIdx, &catType, &listIdx)) { - charIdx = std::clamp(charIdx, 0, 3); - listIdx = std::clamp(listIdx, 0, 4); - if (catType == 0) return Py_BuildValue("i", s_wikiCategoryWeapons[charIdx][listIdx]); - if (catType == 1) return Py_BuildValue("i", s_wikiCategoryArmors[charIdx][listIdx]); - if (catType == 2) return Py_BuildValue("i", 12200 + listIdx * 10); - if (catType == 3) return Py_BuildValue("i", 13000 + listIdx * 10); - if (catType == 4) return Py_BuildValue("i", 17000 + listIdx * 10); - if (catType == 5) return Py_BuildValue("i", 14000 + listIdx * 10); - if (catType == 6) return Py_BuildValue("i", 16000 + listIdx * 10); - if (catType == 7) return Py_BuildValue("i", 15000 + listIdx * 10); - return Py_BuildValue("i", 11200 + listIdx * 10); - } - return Py_BuildValue("i", 0); -} - -static PyObject* wiki_GetCostumeSize(PyObject*, PyObject* args) { - return Py_BuildValue("i", 6); -} - -static PyObject* wiki_GetCostumeData(PyObject*, PyObject* args) { - int cat = 0, idx = 0; - if (PyArg_ParseTuple(args, "ii", &cat, &idx)) { - return Py_BuildValue("i", 40101 + idx); - } - return Py_BuildValue("i", 40101); -} - -static PyObject* wiki_GetChestSize(PyObject*, PyObject* args) { - int cat = 0; - if (PyArg_ParseTuple(args, "i", &cat)) { - if (cat == 0) return Py_BuildValue("i", (int)(sizeof(s_wikiBossChests)/sizeof(s_wikiBossChests[0]))); - if (cat == 1) return Py_BuildValue("i", (int)(sizeof(s_wikiDungeonChests)/sizeof(s_wikiDungeonChests[0]))); - if (cat == 2) return Py_BuildValue("i", (int)(sizeof(s_wikiOtherChests)/sizeof(s_wikiOtherChests[0]))); - if (cat == 3) return Py_BuildValue("i", (int)(sizeof(s_wikiEventChests)/sizeof(s_wikiEventChests[0]))); - } - return Py_BuildValue("i", 4); -} - -static PyObject* wiki_GetChestData(PyObject*, PyObject* args) { - int cat = 0, idx = 0; - if (PyArg_ParseTuple(args, "ii", &cat, &idx)) { - if (cat == 0 && idx < 8) return Py_BuildValue("ii", s_wikiBossChests[idx][0], s_wikiBossChests[idx][1]); - if (cat == 1 && idx < 7) return Py_BuildValue("ii", s_wikiDungeonChests[idx][0], s_wikiDungeonChests[idx][1]); - if (cat == 2 && idx < 7) return Py_BuildValue("ii", s_wikiOtherChests[idx][0], s_wikiOtherChests[idx][1]); - if (cat == 3 && idx < 8) return Py_BuildValue("ii", s_wikiEventChests[idx][0], s_wikiEventChests[idx][1]); - } - return Py_BuildValue("ii", 50070, 691); -} - -static PyObject* wiki_GetMonsterSize(PyObject*, PyObject* args) { - return Py_BuildValue("i", (int)(sizeof(s_wikiMonsters)/sizeof(s_wikiMonsters[0]))); -} - -static PyObject* wiki_GetMonsterData(PyObject*, PyObject* args) { - int cat = 0, idx = 0; - if (PyArg_ParseTuple(args, "ii", &cat, &idx)) { - if (idx >= 0 && idx < 15) return Py_BuildValue("i", s_wikiMonsters[idx]); - } - return Py_BuildValue("i", 101); -} - -static PyObject* wiki_GetBossSize(PyObject*, PyObject* args) { - return Py_BuildValue("i", (int)(sizeof(s_wikiBosses)/sizeof(s_wikiBosses[0]))); -} - -static PyObject* wiki_GetBossData(PyObject*, PyObject* args) { - int cat = 0, idx = 0; - if (PyArg_ParseTuple(args, "ii", &cat, &idx)) { - if (idx >= 0 && idx < 10) return Py_BuildValue("i", s_wikiBosses[idx]); - } - return Py_BuildValue("i", 691); -} - -static PyObject* wiki_GetStoneSize(PyObject*, PyObject* args) { - return Py_BuildValue("i", (int)(sizeof(s_wikiMetinStones)/sizeof(s_wikiMetinStones[0]))); -} - -static PyObject* wiki_GetStoneData(PyObject*, PyObject* args) { - int cat = 0, idx = 0; - if (PyArg_ParseTuple(args, "ii", &cat, &idx)) { - if (idx >= 0 && idx < 14) return Py_BuildValue("i", s_wikiMetinStones[idx]); - } - return Py_BuildValue("i", 8001); -} - -static PyObject* wiki_GetRefineMaxLevel(PyObject*, PyObject* args) { - int vnum = 0; - if (PyArg_ParseTuple(args, "i", &vnum)) { - return Py_BuildValue("i", (vnum % 10)); - } - return Py_BuildValue("i", 9); -} - -static PyObject* wiki_GetRefineItems(PyObject*, PyObject* args) { - return PyTuple_New(0); -} - -static PyObject* wiki_GetSpecialInfoSize(PyObject*, PyObject* args) { - return Py_BuildValue("i", 4); -} - -static PyObject* wiki_GetSpecialInfoData(PyObject*, PyObject* args) { - int vnum = 0, idx = 0; - if (PyArg_ParseTuple(args, "ii", &vnum, &idx)) { - const uint32_t drops[] = { 27003, 27006, 70005, 50300 }; - return Py_BuildValue("ii", drops[idx % 4], 1); - } - return Py_BuildValue("ii", 27003, 1); -} - -static PyObject* wiki_GetMobInfoSize(PyObject*, PyObject* args) { - return Py_BuildValue("i", 3); -} - -static PyObject* wiki_GetMobInfoData(PyObject*, PyObject* args) { - int vnum = 0, idx = 0; - if (PyArg_ParseTuple(args, "ii", &vnum, &idx)) { - const uint32_t drops[] = { 27001, 27004, 30005 }; - return Py_BuildValue("ii", drops[idx % 3], 1); - } - return Py_BuildValue("ii", 27001, 1); -} - -static PyObject* wiki_GetItemDropFromChest(PyObject*, PyObject* args) { - return PyList_New(0); -} - -static PyObject* wiki_GetItemDropFromMonster(PyObject*, PyObject* args) { - return PyList_New(0); -} -} // namespace - -void initSwitchbot() { - static PyMethodDef methods[] = { - {"IsActive", switchbot_IsActive, METH_VARARGS, nullptr}, - {"IsFinished", switchbot_IsFinished, METH_VARARGS, nullptr}, - {"GetAttribute", switchbot_GetAttribute, METH_VARARGS, nullptr}, - {"SetAttribute", switchbot_SetAttribute, METH_VARARGS, nullptr}, - {"GetAttributesForSet", switchbot_GetAttributesForSet, METH_VARARGS, nullptr}, - {"GetAttributeMaxValue", switchbot_GetAttributeMaxValue, METH_VARARGS, nullptr}, - {"ClearSlot", switchbot_ClearSlot, METH_VARARGS, nullptr}, - {"Start", switchbot_Start, METH_VARARGS, nullptr}, - {"Stop", switchbot_Stop, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("switchbot", methods); - PyModule_AddIntConstant(module, "SLOT_COUNT", 5); - PyModule_AddIntConstant(module, "ALTERNATIVE_COUNT", 2); -} - -void initWiki() { - static PyMethodDef methods[] = { - {"GetRefineItems", wiki_GetRefineItems, METH_VARARGS, nullptr}, - {"IsBlackList", dummy_zero, METH_VARARGS, nullptr}, - {"GetCategorySize", wiki_GetCategorySize, METH_VARARGS, nullptr}, - {"GetCategoryData", wiki_GetCategoryData, METH_VARARGS, nullptr}, - {"GetBossSize", wiki_GetBossSize, METH_VARARGS, nullptr}, - {"GetBossData", wiki_GetBossData, METH_VARARGS, nullptr}, - {"GetMonsterSize", wiki_GetMonsterSize, METH_VARARGS, nullptr}, - {"GetMonsterData", wiki_GetMonsterData, METH_VARARGS, nullptr}, - {"GetCostumeSize", wiki_GetCostumeSize, METH_VARARGS, nullptr}, - {"GetCostumeData", wiki_GetCostumeData, METH_VARARGS, nullptr}, - {"GetStoneSize", wiki_GetStoneSize, METH_VARARGS, nullptr}, - {"GetStoneData", wiki_GetStoneData, METH_VARARGS, nullptr}, - {"GetChestSize", wiki_GetChestSize, METH_VARARGS, nullptr}, - {"GetChestData", wiki_GetChestData, METH_VARARGS, nullptr}, - {"GetSpecialInfoSize", wiki_GetSpecialInfoSize, METH_VARARGS, nullptr}, - {"GetSpecialInfoData", wiki_GetSpecialInfoData, METH_VARARGS, nullptr}, - {"GetMobInfoSize", wiki_GetMobInfoSize, METH_VARARGS, nullptr}, - {"GetMobInfoData", wiki_GetMobInfoData, METH_VARARGS, nullptr}, - {"ReadData", dummy_none, METH_VARARGS, nullptr}, - {"GetRefineMaxLevel", wiki_GetRefineMaxLevel, METH_VARARGS, nullptr}, - {"GetItemDropFromChest", wiki_GetItemDropFromChest, METH_VARARGS, nullptr}, - {"GetItemDropFromMonster", wiki_GetItemDropFromMonster, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("wiki", methods); -} +// wiki module: CPythonWiki port in src/python_wiki.cpp. void initCombatZoneSystem() { static PyMethodDef methods[] = { @@ -1761,25 +1389,6 @@ void initBankManager() { auto* module = Py_InitModule("managerBankLogs", methods); } -static PyObject* dropitem_getdates(PyObject*, PyObject*) { - return Py_BuildValue("siii", "None", 0, 0, 0); -} - -void intdropitem() { - static PyMethodDef methods[] = { - {"Open", dummy_none, METH_VARARGS, nullptr}, - {"SearchItem", dummy_none, METH_VARARGS, nullptr}, - {"CountDates", dummy_zero, METH_VARARGS, nullptr}, - {"GetDates", dropitem_getdates, METH_VARARGS, nullptr}, - {"GetPageView", dummy_zero, METH_VARARGS, nullptr}, - {"SetPageSelect", dummy_none, METH_VARARGS, nullptr}, - {"GetPageActual", dummy_zero, METH_VARARGS, nullptr}, - {"SetDropItemHandler", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("drop_item", methods); -} - static PyObject* safebox_GetCurrentSafeboxSize(PyObject*, PyObject*) { return PyInt_FromLong(CPythonSafeBox::Instance().GetCurrentSafeBoxSize()); } @@ -1961,123 +1570,7 @@ void initsafebox() { PyModule_AddIntConstant(module, "SAFEBOX_PAGE_SIZE", 45); } -static PyObject* guild_GuildIDToMarkID(PyObject* self, PyObject* args) { - uint32_t guildID = 0; - if (!PyArg_ParseTuple(args, "i", &guildID)) return Py_BuildValue(""); - uint32_t markID = ava2::GuildMarkManager::Instance().GetMarkID(guildID); - if (markID == ava2::INVALID_MARK_ID) return Py_BuildValue(""); - return PyLong_FromUnsignedLong(markID); -} - -static PyObject* guild_GetMarkImageFilenameByMarkID(PyObject* self, PyObject* args) { - uint32_t markID = 0; - if (!PyArg_ParseTuple(args, "i", &markID)) return Py_BuildValue("s", ""); - uint32_t imgIdx = markID / ava2::GuildMarkImage::MARK_TOTAL_COUNT; - std::string filename; - ava2::GuildMarkManager::Instance().GetMarkImageFilename(imgIdx, filename); - return Py_BuildValue("s", filename.c_str()); -} - -static PyObject* guild_GetMarkIndexByMarkID(PyObject* self, PyObject* args) { - uint32_t markID = 0; - if (!PyArg_ParseTuple(args, "i", &markID)) return Py_BuildValue("i", 0); - uint32_t slotIdx = markID % ava2::GuildMarkImage::MARK_TOTAL_COUNT; - return PyLong_FromUnsignedLong(slotIdx); -} - -void initguild() { - static PyMethodDef methods[] = { - {"IsGuildEnable", dummy_zero, METH_VARARGS, nullptr}, - {"GuildIDToMarkID", guild_GuildIDToMarkID, METH_VARARGS, nullptr}, - {"GetMarkImageFilenameByMarkID", guild_GetMarkImageFilenameByMarkID, METH_VARARGS, nullptr}, - {"GetMarkIndexByMarkID", guild_GetMarkIndexByMarkID, METH_VARARGS, nullptr}, - {"GetGuildID", dummy_zero, METH_VARARGS, nullptr}, - {"HasGuildLand", dummy_none, METH_VARARGS, nullptr}, - {"GetGuildName", dummy_str, METH_VARARGS, nullptr}, - {"GetGuildMasterName", dummy_str, METH_VARARGS, nullptr}, - {"GetEnemyGuildName", dummy_str, METH_VARARGS, nullptr}, - {"GetGuildMoney", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildBoardCommentCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildBoardCommentData", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildLevel", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildExperience", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildMemberCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildMemberLevelSummary", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildMemberLevelAverage", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildExperienceSummary", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildSkillPoint", dummy_zero, METH_VARARGS, nullptr}, - {"GetDragonPowerPoint", dummy_zero, METH_VARARGS, nullptr}, - {"GetGuildSkillLevel", dummy_zero, METH_VARARGS, nullptr}, - {"GetSkillLevel", dummy_zero, METH_VARARGS, nullptr}, - {"GetSkillMaxLevelNew", dummy_zero, METH_VARARGS, nullptr}, - {"SetSkillIndex", dummy_none, METH_VARARGS, nullptr}, - {"GetSkillIndex", dummy_zero, METH_VARARGS, nullptr}, - {"GetGradeData", dummy_zero, METH_VARARGS, nullptr}, - {"GetGradeName", dummy_str, METH_VARARGS, nullptr}, - {"GetMemberCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetMemberData", dummy_zero, METH_VARARGS, nullptr}, - {"MemberIndexToPID", dummy_none, METH_VARARGS, nullptr}, - {"IsMember", dummy_zero, METH_VARARGS, nullptr}, - {"IsMemberByName", dummy_str, METH_VARARGS, nullptr}, - {"MainPlayerHasAuthority", dummy_none, METH_VARARGS, nullptr}, - {"Destroy", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("guild", methods); - PyModule_AddIntConstant(module, "AUTH_ADD_MEMBER", 0); - PyModule_AddIntConstant(module, "AUTH_REMOVE_MEMBER", 0); - PyModule_AddIntConstant(module, "AUTH_NOTICE", 0); - PyModule_AddIntConstant(module, "AUTH_SKILL", 0); - PyModule_AddIntConstant(module, "ENEMY_GUILD_SLOT_MAX_COUNT", 0); -} - namespace { -struct DungeonInfoEntry { - int index; - std::string name; - int minLv; - int maxLv; - int partyMin; - int partyMax; - int timeLimit; - int cooldown; - int itemVnum; - int itemCount; - int mapIndex; -}; - -static const std::vector s_dungeons = { - {0, "Demon Tower", 40, 105, 1, 8, 3600, 1800, 30302, 1, 66}, - {1, "Spider Baroness", 50, 105, 1, 8, 2400, 3600, 71095, 1, 217}, - {2, "Beran-Setaou Lair", 75, 120, 1, 8, 1800, 7200, 30179, 3, 208}, - {3, "Nemere Watchtower", 100, 120, 2, 8, 3600, 14400, 71130, 1, 352}, - {4, "Razador Fortress", 100, 120, 2, 8, 3600, 14400, 71130, 1, 351}, - {5, "Meley Lair", 105, 120, 4, 16, 3600, 21600, 71130, 2, 212} -}; - -static PyObject* dungeoninfo_CountDate(PyObject*, PyObject*) { - return Py_BuildValue("i", (int)s_dungeons.size()); -} - -static PyObject* dungeoninfo_InfoDate(PyObject*, PyObject* args) { - int idx = 0; - if (PyArg_ParseTuple(args, "i", &idx)) { - if (idx >= 0 && idx < (int)s_dungeons.size()) { - const auto& d = s_dungeons[idx]; - return Py_BuildValue("isiiiiiiiii", d.index, d.name.c_str(), d.minLv, d.maxLv, d.partyMin, d.partyMax, d.timeLimit, d.cooldown, d.itemVnum, d.itemCount, d.mapIndex); - } - } - return Py_BuildValue("isiiiiiiiii", 0, "Unknown", 1, 120, 1, 8, 3600, 3600, 0, 0, 0); -} - -static PyObject* dungeoninfo_GetPageCount(PyObject*, PyObject*) { - return Py_BuildValue("i", 1); -} - -static PyObject* dungeoninfo_GetPageView(PyObject*, PyObject*) { - return Py_BuildValue("i", (int)s_dungeons.size()); -} - static PyObject* renderTarget_SelectModel(PyObject*, PyObject* args) { int idx = 0; int modelVnum = 0; @@ -2234,25 +1727,6 @@ static PyObject* renderTarget_Destroy(PyObject*, PyObject* args) { } } // namespace -void intdungeoninfo() { - static PyMethodDef methods[] = { - {"CountDateRanking", dummy_none, METH_VARARGS, nullptr}, - {"InfoDateRanking", dummy_none, METH_VARARGS, nullptr}, - {"InfoDateMision", dummy_none, METH_VARARGS, nullptr}, - {"CountDate", dungeoninfo_CountDate, METH_VARARGS, nullptr}, - {"InfoDate", dungeoninfo_InfoDate, METH_VARARGS, nullptr}, - {"Open", dummy_none, METH_VARARGS, nullptr}, - {"Teleport", dummy_none, METH_VARARGS, nullptr}, - {"Ranking", dummy_none, METH_VARARGS, nullptr}, - {"Mision", dummy_none, METH_VARARGS, nullptr}, - {"SetPageCount", dummy_none, METH_VARARGS, nullptr}, - {"GetPageCount", dungeoninfo_GetPageCount, METH_VARARGS, nullptr}, - {"GetPageView", dungeoninfo_GetPageView, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("dungeon_info", methods); -} - void initRenderTarget() { static PyMethodDef methods[] = { {"SelectModel", renderTarget_SelectModel, METH_VARARGS, nullptr}, @@ -2284,37 +1758,6 @@ void initRenderTarget() { auto* module = Py_InitModule("renderTarget", methods); } -static PyObject* cuberenewal_getdates(PyObject*, PyObject*) { - return Py_BuildValue("iibiiiiiiiiiiiis", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "None"); -} - -void intcuberenewal() { - static PyMethodDef methods[] = { - {"CountDates", dummy_zero, METH_VARARGS, nullptr}, - {"GetDates", cuberenewal_getdates, METH_VARARGS, nullptr}, - {"SetCubeRenewalHandler", dummy_none, METH_VARARGS, nullptr}, - {"CubeRenewalMakeItem", dummy_none, METH_VARARGS, nullptr}, - {"CubeRenewalClose", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("cube_renewal", methods); -} - -void intbattlepass() { - static PyMethodDef methods[] = { - {"CountDates", dummy_zero, METH_VARARGS, nullptr}, - {"GetDates", dummy_tuple2, METH_VARARGS, nullptr}, - {"GetDatesItems", dummy_zero, METH_VARARGS, nullptr}, - {"GetDatesCount", dummy_tuple3, METH_VARARGS, nullptr}, - {"SetBattlePassHandler", dummy_none, METH_VARARGS, nullptr}, - {"GetTime", dummy_zero, METH_VARARGS, nullptr}, - {"Open", dummy_none, METH_VARARGS, nullptr}, - {"Reward", dummy_none, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - auto* module = Py_InitModule("battlepass", methods); -} - void initudp() { static PyMethodDef methods[] = { {nullptr, nullptr, 0, nullptr} @@ -2322,25 +1765,5 @@ void initudp() { auto* module = Py_InitModule("udp", methods); } -void initprivateShopSearch() { - static PyMethodDef methods[] = { - {"GetItemCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetSearchItemCount", dummy_zero, METH_VARARGS, nullptr}, - {"GetSearchItemPrice", dummy_zero, METH_VARARGS, nullptr}, - {"GetSearchItemVnum", dummy_zero, METH_VARARGS, nullptr}, - {"GetSearchItemShopVID", dummy_zero, METH_VARARGS, nullptr}, - {"ClearSearchItems", dummy_none, METH_VARARGS, nullptr}, - {"GetSearchItemMetinSocket", dummy_zero, METH_VARARGS, nullptr}, - {"GetSearchItemAttribute", dummy_tuple2, METH_VARARGS, nullptr}, - {"GetSearchItemTransmutation", dummy_zero, METH_VARARGS, nullptr}, - {"GetSearchItemNewName", dummy_str, METH_VARARGS, nullptr}, - {"GetSearchItemPerma", dummy_zero, METH_VARARGS, nullptr}, - {"GetSearchItemPos", dummy_zero, METH_VARARGS, nullptr}, - {"GetSearchItemSeller", dummy_str, METH_VARARGS, nullptr}, - {"GetSearchItemID", dummy_zero, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} - }; - Py_InitModule("privateShopSearch", methods); -} } // namespace ava2 diff --git a/src/python_native_modules.h b/src/python_native_modules.h index 8fa93da5..d6331a09 100644 --- a/src/python_native_modules.h +++ b/src/python_native_modules.h @@ -17,6 +17,7 @@ std::array GetGameEventCenter(); void initshop(); void ResetShopState(); void ClearShopState(); +bool IsShopOpen(); struct ShopItemRecord { uint32_t vnum=0,count=0,buyVnum=0,buyCount=0; int64_t price=0; @@ -31,6 +32,10 @@ void SetShopTab(unsigned index,const std::string& name,unsigned coin); void initskill(); float EvaluateSkillFormula(const std::string& formula, float level); void ResetSkillDescriptions(); +int GetSkillTypeById(uint32_t id); +struct SkillDescription; +// CPythonSkill::GetSkillData; nullptr for an unknown index. +const SkillDescription* FindSkillDescription(uint32_t id); bool LoadSkillDescriptions(const std::string& path); bool LoadSkillTable(const std::string& path, bool cheonma=false); void initskillpet(); @@ -40,7 +45,7 @@ void initSash(); void initServerStateChecker(); void initPlayerSettingsModule(); void initSwitchbot(); -void initWiki(); +void initWiki(); // src/python_wiki.cpp void initCombatZoneSystem(); void initBankManager(); void intdropitem(); diff --git a/src/python_net.cpp b/src/python_net.cpp index 442de611..8ea508cb 100644 --- a/src/python_net.cpp +++ b/src/python_net.cpp @@ -1,13 +1,19 @@ #include "python_net.h" +#include "guild_state.h" +#include "python_gameplay_modules.h" #include "login_client.h" #include "protocol.h" #include "eter_net/PythonNetworkStream.h" #include "eter_net/NetworkActorManager.h" +#include "shared/common/PythonUtils.h" +#include "python_runtime.h" #include #include +#include #include #include #include +#include namespace ava2 { namespace { @@ -31,19 +37,10 @@ void replace(PyObject*& old,PyObject* next) { Py_XDECREF(previous); } +// PyCallClassMemberFunc (ScriptLib): a missing method is skipped, a Python +// exception is printed; neither aborts the network pump. void callback(PyObject* target,const char* name,const char* text=nullptr) { - if(!target) return; - Py_INCREF(target); - auto* method=PyObject_GetAttrString(target,name); - if(!method) { - Py_DECREF(target); - throw std::runtime_error(std::string("missing Python callback: ")+name); - } - auto* result=text?PyObject_CallFunction(method,const_cast("s"),text):PyObject_CallObject(method,nullptr); - Py_DECREF(method); - Py_DECREF(target); - if(!result) throw std::runtime_error(std::string("Python callback failed: ")+name); - Py_DECREF(result); + PyCallClassMemberFunc(target,name,text?Py_BuildValue("(s)",text):Py_BuildValue("()")); } PyObject* set_handler(PyObject*,PyObject* args) { PyObject* value;if(!PyArg_ParseTuple(args,"O",&value)) return nullptr;replace(handler,value);PythonNetworkStream::Instance().SetHandler(value);Py_RETURN_NONE; } @@ -114,6 +111,352 @@ PyObject* net_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); } PyObject* net_dummy_str(PyObject*, PyObject*) { return PyString_FromString(""); } PyObject* net_dummy_tuple4(PyObject*, PyObject*) { return Py_BuildValue("iiii", 0, 0, 0, 0); } +// ── AVA2 PythonNetworkStreamModule.cpp wrappers (ScriptLib argument helpers, Py_BuildException -> None) ── +PyObject* netSendExchangeStartPacket(PyObject*, PyObject* poArgs) { + int vid; + if (!PyTuple_GetInteger(poArgs, 0, &vid)) return Py_BuildException(); + PythonNetworkStream::Instance().SendExchangeStartPacket(vid); + return Py_BuildNone(); +} +PyObject* netSendExchangeElkAddPacket(PyObject*, PyObject* poArgs) { + long long elk; + if (!PyTuple_GetLongLong(poArgs, 0, &elk)) return Py_BuildException(); + PythonNetworkStream::Instance().SendExchangeElkAddPacket(elk); + return Py_BuildNone(); +} +PyObject* netSendExchangeItemAddPacket(PyObject*, PyObject* poArgs) { + unsigned char window; unsigned short slot; int displayPos; + if (!PyTuple_GetInteger(poArgs, 0, &window)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &slot)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 2, &displayPos)) return Py_BuildException(); + PythonNetworkStream::Instance().SendExchangeItemAddPacket(window, slot, static_cast(displayPos)); + return Py_BuildNone(); +} +PyObject* netSendExchangeItemDelPacket(PyObject*, PyObject* poArgs) { + int pos; + if (!PyTuple_GetInteger(poArgs, 0, &pos)) return Py_BuildException(); + PythonNetworkStream::Instance().SendExchangeItemDelPacket(static_cast(pos)); + return Py_BuildNone(); +} +PyObject* netSendExchangeAcceptPacket(PyObject*, PyObject*) { PythonNetworkStream::Instance().SendExchangeAcceptPacket();return Py_BuildNone(); } +PyObject* netSendExchangeExitPacket(PyObject*, PyObject*) { PythonNetworkStream::Instance().SendExchangeExitPacket();return Py_BuildNone(); } + +PyObject* netSendPrivateShopSearchInfo(PyObject*,PyObject* args) { + TPacketCGShopSearch p{}; + if(!PyTuple_GetInteger(args,0,&p.ItemCat)||!PyTuple_GetInteger(args,1,&p.SubCat))return Py_BuildException(); + uint8_t* pairs[]={p.avg,p.skill,p.abs,p.level,p.refine}; + for(int i=0;i<10;++i)if(!PyTuple_GetInteger(args,i+2,&pairs[i/2][i%2]))return Py_BuildException(); + if(!PyTuple_GetInteger(args,12,&p.enchant)||!PyTuple_GetInteger(args,13,&p.alchemy)|| + !PyTuple_GetInteger(args,14,&p.sex)||!PyTuple_GetInteger(args,15,&p.character))return Py_BuildException(); + long long lo,hi;char* input; + if(!PyTuple_GetLongLong(args,16,&lo)||!PyTuple_GetLongLong(args,17,&hi)||!PyTuple_GetString(args,18,&input))return Py_BuildException(); + if(PyErr_Occurred())return nullptr; + const size_t length=std::strlen(input); + if(length>=sizeof(p.searchInput)) { PyErr_SetString(PyExc_ValueError,"Shop search text exceeds 49 bytes");return nullptr; } + std::memcpy(p.searchInput,input,length);p.price[0]=lo;p.price[1]=hi; + PythonNetworkStream::Instance().SendPrivateShopSearchInfo(p);Py_RETURN_NONE; +} + +PyObject* netSendMessengerAddByVIDPacket(PyObject*, PyObject* poArgs) { + int vid; + if (!PyTuple_GetInteger(poArgs, 0, &vid)) return Py_BuildException(); + PythonNetworkStream::Instance().SendMessengerAddByVIDPacket(vid); + return Py_BuildNone(); +} +PyObject* netSendMessengerAddByNamePacket(PyObject*, PyObject* poArgs) { + char* name; + if (!PyTuple_GetString(poArgs, 0, &name)) return Py_BuildException(); + PythonNetworkStream::Instance().SendMessengerAddByNamePacket(name); + return Py_BuildNone(); +} +PyObject* netSendMessengerRemovePacket(PyObject*, PyObject* poArgs) { + char* key; char* name; + if (!PyTuple_GetString(poArgs, 0, &key)) return Py_BuildException(); + if (!PyTuple_GetString(poArgs, 1, &name)) return Py_BuildException(); + PythonNetworkStream::Instance().SendMessengerRemovePacket(key, name); + return Py_BuildNone(); +} + +// IAbstractPlayer::PartyMemberVIDToPID. The port does not track party members yet +// (player.IsPartyMember is still a placeholder), so the lookup fails like an empty party. +bool party_member_vid_to_pid(uint32_t, uint32_t*) { return false; } + +PyObject* netSendPartyInvitePacket(PyObject*, PyObject* poArgs) { + int vid; + if (!PyTuple_GetInteger(poArgs, 0, &vid)) return Py_BuildException(); + PythonNetworkStream::Instance().SendPartyInvitePacket(vid); + return Py_BuildNone(); +} +PyObject* netSendPartyInviteAnswerPacket(PyObject*, PyObject* poArgs) { + int vid, answer; + if (!PyTuple_GetInteger(poArgs, 0, &vid)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &answer)) return Py_BuildException(); + PythonNetworkStream::Instance().SendPartyInviteAnswerPacket(vid, static_cast(answer)); + return Py_BuildNone(); +} +PyObject* netSendPartyExitPacket(PyObject*, PyObject*) { + uint32_t pid; + if (party_member_vid_to_pid(PythonNetworkStream::Instance().GetMainActorVID(), &pid)) + PythonNetworkStream::Instance().SendPartyRemovePacket(pid); + return Py_BuildNone(); +} +PyObject* netSendPartyRemovePacketPID(PyObject*, PyObject* poArgs) { + int pid; + if (!PyTuple_GetInteger(poArgs, 0, &pid)) return Py_BuildException(); + PythonNetworkStream::Instance().SendPartyRemovePacket(pid); + return Py_BuildNone(); +} +PyObject* netSendPartyRemovePacketVID(PyObject*, PyObject* poArgs) { + int vid; + if (!PyTuple_GetInteger(poArgs, 0, &vid)) return Py_BuildException(); + uint32_t pid; + if (party_member_vid_to_pid(vid, &pid)) PythonNetworkStream::Instance().SendPartyRemovePacket(pid); + return Py_BuildNone(); +} +PyObject* netSendPartySetStatePacket(PyObject*, PyObject* poArgs) { + int vid, state, flag; + if (!PyTuple_GetInteger(poArgs, 0, &vid)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &state)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 2, &flag)) return Py_BuildException(); + PythonNetworkStream::Instance().SendPartySetStatePacket(vid, static_cast(state), static_cast(flag)); + return Py_BuildNone(); +} +PyObject* netSendPartyUseSkillPacket(PyObject*, PyObject* poArgs) { + int skillIndex, vid; + if (!PyTuple_GetInteger(poArgs, 0, &skillIndex)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &vid)) return Py_BuildException(); + PythonNetworkStream::Instance().SendPartyUseSkillPacket(static_cast(skillIndex), vid); + return Py_BuildNone(); +} +PyObject* netSendPartyParameterPacket(PyObject*, PyObject* poArgs) { + int mode; + if (!PyTuple_GetInteger(poArgs, 0, &mode)) return Py_BuildException(); + PythonNetworkStream::Instance().SendPartyParameterPacket(static_cast(mode)); + return Py_BuildNone(); +} + +PyObject* netSendSafeboxSaveMoneyPacket(PyObject*, PyObject* poArgs) { + int money; + if (!PyTuple_GetInteger(poArgs, 0, &money)) return Py_BuildException(); + PythonNetworkStream::Instance().SendSafeBoxMoneyPacket(0, money); // SAFEBOX_MONEY_STATE_SAVE: disabled, sends nothing + return Py_BuildNone(); +} +PyObject* netSendSafeboxWithdrawMoneyPacket(PyObject*, PyObject* poArgs) { + int money; + if (!PyTuple_GetInteger(poArgs, 0, &money)) return Py_BuildException(); + PythonNetworkStream::Instance().SendSafeBoxMoneyPacket(1, money); // SAFEBOX_MONEY_STATE_WITHDRAW: disabled, sends nothing + return Py_BuildNone(); +} +// TItemPos() starts as {INVENTORY, WORD_MAX}; Windows' switch has no default for other arg counts, +// sending the ctor position and an uninitialized safebox slot (emitted as 0 here). +PyObject* netSendSafeboxCheckinPacket(PyObject*, PyObject* poArgs) { + unsigned char window = 1; unsigned short cell = 0xffff; int safeboxPos = 0; + switch (PyTuple_Size(poArgs)) { + case 2: + window = 1; + if (!PyTuple_GetInteger(poArgs, 0, &cell)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &safeboxPos)) return Py_BuildException(); + break; + case 3: + if (!PyTuple_GetInteger(poArgs, 0, &window)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &cell)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 2, &safeboxPos)) return Py_BuildException(); + break; + } + PythonNetworkStream::Instance().SendSafeBoxCheckinPacket(window, cell, static_cast(safeboxPos)); + return Py_BuildNone(); +} +PyObject* netSendSafeboxCheckoutPacket(PyObject*, PyObject* poArgs) { + int safeboxPos = 0; unsigned char window = 1; unsigned short cell = 0xffff; + switch (PyTuple_Size(poArgs)) { + case 2: + if (!PyTuple_GetInteger(poArgs, 0, &safeboxPos)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &cell)) return Py_BuildException(); + break; + case 3: + if (!PyTuple_GetInteger(poArgs, 0, &safeboxPos)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &window)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 2, &cell)) return Py_BuildException(); + break; + default: + break; + } + PythonNetworkStream::Instance().SendSafeBoxCheckoutPacket(static_cast(safeboxPos), window, cell); + return Py_BuildNone(); +} +PyObject* netSendSafeboxItemMovePacket(PyObject*, PyObject* poArgs) { + int source, target, count; + if (!PyTuple_GetInteger(poArgs, 0, &source)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &target)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 2, &count)) return Py_BuildException(); + PythonNetworkStream::Instance().SendSafeBoxItemMovePacket(static_cast(source), static_cast(target), static_cast(count)); + return Py_BuildNone(); +} +PyObject* netSendMallCheckoutPacket(PyObject*, PyObject* poArgs) { + int mallPos; unsigned char window = 1; unsigned short cell = 0xffff; + switch (PyTuple_Size(poArgs)) { + case 2: + if (!PyTuple_GetInteger(poArgs, 0, &mallPos)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &cell)) return Py_BuildException(); + break; + case 3: + if (!PyTuple_GetInteger(poArgs, 0, &mallPos)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &window)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 2, &cell)) return Py_BuildException(); + break; + default: + return Py_BuildException(); + } + PythonNetworkStream::Instance().SendMallCheckoutPacket(static_cast(mallPos), window, cell); + return Py_BuildNone(); +} + +PyObject* netSendAnswerMakeGuildPacket(PyObject*, PyObject* poArgs) { + char* name; + if (!PyTuple_GetString(poArgs, 0, &name)) return Py_BuildException(); + PythonNetworkStream::Instance().SendAnswerMakeGuildPacket(name); + return Py_BuildNone(); +} +PyObject* netSendQuestInputStringPacket(PyObject*, PyObject* poArgs) { + char* text; + if (!PyTuple_GetString(poArgs, 0, &text)) return Py_BuildException(); + PythonNetworkStream::Instance().SendQuestInputStringPacket(text); + return Py_BuildNone(); +} +PyObject* netSendQuestInputLongStringPacket(PyObject*, PyObject* poArgs) { + char* text; + if (!PyTuple_GetString(poArgs, 0, &text)) return Py_BuildException(); + PythonNetworkStream::Instance().SendQuestInputStringLongPacket(text); + return Py_BuildNone(); +} +PyObject* netSendQuestConfirmPacket(PyObject*, PyObject* poArgs) { + int answer, pid; + if (!PyTuple_GetInteger(poArgs, 0, &answer)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &pid)) return Py_BuildException(); + PythonNetworkStream::Instance().SendQuestConfirmPacket(static_cast(answer), pid); + return Py_BuildNone(); +} +PyObject* netSendRequestRefineInfoPacket(PyObject*, PyObject* poArgs) { + int slot; + if (!PyTuple_GetInteger(poArgs, 0, &slot)) return Py_BuildException(); + // Windows: assert(!"... not used anymore"); nothing is sent. + return Py_BuildNone(); +} +PyObject* netSendSelectItemPacket(PyObject*, PyObject* poArgs) { + int itemPos; + if (!PyTuple_GetInteger(poArgs, 0, &itemPos)) return Py_BuildException(); + PythonNetworkStream::Instance().SendSelectItemPacket(itemPos); + return Py_BuildNone(); +} +PyObject* netTargetInfoLoad(PyObject*, PyObject* poArgs) { + unsigned int vid; // DWORD: Windows' "dwVID < 0" early return can never fire + if (!PyArg_ParseTuple(poArgs, "i", &vid)) return Py_BuildException(); + PythonNetworkStream::Instance().SendTargetInfoLoadPacket(vid); + return Py_BuildNone(); +} + +PyObject* netGetGuildID(PyObject*,PyObject*) {return PyInt_FromLong(int32_t(PythonNetworkStream::Instance().GetGuildID()));} + +PyObject* netSendGuildAddMemberPacket(PyObject*, PyObject* poArgs) { + int vid; + if (!PyTuple_GetInteger(poArgs, 0, &vid)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildAddMemberPacket(vid); + return Py_BuildNone(); +} +PyObject* netSendGuildRemoveMemberPacket(PyObject*, PyObject* poArgs) { + char* key; + if (!PyTuple_GetString(poArgs, 0, &key)) return Py_BuildException(); + if (auto* member=GetGuildState().ByName(key)) + PythonNetworkStream::Instance().SendGuildRemoveMemberPacket(member->pid); + else + std::cerr << "netSendGuildRemoveMemberPacket(szKey=" << key << ") - Can't Find Guild Member\n"; + return Py_BuildNone(); +} +PyObject* netSendGuildChangeGradeNamePacket(PyObject*, PyObject* poArgs) { + int grade; char* name; + if (!PyTuple_GetInteger(poArgs, 0, &grade)) return Py_BuildException(); + if (!PyTuple_GetString(poArgs, 1, &name)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildChangeGradeNamePacket(static_cast(grade), name); + return Py_BuildNone(); +} +PyObject* netSendGuildChangeGradeAuthorityPacket(PyObject*, PyObject* poArgs) { + int grade, authority; + if (!PyTuple_GetInteger(poArgs, 0, &grade)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &authority)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildChangeGradeAuthorityPacket(static_cast(grade), static_cast(authority)); + return Py_BuildNone(); +} +PyObject* netSendGuildOfferPacket(PyObject*, PyObject* poArgs) { + int experience; + if (!PyTuple_GetInteger(poArgs, 0, &experience)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildOfferPacket(experience); + return Py_BuildNone(); +} +PyObject* netSnedGuildPostCommentPacket(PyObject*, PyObject* poArgs) { + char* comment; + if (!PyTuple_GetString(poArgs, 0, &comment)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildPostCommentPacket(comment); + return Py_BuildNone(); +} +PyObject* netSnedGuildDeleteCommentPacket(PyObject*, PyObject* poArgs) { + int index; + if (!PyTuple_GetInteger(poArgs, 0, &index)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildDeleteCommentPacket(index); + return Py_BuildNone(); +} +PyObject* netSendGuildRefreshCommentsPacket(PyObject*, PyObject* poArgs) { + int highestIndex; + if (!PyTuple_GetInteger(poArgs, 0, &highestIndex)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildRefreshCommentsPacket(highestIndex); + return Py_BuildNone(); +} +PyObject* netSendGuildChangeMemberGradePacket(PyObject*, PyObject* poArgs) { + int pid, grade; + if (!PyTuple_GetInteger(poArgs, 0, &pid)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &grade)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildChangeMemberGradePacket(pid, static_cast(grade)); + return Py_BuildNone(); +} +PyObject* netSendGuildUseSkillPacket(PyObject*, PyObject* poArgs) { + int skillID, targetVID; + if (!PyTuple_GetInteger(poArgs, 0, &skillID)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &targetVID)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildUseSkillPacket(skillID, targetVID); + return Py_BuildNone(); +} +PyObject* netSendGuildChangeMemberGeneralPacket(PyObject*, PyObject* poArgs) { + int pid, flag; + if (!PyTuple_GetInteger(poArgs, 0, &pid)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &flag)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildChangeMemberGeneralPacket(pid, static_cast(flag)); + return Py_BuildNone(); +} +PyObject* netSendGuildInviteAnswerPacket(PyObject*, PyObject* poArgs) { + int guildID, answer; + if (!PyTuple_GetInteger(poArgs, 0, &guildID)) return Py_BuildException(); + if (!PyTuple_GetInteger(poArgs, 1, &answer)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildInviteAnswerPacket(guildID, static_cast(answer)); + return Py_BuildNone(); +} +PyObject* netSendGuildChargeGSPPacket(PyObject*, PyObject* poArgs) { + int gsp; + if (!PyTuple_GetInteger(poArgs, 0, &gsp)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildChargeGSPPacket(gsp); + return Py_BuildNone(); +} +PyObject* netSendGuildDepositMoneyPacket(PyObject*, PyObject* poArgs) { + int money; + if (!PyTuple_GetInteger(poArgs, 0, &money)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildDepositMoneyPacket(money); + return Py_BuildNone(); +} +PyObject* netSendGuildWithdrawMoneyPacket(PyObject*, PyObject* poArgs) { + int money; + if (!PyTuple_GetInteger(poArgs, 0, &money)) return Py_BuildException(); + PythonNetworkStream::Instance().SendGuildWithdrawMoneyPacket(money); + return Py_BuildNone(); +} + PyObject* net_get_main_actor_vid(PyObject*, PyObject*) { uint32_t vid = PythonNetworkStream::Instance().GetMainActorVID(); if (vid == 0 && has_mock_characters) vid = 1001; @@ -377,6 +720,13 @@ PyObject* send_item_move_packet(PyObject*, PyObject* args) { } // namespace +void update_player_guild(uint32_t id,const std::string& name) { + if(has_mock_characters) { + for(auto& c:mock_characters)if(c.name==GetMainCharacterName()) {c.guild_id=id;c.guild_name=name;} + } + client.update_player_guild(GetMainCharacterName(),id,name); +} + const CharacterMoveState& get_last_character_move() { return last_move_state; } @@ -393,6 +743,33 @@ void SetItemMovePacketCallback(ItemMovePacketCallback cb) { s_itemMoveCallback = cb; } +// AVA2 PythonNetworkStreamModule.cpp: server-command / chat-filter / emoticon wrappers. +std::vector preserved_commands; // g_kList_strCommand +PyObject* server_command_parser=nullptr; +static PyObject* net_preserve_server_command(PyObject*, PyObject* args) { char* line;if(!PyTuple_GetString(args,0,&line)) return Py_BuildException();preserved_commands.push_back(line);return Py_BuildNone(); } +static PyObject* net_get_preserved_server_command(PyObject*, PyObject*) { + if(preserved_commands.empty()) return Py_BuildValue("s",""); + std::string command=preserved_commands.front();preserved_commands.erase(preserved_commands.begin()); + return Py_BuildValue("s",command.c_str()); +} +static PyObject* net_set_server_command_parser_window(PyObject*, PyObject* args) { + PyObject* window;if(!PyTuple_GetObject(args,0,&window)) return Py_BuildException(); + replace(server_command_parser,window);PythonNetworkStream::Instance().SetServerCommandParserWindow(server_command_parser);return Py_BuildNone(); +} +// netLoadInsultList / netIsChatInsultIn / netIsInsultIn (AVA2 PythonNetworkStreamModule.cpp). +bool LoadInsultList(const std::string& path) { + std::string text; + try { text=ReadPackedText(path); } catch(const std::exception&) { return false; } + return PythonNetworkStream::Instance().LoadInsultList(text); +} +static PyObject* net_load_insult_list(PyObject*, PyObject* args) { char* path;if(!PyTuple_GetString(args,0,&path)) return Py_BuildException();return Py_BuildValue("i",LoadInsultList(path)); } +static PyObject* net_is_chat_insult_in(PyObject*, PyObject* args) { char* msg;if(!PyTuple_GetString(args,0,&msg)) return Py_BuildException();return Py_BuildValue("i",PythonNetworkStream::Instance().IsChatInsultIn(msg)); } +static PyObject* net_is_insult_in(PyObject*, PyObject* args) { char* msg;if(!PyTuple_GetString(args,0,&msg)) return Py_BuildException();return Py_BuildValue("i",PythonNetworkStream::Instance().IsInsultIn(msg)); } +static PyObject* net_enable_chat_insult_filter(PyObject*, PyObject* args) { int enable;if(!PyTuple_GetInteger(args,0,&enable)) return Py_BuildException();PythonNetworkStream::Instance().EnableChatInsultFilter(enable!=0);return Py_BuildNone(); } +static PyObject* net_set_empire_language_mode(PyObject*, PyObject* args) { int mode;if(!PyTuple_GetInteger(args,0,&mode)) return Py_BuildException();PythonNetworkStream::Instance().SetEmpireLanguageMode(mode!=0);return Py_BuildNone(); } +static PyObject* net_register_emoticon_string(PyObject*, PyObject* args) { char* text;if(!PyTuple_GetString(args,0,&text)) return Py_BuildException();PythonNetworkStream::Instance().RegisterEmoticonString(text);return Py_BuildNone(); } +static PyObject* net_send_emoticon(PyObject*, PyObject* args) { int emoticon;if(!PyTuple_GetInteger(args,0,&emoticon)) return Py_BuildException();PythonNetworkStream::Instance().SendEmoticon(unsigned(emoticon));return Py_BuildNone(); } + static PyObject* net_send_refine_packet(PyObject*, PyObject* args) { int targetPos = 0, type = 0, specialStorage = 0, indexSelect = -1; if (PyArg_ParseTuple(args, "iiii", &targetPos, &type, &specialStorage, &indexSelect)) { @@ -460,30 +837,30 @@ void initnet() { {"Update", update, METH_NOARGS, nullptr}, {"GetConnectionState", status, METH_NOARGS, nullptr}, {"GetBettingGuildWarValue", net_dummy_zero, METH_VARARGS, nullptr}, - {"EnableChatInsultFilter", net_dummy_none, METH_VARARGS, nullptr}, + {"EnableChatInsultFilter", net_enable_chat_insult_filter, METH_VARARGS, nullptr}, {"SetServerInfo", net_dummy_none, METH_VARARGS, nullptr}, {"GetServerInfo", net_dummy_str, METH_VARARGS, nullptr}, - {"PreserveServerCommand", net_dummy_none, METH_VARARGS, nullptr}, - {"GetPreservedServerCommand", net_dummy_str, METH_VARARGS, nullptr}, + {"PreserveServerCommand", net_preserve_server_command, METH_VARARGS, nullptr}, + {"GetPreservedServerCommand", net_get_preserved_server_command, METH_VARARGS, nullptr}, {"StartGame", net_start_game, METH_VARARGS, nullptr}, {"Warp", net_warp, METH_VARARGS, nullptr}, {"IsTest", net_dummy_zero, METH_VARARGS, nullptr}, {"SetMarkServer", net_dummy_none, METH_VARARGS, nullptr}, - {"IsChatInsultIn", net_dummy_zero, METH_VARARGS, nullptr}, - {"IsInsultIn", net_dummy_zero, METH_VARARGS, nullptr}, - {"LoadInsultList", net_dummy_none, METH_VARARGS, nullptr}, + {"IsChatInsultIn", net_is_chat_insult_in, METH_VARARGS, nullptr}, + {"IsInsultIn", net_is_insult_in, METH_VARARGS, nullptr}, + {"LoadInsultList", net_load_insult_list, METH_VARARGS, nullptr}, {"UploadMark", net_dummy_none, METH_VARARGS, nullptr}, {"UploadSymbol", net_dummy_none, METH_VARARGS, nullptr}, - {"GetGuildID", net_dummy_zero, METH_VARARGS, nullptr}, + {"GetGuildID", netGetGuildID, METH_VARARGS, nullptr}, {"GetMainActorVID", net_get_main_actor_vid, METH_VARARGS, nullptr}, {"GetMainActorRace", net_get_main_actor_race, METH_VARARGS, nullptr}, {"GetMainActorEmpire", net_get_main_actor_empire, METH_VARARGS, nullptr}, {"GetMainActorSkillGroup", net_get_main_actor_skill_group, METH_VARARGS, nullptr}, - {"SendTargetInfoLoad", net_dummy_none, METH_VARARGS, nullptr}, + {"SendTargetInfoLoad", netTargetInfoLoad, METH_VARARGS, nullptr}, {"GetFieldMusicFileName", net_get_field_music_name, METH_VARARGS, nullptr}, {"GetFieldMusicVolume", net_get_field_music_volume, METH_VARARGS, nullptr}, {"ToggleGameDebugInfo", net_dummy_none, METH_VARARGS, nullptr}, - {"SetServerCommandParserWindow", net_dummy_none, METH_VARARGS, nullptr}, + {"SetServerCommandParserWindow", net_set_server_command_parser_window, METH_VARARGS, nullptr}, {"SetTCPRecvBufferSize", net_dummy_none, METH_VARARGS, nullptr}, {"SetTCPSendBufferSize", net_dummy_none, METH_VARARGS, nullptr}, {"SetUDPRecvBufferSize", net_dummy_none, METH_VARARGS, nullptr}, @@ -514,7 +891,7 @@ void initnet() { {"SetOfflinePhase", net_dummy_none, METH_VARARGS, nullptr}, {"IsConnect", is_connected, METH_VARARGS, nullptr}, {"SendChatPacket", net_send_chat, METH_VARARGS, nullptr}, - {"SendEmoticon", net_dummy_none, METH_VARARGS, nullptr}, + {"SendEmoticon", net_send_emoticon, METH_VARARGS, nullptr}, {"SendWhisperPacket", net_send_whisper, METH_VARARGS, nullptr}, {"SendMobileMessagePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendCharacterPositionPacket", send_character_position_packet, METH_VARARGS, nullptr}, @@ -524,57 +901,57 @@ void initnet() { {"SendShopBuyPacket", shop_buy, METH_VARARGS, nullptr}, {"SendShopSellPacket", shop_sell, METH_VARARGS, nullptr}, {"SendShopSellPacketNew", shop_sell_new, METH_VARARGS, nullptr}, - {"SendExchangeStartPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendExchangeItemAddPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendExchangeItemDelPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendExchangeElkAddPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendExchangeAcceptPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendExchangeExitPacket", net_dummy_none, METH_VARARGS, nullptr}, + {"SendExchangeStartPacket", netSendExchangeStartPacket, METH_VARARGS, nullptr}, + {"SendExchangeItemAddPacket", netSendExchangeItemAddPacket, METH_VARARGS, nullptr}, + {"SendExchangeItemDelPacket", netSendExchangeItemDelPacket, METH_VARARGS, nullptr}, + {"SendExchangeElkAddPacket", netSendExchangeElkAddPacket, METH_VARARGS, nullptr}, + {"SendExchangeAcceptPacket", netSendExchangeAcceptPacket, METH_VARARGS, nullptr}, + {"SendExchangeExitPacket", netSendExchangeExitPacket, METH_VARARGS, nullptr}, {"SendOnClickPacket", net_send_onclick, METH_VARARGS, nullptr}, - {"RegisterEmoticonString", net_dummy_none, METH_VARARGS, nullptr}, - {"SendMessengerAddByVIDPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendMessengerAddByNamePacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendMessengerRemovePacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartyInvitePacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartyInviteAnswerPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartyExitPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartyRemovePacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartyRemovePacketPID", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartyRemovePacketVID", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartySetStatePacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartyUseSkillPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPartyParameterPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendSafeboxSaveMoneyPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendSafeboxWithdrawMoneyPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendSafeboxCheckinPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendSafeboxCheckoutPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendSafeboxItemMovePacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendMallCheckoutPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendAnswerMakeGuildPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendQuestInputStringPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendQuestInputLongStringPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendQuestConfirmPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildAddMemberPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildRemoveMemberPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildChangeGradeNamePacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildChangeGradeAuthorityPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildOfferPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildPostCommentPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildDeleteCommentPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildRefreshCommentsPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildChangeMemberGradePacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildUseSkillPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildChangeMemberGeneralPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildInviteAnswerPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildChargeGSPPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildDepositMoneyPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendGuildWithdrawMoneyPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SendRequestRefineInfoPacket", net_dummy_none, METH_VARARGS, nullptr}, + {"RegisterEmoticonString", net_register_emoticon_string, METH_VARARGS, nullptr}, + {"SendMessengerAddByVIDPacket", netSendMessengerAddByVIDPacket, METH_VARARGS, nullptr}, + {"SendMessengerAddByNamePacket", netSendMessengerAddByNamePacket, METH_VARARGS, nullptr}, + {"SendMessengerRemovePacket", netSendMessengerRemovePacket, METH_VARARGS, nullptr}, + {"SendPartyInvitePacket", netSendPartyInvitePacket, METH_VARARGS, nullptr}, + {"SendPartyInviteAnswerPacket", netSendPartyInviteAnswerPacket, METH_VARARGS, nullptr}, + {"SendPartyExitPacket", netSendPartyExitPacket, METH_VARARGS, nullptr}, + {"SendPartyRemovePacket", netSendPartyRemovePacketPID, METH_VARARGS, nullptr}, + {"SendPartyRemovePacketPID", netSendPartyRemovePacketPID, METH_VARARGS, nullptr}, + {"SendPartyRemovePacketVID", netSendPartyRemovePacketVID, METH_VARARGS, nullptr}, + {"SendPartySetStatePacket", netSendPartySetStatePacket, METH_VARARGS, nullptr}, + {"SendPartyUseSkillPacket", netSendPartyUseSkillPacket, METH_VARARGS, nullptr}, + {"SendPartyParameterPacket", netSendPartyParameterPacket, METH_VARARGS, nullptr}, + {"SendSafeboxSaveMoneyPacket", netSendSafeboxSaveMoneyPacket, METH_VARARGS, nullptr}, + {"SendSafeboxWithdrawMoneyPacket", netSendSafeboxWithdrawMoneyPacket, METH_VARARGS, nullptr}, + {"SendSafeboxCheckinPacket", netSendSafeboxCheckinPacket, METH_VARARGS, nullptr}, + {"SendSafeboxCheckoutPacket", netSendSafeboxCheckoutPacket, METH_VARARGS, nullptr}, + {"SendSafeboxItemMovePacket", netSendSafeboxItemMovePacket, METH_VARARGS, nullptr}, + {"SendMallCheckoutPacket", netSendMallCheckoutPacket, METH_VARARGS, nullptr}, + {"SendAnswerMakeGuildPacket", netSendAnswerMakeGuildPacket, METH_VARARGS, nullptr}, + {"SendQuestInputStringPacket", netSendQuestInputStringPacket, METH_VARARGS, nullptr}, + {"SendQuestInputLongStringPacket", netSendQuestInputLongStringPacket, METH_VARARGS, nullptr}, + {"SendQuestConfirmPacket", netSendQuestConfirmPacket, METH_VARARGS, nullptr}, + {"SendGuildAddMemberPacket", netSendGuildAddMemberPacket, METH_VARARGS, nullptr}, + {"SendGuildRemoveMemberPacket", netSendGuildRemoveMemberPacket, METH_VARARGS, nullptr}, + {"SendGuildChangeGradeNamePacket", netSendGuildChangeGradeNamePacket, METH_VARARGS, nullptr}, + {"SendGuildChangeGradeAuthorityPacket", netSendGuildChangeGradeAuthorityPacket, METH_VARARGS, nullptr}, + {"SendGuildOfferPacket", netSendGuildOfferPacket, METH_VARARGS, nullptr}, + {"SendGuildPostCommentPacket", netSnedGuildPostCommentPacket, METH_VARARGS, nullptr}, + {"SendGuildDeleteCommentPacket", netSnedGuildDeleteCommentPacket, METH_VARARGS, nullptr}, + {"SendGuildRefreshCommentsPacket", netSendGuildRefreshCommentsPacket, METH_VARARGS, nullptr}, + {"SendGuildChangeMemberGradePacket", netSendGuildChangeMemberGradePacket, METH_VARARGS, nullptr}, + {"SendGuildUseSkillPacket", netSendGuildUseSkillPacket, METH_VARARGS, nullptr}, + {"SendGuildChangeMemberGeneralPacket", netSendGuildChangeMemberGeneralPacket, METH_VARARGS, nullptr}, + {"SendGuildInviteAnswerPacket", netSendGuildInviteAnswerPacket, METH_VARARGS, nullptr}, + {"SendGuildChargeGSPPacket", netSendGuildChargeGSPPacket, METH_VARARGS, nullptr}, + {"SendGuildDepositMoneyPacket", netSendGuildDepositMoneyPacket, METH_VARARGS, nullptr}, + {"SendGuildWithdrawMoneyPacket", netSendGuildWithdrawMoneyPacket, METH_VARARGS, nullptr}, + {"SendRequestRefineInfoPacket", netSendRequestRefineInfoPacket, METH_VARARGS, nullptr}, {"SendRefinePacket", net_send_refine_packet, METH_VARARGS, nullptr}, {"SendScriptAnswerPacket", net_send_script_answer_packet, METH_VARARGS, nullptr}, {"SendScriptButtonPacket", net_send_script_button_packet, METH_VARARGS, nullptr}, - {"SendSelectItemPacket", net_dummy_none, METH_VARARGS, nullptr}, - {"SetEmpireLanguageMode", net_dummy_none, METH_VARARGS, nullptr}, + {"SendSelectItemPacket", netSendSelectItemPacket, METH_VARARGS, nullptr}, + {"SetEmpireLanguageMode", net_set_empire_language_mode, METH_VARARGS, nullptr}, {"SetSkillGroupFake", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildSymbol", net_dummy_none, METH_VARARGS, nullptr}, {"DisconnectUploader", net_dummy_none, METH_VARARGS, nullptr}, @@ -602,7 +979,7 @@ void initnet() { {"CalendarOpen", net_dummy_none, METH_VARARGS, nullptr}, {"CalendarClose", net_dummy_none, METH_VARARGS, nullptr}, {"CalendarSend", net_dummy_none, METH_VARARGS, nullptr}, - {"SendPrivateShopSearchInfo", net_dummy_none, METH_VARARGS, nullptr}, + {"SendPrivateShopSearchInfo", netSendPrivateShopSearchInfo, METH_VARARGS, nullptr}, {"SendMiniGameCatchKingStart", net_dummy_none, METH_VARARGS, nullptr}, {"SendMiniGameCatchKingDeckCardClick", net_dummy_none, METH_VARARGS, nullptr}, {"SendMiniGameCatchKingFieldCardClick", net_dummy_none, METH_VARARGS, nullptr}, @@ -720,10 +1097,10 @@ void pump_python_net() { } } auto& stream=PythonNetworkStream::Instance(); - stream.PushRecvData(client.take_game_input()); + stream.PushRecvData(client.take_game_input(stream.RecvBufferSpace())); stream.ProcessRecvData(); if(client.status()==LoginClient::Status::Loading) { - for(auto& packet:stream.PopSendPackets()) client.send_game_packet(std::move(packet)); + for(auto& [packet,sequence]:stream.PopSendPacketsWithSequence()) client.send_game_packet(std::move(packet),sequence); } } diff --git a/src/python_net.h b/src/python_net.h index 3cb650d1..42d3c5b7 100644 --- a/src/python_net.h +++ b/src/python_net.h @@ -5,7 +5,9 @@ void register_python_net(); void reset_python_net(); void pump_python_net(); void set_mock_character(int slot, const Character& chr); +void update_player_guild(uint32_t id,const std::string& name); void set_mock_empire(std::uint8_t empire); +bool LoadInsultList(const std::string& path); // CPythonNetworkStream::LoadInsultList struct CharacterMoveState { std::uint8_t func = 0; diff --git a/src/python_offline_shop.cpp b/src/python_offline_shop.cpp new file mode 100644 index 00000000..143319c2 --- /dev/null +++ b/src/python_offline_shop.cpp @@ -0,0 +1,92 @@ +// Port of AVA2 UserInterface/PythonShop.cpp offline methods. No invented local state transitions. +#include "offline_shop_state.h" +#include "eter_net/PythonNetworkStream.h" +#include "shared/common/PythonUtils.h" +#include +#include +#include +namespace ava2 { +OfflineShopState& GetOfflineShopState() {static OfflineShopState state;return state;} +void ClearOfflineShopState() {GetOfflineShopState()={};} +namespace { +template PyObject* itemField(PyObject*,PyObject* args) { + int index;if(!PyTuple_GetInteger(args,0,&index))return Py_BuildException(); + auto* item=GetOfflineShopState().Item(uint32_t(index)); + if constexpr(field==5)return item?PyString_FromStringAndSize(item->szBuyerName,strnlen(item->szBuyerName,25)):PyString_FromString("None"); + if(!item)return PyInt_FromLong(0); + if constexpr(field==0)return PyInt_FromLong(std::bit_cast(item->vnum)); + if constexpr(field==1)return PyInt_FromLong(item->count); + if constexpr(field==2)return PyLong_FromLongLong(item->price); + if constexpr(field==3)return PyInt_FromLong(item->status); + if constexpr(field==4)return PyInt_FromLong(std::bit_cast(item->owner_id)); +} +template PyObject* detail(PyObject*,PyObject* args) { + int index,slot;if(!PyTuple_GetInteger(args,0,&index)||!PyTuple_GetInteger(args,1,&slot))return Py_BuildException(); + auto* item=GetOfflineShopState().Item(uint32_t(index)); + if constexpr(attribute) { + if(!item||slot<0||slot>=15)return Py_BuildValue("(ii)",0,0); + return Py_BuildValue("(ii)",int(item->aAttr[slot].bType),int(item->aAttr[slot].sValue)); + }else return PyInt_FromLong(item&&slot>=0&&slot<8?item->alSockets[slot]:0); +} +template PyObject* stateField(PyObject*,PyObject*) { + const auto& s=GetOfflineShopState(); + if constexpr(field==0)return PyInt_FromLong(0); + if constexpr(field==1)return PyInt_FromLong(s.hasShop); + if constexpr(field==2)return PyString_FromString(s.sign.c_str()); + if constexpr(field==3)return PyInt_FromLong(std::bit_cast(s.displayed)); + if constexpr(field==4)return PyInt_FromLong(std::bit_cast(s.watchers)); + if constexpr(field==5)return PyLong_FromLongLong(s.money); + if constexpr(field==6)return PyLong_FromLongLong(std::bit_cast(s.flag)); + if constexpr(field==7)return PyInt_FromLong(std::bit_cast(s.type)); + if constexpr(field==8)return PyInt_FromLong(s.time); +} +template PyObject* setField(PyObject*,PyObject* args) { + auto& s=GetOfflineShopState(); + if constexpr(field==0) {long long value;if(!PyTuple_GetLongLong(args,0,&value))return Py_BuildException();s.flag=uint64_t(value);} + else {int value;if(!PyTuple_GetInteger(args,0,&value))return Py_BuildException();if constexpr(field==1)s.type=uint32_t(value);else s.time=value;} + Py_RETURN_NONE; +} +PyObject* clearStock(PyObject*,PyObject*) {GetOfflineShopState().stock.clear();Py_RETURN_NONE;} +PyObject* addStock(PyObject*,PyObject* args) { + uint8_t window;uint16_t cell;int display;long long price; + if(!PyTuple_GetInteger(args,0,&window)||!PyTuple_GetInteger(args,1,&cell)||!PyTuple_GetInteger(args,2,&display)||!PyTuple_GetLongLong(args,3,&price))return Py_BuildException(); + TOfflineShopItemTable item{};item.pos={window,cell};item.display_pos=uint8_t(display);item.price=price; + GetOfflineShopState().stock[{window,cell}]=item;Py_RETURN_NONE; +} +PyObject* delStock(PyObject*,PyObject* args) { + uint8_t window;uint16_t cell;if(!PyTuple_GetInteger(args,0,&window)||!PyTuple_GetInteger(args,1,&cell))return Py_BuildException(); + GetOfflineShopState().stock.erase({window,cell});Py_RETURN_NONE; +} +PyObject* priceStock(PyObject*,PyObject* args) { + uint8_t window;uint16_t cell;if(!PyTuple_GetInteger(args,0,&window)||!PyTuple_GetInteger(args,1,&cell))return Py_BuildException(); + const auto& stock=GetOfflineShopState().stock;auto it=stock.find({window,cell});return PyLong_FromLongLong(it==stock.end()?0:it->second.price); +} +PyObject* build(PyObject*,PyObject* args) { + char* name;int vnum,title;if(!PyTuple_GetString(args,0,&name)||!PyTuple_GetInteger(args,1,&vnum)||!PyTuple_GetInteger(args,2,&title))return Py_BuildException(); + std::vector items;for(const auto& [key,item]:GetOfflineShopState().stock)items.push_back(item); + std::sort(items.begin(),items.end(),[](const auto& a,const auto& b){return a.display_pos,METH_VARARGS,nullptr},{"HasOfflineShop",stateField<1>,METH_VARARGS,nullptr}, + {"GetSign",stateField<2>,METH_VARARGS,nullptr},{"GetDisplayedCount",stateField<3>,METH_VARARGS,nullptr}, + {"GetRealWatcherCount",stateField<4>,METH_VARARGS,nullptr},{"GetCurrentOfflineShopMoney",stateField<5>,METH_VARARGS,nullptr}, + {"GetShopFlag",stateField<6>,METH_VARARGS,nullptr},{"GetShopType",stateField<7>,METH_VARARGS,nullptr},{"GetShopTime",stateField<8>,METH_VARARGS,nullptr}, + {"SetShopFlag",setField<0>,METH_VARARGS,nullptr},{"SetShopType",setField<1>,METH_VARARGS,nullptr},{"SetShopTime",setField<2>,METH_VARARGS,nullptr}, + {"GetOfflineShopItemID",itemField<0>,METH_VARARGS,nullptr},{"GetOfflineShopItemVnum",itemField<0>,METH_VARARGS,nullptr}, + {"GetOfflineShopItemCount",itemField<1>,METH_VARARGS,nullptr},{"GetOfflineShopItemPrice",itemField<2>,METH_VARARGS,nullptr}, + {"GetOfflineShopItemStatus",itemField<3>,METH_VARARGS,nullptr},{"GetOfflineShopID",itemField<4>,METH_VARARGS,nullptr}, + {"GetOfflineShopItemBuyerName",itemField<5>,METH_VARARGS,nullptr},{"GetOfflineShopItemAttribute",detail,METH_VARARGS,nullptr}, + {"GetOfflineShopItemMetinSocket",detail,METH_VARARGS,nullptr},{"ClearOfflineShopStock",clearStock,METH_VARARGS,nullptr}, + {"AddOfflineShopItemStock",addStock,METH_VARARGS,nullptr},{"DelOfflineShopItemStock",delStock,METH_VARARGS,nullptr}, + {"GetOfflineShopItemPriceReal",priceStock,METH_VARARGS,nullptr},{"BuildOfflineShop",build,METH_VARARGS,nullptr}, + {"ChangeDecoration",decoration,METH_VARARGS,nullptr},{nullptr,nullptr,0,nullptr}}; + Py_InitModule("shop",methods); +} +} diff --git a/src/python_pet_skill.cpp b/src/python_pet_skill.cpp new file mode 100644 index 00000000..4da10641 --- /dev/null +++ b/src/python_pet_skill.cpp @@ -0,0 +1,62 @@ +// Direct port of AVA2 UserInterface/PythonSkillPet.cpp. Image pointers use the existing cross-platform handle bridge. +#include "pet_skill_state.h" +#include "ava2_text_file.h" +#include "python_runtime.h" +#include "python_native_modules.h" +#include "shared/common/PythonUtils.h" +#include "eter_resource/ResourceManager.h" +#include "eter_image/GrpImage.h" +#include "eter_image/GrpImageInstance.h" +#include "python_grp.h" +#include +#include +namespace ava2 { +PetSkillState& GetPetSkillState() {static PetSkillState state;return state;} +namespace { +uint32_t image(const std::string& path) { + auto* resource=CResourceManager::Instance().GetResourcePointer(path.c_str()); + return resource&&resource->IsType(CGraphicImage::Type())?GrpRegisterImageHandle(static_cast(resource)):0; +} +PyObject* setSlot(PyObject*,PyObject* args) { + int slot,index;if(!PyTuple_GetInteger(args,0,&slot)||!PyTuple_GetInteger(args,1,&index))return Py_BadArgument(); + // AVA2 writes unchecked; reject memory corruption beyond its three-element array. + if(slot<0||slot>=3)return Py_BadArgument(); + GetPetSkillState().slots[slot]=index;return PyInt_FromLong(0); +} +PyObject* getSlot(PyObject*,PyObject* args) { + int slot;if(!PyTuple_GetInteger(args,0,&slot)||slot<0||slot>=3)return Py_BadArgument(); + return PyInt_FromLong(GetPetSkillState().slots[slot]); +} +PyObject* getIcon(PyObject*,PyObject* args) { + int index;if(!PyTuple_GetInteger(args,0,&index))return Py_BadArgument(); + const auto& records=GetPetSkillState().records;auto it=records.find(uint32_t(index)); + return PyInt_FromLong(it==records.end()?0:std::bit_cast(it->second.imageHandle)); +} +PyObject* emptySkill(PyObject*,PyObject*) {return PyInt_FromLong(std::bit_cast(image("d:/ymir work/ui/pet/skill_button/skill_enable_button.sub")));} +} +bool LoadPetSkills(const std::string& path) { + std::string text;try {text=ReadPackedText(path);}catch(const std::exception&){return false;} + auto lines=ava2TextLines(text);auto& records=GetPetSkillState().records; + // AVA2 deliberately excludes GetLineCount()-1, even when the final row has no newline. + for(size_t line=0;line+165)record.icon.resize(65); + if(fields[3]=="EMPTY")record.type=SKILLPET_TYPE_NONE; + else if(fields[3]=="PASSIVE")record.type=SKILLPET_TYPE_PASSIVE; + else if(fields[3]=="AUTO")record.type=SKILLPET_TYPE_AUTO; + // Unknown type retains the previous value on duplicate entries. + record.description=fields[4];record.delay=uint32_t(std::strtol(fields[5].c_str(),nullptr,10));record.imageHandle=image(record.icon); + } + return true; +} +void initskillpet() { + static PyMethodDef methods[]={ + {"SetSkillSlot",setSlot,METH_VARARGS,nullptr},{"GetIconImage",getIcon,METH_VARARGS,nullptr}, + {"GetSkillbySlot",getSlot,METH_VARARGS,nullptr},{"GetEmptySkill",emptySkill,METH_VARARGS,nullptr},{nullptr,nullptr,0,nullptr}}; + Py_InitModule("petskill",methods); +} +} diff --git a/src/python_quest.cpp b/src/python_quest.cpp new file mode 100644 index 00000000..96dc6ee8 --- /dev/null +++ b/src/python_quest.cpp @@ -0,0 +1,65 @@ +// Port of AVA2 UserInterface/PythonQuest.cpp, including ENABLE_MULTILANGUAGE_SYSTEM. +#include "quest_state.h" +#include "python_app.h" +#include "python_native_modules.h" +#include "eter_resource/ResourceManager.h" +#include "eter_image/GrpImageInstance.h" +#include "shared/common/PythonUtils.h" +#include +#include + +namespace ava2 { +QuestState& GetQuestState() { static QuestState state;return state; } +int32_t GetQuestTime() { return GetApplicationSeconds(); } +namespace { +QuestRecord* by_array_index(PyObject* args) { + int index; + if(!PyTuple_GetInteger(args,0,&index)) { PyErr_BadArgument();return nullptr; } + auto& data=GetQuestState().records; + if(uint32_t(index)>=data.size()) { + PyErr_Format(PyExc_RuntimeError,"Failed to find quest by index %d",index);return nullptr; + } + return &data[index]; +} +PyObject* count(PyObject*,PyObject*) { return PyInt_FromLong(GetQuestState().records.size()); } +PyObject* index(PyObject*,PyObject* args) { + auto* q=by_array_index(args);return q?PyInt_FromLong(std::bit_cast(q->index)):nullptr; +} +PyObject* last_time(PyObject*,PyObject* args) { + auto* q=by_array_index(args);return q?Py_BuildValue("(si)",q->clockName.c_str(),QuestState::remaining(*q,GetQuestTime())):nullptr; +} +PyObject* data(PyObject*,PyObject* args) { + auto* q=by_array_index(args);if(!q)return nullptr; + const auto path=q->iconFile.empty()?std::string("season1/icon/scroll_open.tga"): + "d:/ymir work/ui/game/quest/questicon/"+q->iconFile; + auto* resource=CResourceManager::Instance().GetResourcePointer(path.c_str()); + uint32_t handle=0; + if(resource && resource->IsType(CGraphicImage::Type())) + handle=GrpRegisterImageHandle(static_cast(resource)); + // Port handles replace the original Win32 pointer while retaining the Python tuple. + return Py_BuildValue("(sisi)",q->title.c_str(),int(handle),q->counterName.c_str(),q->counterValue); +} +PyObject* clear(PyObject*,PyObject*) { GetQuestState().records.clear();Py_RETURN_NONE; } +PyObject* add(PyObject*,PyObject* args) { + int type,id,clock,counter,flags;char *title,*clockName,*counterName,*icon; + if(!PyTuple_GetInteger(args,0,&type)||!PyTuple_GetInteger(args,1,&id)|| + !PyTuple_GetString(args,2,&title)||!PyTuple_GetString(args,3,&clockName)|| + !PyTuple_GetInteger(args,4,&clock)||!PyTuple_GetString(args,5,&counterName)|| + !PyTuple_GetInteger(args,6,&counter)||!PyTuple_GetString(args,7,&icon)|| + !PyTuple_GetInteger(args,8,&flags))return Py_BadArgument(); + QuestRecord q;q.index=uint32_t(id);q.title=title;q.clockName=clockName; + q.clockValue=clock;q.counterName=counterName;q.counterValue=counter;q.iconFile=icon; + if(type==1 && GetQuestState().find(q.index)) + std::cerr<<"[AVA2 TraceError] Quest with index "< #include @@ -72,8 +84,18 @@ std::string ReadPackedText(const std::string& name) { PythonRuntime::PythonRuntime(const std::filesystem::path& stdlib,const std::filesystem::path& root) { if(Py_IsInitialized()) throw std::logic_error("one embedded Python runtime allowed"); ResetPythonAppState(); + GetPetSkillState()=PetSkillState{}; ResetSkillDescriptions(); ResetShopState(); + GetQuestState().records.clear(); + GetGuildState()=GuildState{}; + GetShopSearchItems().clear(); + GetMessengerState().Reset(); + GetCubeRenewalState().Reset(); + GetBattlePassState().Reset(); + GetDropItemState().Reset(); + GetDungeonInfoState()=DungeonInfoState{}; + GetSwitchbotState()=SwitchbotState{}; if(!std::filesystem::is_regular_file(stdlib)) throw std::runtime_error("python27.zip missing"); pack_root=std::filesystem::canonical(root); static bool registered=false; @@ -132,6 +154,7 @@ PythonRuntime::PythonRuntime(const std::filesystem::path& stdlib,const std::file registered=true; } Py_FrozenFlag=1;Py_IgnoreEnvironmentFlag=1;Py_NoSiteFlag=1;Py_DontWriteBytecodeFlag=1; + CResourceManager::SetResourceRoot(std::filesystem::absolute(root)); m_resourceManager = std::make_unique(); Py_Initialize(); m_windowManager = std::make_unique(); @@ -214,6 +237,15 @@ sys.meta_path.insert(0, _AVA2PackImporter()) )PY"); } catch(...) { reset_python_net(); ClearPlayerPythonWindow(); + GetMessengerState().Reset(); + GetCubeRenewalState().Reset(); + GetBattlePassState().Reset(); + GetDropItemState().Reset(); + GetDungeonInfoState()=DungeonInfoState{}; + GetSwitchbotState()=SwitchbotState{}; + // The event sets hold weak references to Python objects. + CPythonEventManager::Instance().Destroy();CPythonChat::Instance().Destroy();CPythonSystem::Instance().Clear(); + CPythonEventManager::Instance().SetInterfaceWindow(nullptr); Py_Finalize(); if (m_windowManager) { @@ -236,6 +268,15 @@ sys.meta_path.insert(0, _AVA2PackImporter()) PythonRuntime::~PythonRuntime() { reset_python_net(); ClearPlayerPythonWindow(); + GetMessengerState().Reset(); + GetCubeRenewalState().Reset(); + GetBattlePassState().Reset(); + GetDropItemState().Reset(); + GetDungeonInfoState()=DungeonInfoState{}; + GetSwitchbotState()=SwitchbotState{}; + // The event sets hold weak references to Python objects. + CPythonEventManager::Instance().Destroy();CPythonChat::Instance().Destroy();CPythonSystem::Instance().Clear(); + CPythonEventManager::Instance().SetInterfaceWindow(nullptr); Py_Finalize(); if (m_windowManager) { diff --git a/src/python_shop_search.cpp b/src/python_shop_search.cpp new file mode 100644 index 00000000..2c4ef748 --- /dev/null +++ b/src/python_shop_search.cpp @@ -0,0 +1,55 @@ +// AVA2 UserInterface/PythonPrivateShopSearch.cpp (active Windows feature set). +#include "shop_search_state.h" +#include "python_native_modules.h" +#include "shared/common/PythonUtils.h" +#include +#include +namespace ava2 { +std::vector& GetShopSearchItems() { static std::vector items;return items; } +namespace { +TOfflineShopItemData* lookup(int index) { + auto& items=GetShopSearchItems(); + if(uint32_t(index)>=items.size()) { PyErr_Format(PyExc_RuntimeError,"Shop search index out of range: %d",index);return nullptr; } + return &items[index]; +} +template PyObject* scalar(PyObject*,PyObject* args) { + int index;if(!PyTuple_GetInteger(args,0,&index))return Py_BadArgument(); + auto* item=lookup(index);if(!item)return nullptr; + if constexpr(field==0)return PyInt_FromLong(item->count); + if constexpr(field==1)return PyLong_FromLongLong(item->price); + if constexpr(field==2)return PyInt_FromLong(std::bit_cast(item->vnum)); + if constexpr(field==3)return PyInt_FromLong(std::bit_cast(item->owner_id)); + if constexpr(field==4)return PyInt_FromLong(item->display_pos); + if constexpr(field==5)return PyInt_FromLong(std::bit_cast(item->id)); + if constexpr(field==6)return PyString_FromStringAndSize(item->szBuyerName,strnlen(item->szBuyerName,sizeof(item->szBuyerName))); +} +PyObject* count(PyObject*,PyObject*) { return PyInt_FromLong(GetShopSearchItems().size()); } +PyObject* clear(PyObject*,PyObject*) { GetShopSearchItems().clear();Py_RETURN_NONE; } +PyObject* socket(PyObject*,PyObject* args) { + int index,slot;if(!PyTuple_GetInteger(args,0,&index)||!PyTuple_GetInteger(args,1,&slot))return Py_BadArgument(); + if(slot>=int(ITEM_SOCKET_SLOT_MAX_NUM))return Py_BuildException(); + if(slot<0) { PyErr_SetString(PyExc_RuntimeError,"Shop search socket out of range");return nullptr; } + auto* item=lookup(index);return item?PyInt_FromLong(item->alSockets[slot]):nullptr; +} +PyObject* attr(PyObject*,PyObject* args) { + int index,slot;if(!PyTuple_GetInteger(args,0,&index)||!PyTuple_GetInteger(args,1,&slot))return Py_BuildException(); + if(slot<0||slot>=int(ITEM_ATTRIBUTE_SLOT_MAX_NUM))return Py_BuildValue("(ii)",0,0); + auto* item=lookup(index);return item?Py_BuildValue("(ii)",int(item->aAttr[slot].bType),int(item->aAttr[slot].sValue)):nullptr; +} +PyObject* new_name(PyObject*,PyObject* args) { + int index;if(!PyTuple_GetInteger(args,0,&index))return Py_BadArgument(); + return PyString_FromString("^"); // Original explicitly ignores the result record's name. +} +} +void initprivateShopSearch() { + static PyMethodDef methods[]={ + {"GetItemCount",count,METH_VARARGS,nullptr},{"GetSearchItemCount",scalar<0>,METH_VARARGS,nullptr}, + {"GetSearchItemPrice",scalar<1>,METH_VARARGS,nullptr},{"GetSearchItemVnum",scalar<2>,METH_VARARGS,nullptr}, + {"GetSearchItemShopVID",scalar<3>,METH_VARARGS,nullptr},{"ClearSearchItems",clear,METH_VARARGS,nullptr}, + {"GetSearchItemMetinSocket",socket,METH_VARARGS,nullptr},{"GetSearchItemAttribute",attr,METH_VARARGS,nullptr}, + {"GetSearchItemNewName",new_name,METH_VARARGS,nullptr},{"GetSearchItemPos",scalar<4>,METH_VARARGS,nullptr}, + {"GetSearchItemSeller",scalar<6>,METH_VARARGS,nullptr},{"GetSearchItemID",scalar<5>,METH_VARARGS,nullptr}, + {nullptr,nullptr,0,nullptr}}; + Py_InitModule("privateShopSearch",methods); +} +} diff --git a/src/python_switchbot.cpp b/src/python_switchbot.cpp new file mode 100644 index 00000000..444dccbc --- /dev/null +++ b/src/python_switchbot.cpp @@ -0,0 +1,75 @@ +// Direct port of AVA2 PythonSwitchbot.cpp. Start/Stop send requests only; server +// UPDATE controls active/finished. The exposed five slots sit over six native slots. +#include "switchbot_state.h" +#include "python_native_modules.h" +#include "python_gameplay_modules.h" +#include "eter_net/PythonNetworkStream.h" +#include "shared/common/PythonUtils.h" +#include +namespace ava2 { +SwitchbotState& GetSwitchbotState() {static SwitchbotState state;return state;} +int SwitchbotState::AttributeSet(uint8_t slot) const { + if(slot>=SWITCHBOT_SLOT_COUNT)return -1; + int type=0,sub=0;if(!GetItemTypeAndSubType(GetPlayerItemData(11,slot).vnum,&type,&sub))return -1; + // ItemData.h: weapon=1, arrow=6, armor=2, costume=28, rings=36. + if(type==1)return sub==6?-1:ATTRIBUTE_SET_WEAPON; + if(type==36)return ATTRIBUTE_SET_NEW_RINGS; + if(type==2 || type==28) { + switch(sub) { + case 0:return ATTRIBUTE_SET_BODY;case 1:return ATTRIBUTE_SET_HEAD;case 2:return ATTRIBUTE_SET_SHIELD; + case 3:return ATTRIBUTE_SET_WRIST;case 4:return ATTRIBUTE_SET_FOOTS;case 5:return ATTRIBUTE_SET_NECK; + case 6:return ATTRIBUTE_SET_EAR;case 8:return ATTRIBUTE_SET_PENDANT; + } + } + return -1; +} +void SwitchbotState::ClearSlot(uint8_t slot) { + if(slot>=SWITCHBOT_SLOT_COUNT)return; + table.active[slot]=0;table.items[slot]=0; + std::memset(table.alternatives[slot],0,sizeof(table.alternatives[slot])); + // Original ClearSlot does not reset finished or the player's item data. +} +namespace { +PyObject* active(PyObject*,PyObject* args) {uint8_t slot;if(!PyTuple_GetByte(args,0,&slot))return Py_BuildException();return PyInt_FromLong(slot<6 && GetSwitchbotState().table.active[slot]!=0);} +PyObject* finished(PyObject*,PyObject* args) {uint8_t slot;if(!PyTuple_GetByte(args,0,&slot))return Py_BuildException();return PyInt_FromLong(slot<6 && GetSwitchbotState().table.finished[slot]!=0);} +PyObject* get(PyObject*,PyObject* args) { + uint8_t slot,alt,i;if(!PyTuple_GetByte(args,0,&slot)||!PyTuple_GetByte(args,1,&alt)||!PyTuple_GetByte(args,2,&i))return Py_BuildException(); + if(slot>=6 || alt>=2 || i>=5)return Py_BuildValue("ii",0,0); + const auto a=GetSwitchbotState().table.alternatives[slot][alt].attributes[i];return Py_BuildValue("ii",int(a.bType),int(a.sValue)); +} +PyObject* set(PyObject*,PyObject* args) { + uint8_t slot,alt,i,type;int value; + if(!PyTuple_GetByte(args,0,&slot)||!PyTuple_GetByte(args,1,&alt)||!PyTuple_GetByte(args,2,&i)||!PyTuple_GetByte(args,3,&type)||!PyTuple_GetInteger(args,4,&value))return Py_BuildException(); + if(slot<6 && alt<2 && i<5)GetSwitchbotState().table.alternatives[slot][alt].attributes[i]={type,int16_t(value)}; + Py_RETURN_NONE; +} +PyObject* clear(PyObject*,PyObject* args) {uint8_t slot;if(!PyTuple_GetByte(args,0,&slot))return Py_BuildException();GetSwitchbotState().ClearSlot(slot);Py_RETURN_NONE;} +PyObject* attributes(PyObject*,PyObject* args) { + uint8_t slot;if(!PyTuple_GetByte(args,0,&slot))return Py_BuildException();auto* list=PyList_New(0); + const auto& state=GetSwitchbotState();int set=state.AttributeSet(slot);if(set<0)return list; + auto it=state.attributes.find(uint8_t(set));if(it==state.attributes.end())return list; + for(const auto& [type,value]:it->second) {auto* pair=Py_BuildValue("(ii)",int(type),int(int16_t(value)));PyList_Append(list,pair);Py_DECREF(pair);} + return list; +} +PyObject* max_value(PyObject*,PyObject* args) { + uint8_t slot,type;if(!PyTuple_GetByte(args,0,&slot)||!PyTuple_GetByte(args,1,&type))return Py_BuildException(); + const auto& state=GetSwitchbotState();int set=state.AttributeSet(slot);if(set<0)return PyInt_FromLong(0); + auto it=state.attributes.find(uint8_t(set));if(it==state.attributes.end())return PyInt_FromLong(0); + auto found=it->second.find(type);return PyInt_FromLong(found==it->second.end()?0:found->second); +} +template PyObject* request(PyObject*,PyObject* args) { + uint8_t slot;if(!PyTuple_GetByte(args,0,&slot))return Py_BuildException(); + // Original wrapper uses > rather than >=; slot6 sends a header without alternatives. + if(slot<=6)PythonNetworkStream::Instance().SendSwitchbotPacket(Start,slot); + Py_RETURN_NONE; +} +} +void initSwitchbot() { + static PyMethodDef methods[]={ + {"IsActive",active,METH_VARARGS,nullptr},{"IsFinished",finished,METH_VARARGS,nullptr}, + {"GetAttribute",get,METH_VARARGS,nullptr},{"SetAttribute",set,METH_VARARGS,nullptr}, + {"GetAttributesForSet",attributes,METH_VARARGS,nullptr},{"GetAttributeMaxValue",max_value,METH_VARARGS,nullptr}, + {"ClearSlot",clear,METH_VARARGS,nullptr},{"Start",request,METH_VARARGS,nullptr},{"Stop",request,METH_VARARGS,nullptr},{nullptr,nullptr,0,nullptr}}; + auto* m=Py_InitModule("switchbot",methods);PyModule_AddIntConstant(m,"SLOT_COUNT",SWITCHBOT_SLOT_COUNT_REAL);PyModule_AddIntConstant(m,"ALTERNATIVE_COUNT",SWITCHBOT_ALTERNATIVE_COUNT); +} +} diff --git a/src/python_system.cpp b/src/python_system.cpp index e0766496..3d0570b6 100644 --- a/src/python_system.cpp +++ b/src/python_system.cpp @@ -1,151 +1,1603 @@ +// Provenance: AVA2 UserInterface/PythonSystem.cpp and PythonSystemModule.cpp (see python_system.h). +// Platform substitutions: D3D adapter modes -> SDL display modes, GetSystemMetrics(SM_C?FULLSCREEN) +// -> SDL usable display bounds, CSoundManager -> ava2::SoundManager, stricmp -> SDL_strcasecmp. #include "python_system.h" -#include -#include +#include "eter_sound/SoundManager.h" +#include "shared/common/PythonUtils.h" +#include +#include +#include +#include +#include +#include namespace ava2 { + +int g_iLoadingDelayTime = 1; + namespace { -int s_width = 1280; -int s_height = 720; -int s_bpp = 32; -float s_music_volume = 1.0f; -float s_sound_volume = 1.0f; -int s_shadow_level = 3; -std::string s_save_id = ""; -bool s_is_save_id = false; -bool s_view_chat = true; -bool s_always_show_name = true; -bool s_show_damage = true; -bool s_show_sales_text = true; +#define DEFAULT_VALUE_ALWAYS_SHOW_NAME true -PyObject* sys_get_width(PyObject*, PyObject*) { return PyInt_FromLong(s_width); } -PyObject* sys_get_height(PyObject*, PyObject*) { return PyInt_FromLong(s_height); } -PyObject* sys_set_width(PyObject*, PyObject* args) { if(!PyArg_ParseTuple(args, "i", &s_width)) return nullptr; Py_RETURN_NONE; } -PyObject* sys_set_height(PyObject*, PyObject* args) { if(!PyArg_ParseTuple(args, "i", &s_height)) return nullptr; Py_RETURN_NONE; } - -PyObject* sys_get_music_volume(PyObject*, PyObject*) { return PyFloat_FromDouble(s_music_volume); } -PyObject* sys_get_sound_volume(PyObject*, PyObject*) { return PyFloat_FromDouble(s_sound_volume); } -PyObject* sys_set_music_volume(PyObject*, PyObject* args) { if(!PyArg_ParseTuple(args, "f", &s_music_volume)) return nullptr; Py_RETURN_NONE; } -PyObject* sys_set_sound_volume(PyObject*, PyObject* args) { if(!PyArg_ParseTuple(args, "f", &s_sound_volume)) return nullptr; Py_RETURN_NONE; } - -PyObject* sys_get_shadow_level(PyObject*, PyObject*) { return PyInt_FromLong(s_shadow_level); } -PyObject* sys_set_shadow_level(PyObject*, PyObject* args) { if(!PyArg_ParseTuple(args, "i", &s_shadow_level)) return nullptr; Py_RETURN_NONE; } - -PyObject* sys_is_save_id(PyObject*, PyObject*) { return PyInt_FromLong(s_is_save_id ? 1 : 0); } -PyObject* sys_get_save_id(PyObject*, PyObject*) { return PyString_FromString(s_save_id.c_str()); } -PyObject* sys_set_save_id(PyObject*, PyObject* args) { - int flag = 0; const char* id = ""; - if(!PyArg_ParseTuple(args, "is", &flag, &id)) return nullptr; - s_is_save_id = (flag != 0); s_save_id = id ? id : ""; - Py_RETURN_NONE; +std::string& ConfigDirectory() +{ + static std::string s_directory; + return s_directory; } -PyObject* sys_is_view_chat(PyObject*, PyObject*) { return PyInt_FromLong(s_view_chat ? 1 : 0); } -PyObject* sys_set_view_chat(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; s_view_chat = (f != 0); Py_RETURN_NONE; } +void PutInt32(unsigned char* p, int32_t value) +{ + const uint32_t u = static_cast(value); + for (int i = 0; i < 4; ++i) + p[i] = static_cast(u >> (i * 8)); +} -PyObject* sys_is_always_show_name(PyObject*, PyObject*) { return PyInt_FromLong(s_always_show_name ? 1 : 0); } -PyObject* sys_set_always_show_name(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; s_always_show_name = (f != 0); Py_RETURN_NONE; } - -PyObject* sys_dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); } -PyObject* sys_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); } -PyObject* sys_dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 1024, 768, 32); } -PyObject* sys_dummy_float_zero(PyObject*, PyObject*) { return PyFloat_FromDouble(0.0); } -PyObject* sys_dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; } +int32_t GetInt32(const unsigned char* p) +{ + uint32_t u = 0; + for (int i = 0; i < 4; ++i) + u |= uint32_t(p[i]) << (i * 8); + return static_cast(u); +} } // namespace -void initsystemSetting() { - static PyMethodDef methods[] = { - {"GetWidth", sys_get_width, METH_VARARGS, nullptr}, - {"GetHeight", sys_get_height, METH_VARARGS, nullptr}, - {"GetMusicVolume", sys_get_music_volume, METH_VARARGS, nullptr}, - {"GetSoundVolume", sys_get_sound_volume, METH_VARARGS, nullptr}, - {"SetMusicVolume", sys_set_music_volume, METH_VARARGS, nullptr}, - {"SetSoundVolumef", sys_set_sound_volume, METH_VARARGS, nullptr}, - {"GetShadowLevel", sys_get_shadow_level, METH_VARARGS, nullptr}, - {"SetShadowLevel", sys_set_shadow_level, METH_VARARGS, nullptr}, - {"SetShadow", sys_dummy_none, METH_VARARGS, nullptr}, - {"IsShadow", sys_dummy_zero, METH_VARARGS, nullptr}, - {"isSaveID", sys_is_save_id, METH_VARARGS, nullptr}, - {"GetSaveID", sys_get_save_id, METH_VARARGS, nullptr}, - {"SetSaveID", sys_set_save_id, METH_VARARGS, nullptr}, - {"IsViewChat", sys_is_view_chat, METH_VARARGS, nullptr}, - {"SetViewChatFlag", sys_set_view_chat, METH_VARARGS, nullptr}, - {"IsAlwaysShowName", sys_is_always_show_name, METH_VARARGS, nullptr}, - {"SetAlwaysShowNameFlag", sys_set_always_show_name, METH_VARARGS, nullptr}, - {"IsShowDamage", sys_dummy_one, METH_VARARGS, nullptr}, - {"SetShowDamageFlag", sys_dummy_none, METH_VARARGS, nullptr}, - {"IsShowSalesText", sys_dummy_one, METH_VARARGS, nullptr}, - {"SetShowSalesTextFlag", sys_dummy_none, METH_VARARGS, nullptr}, - {"IsShowOutline", sys_dummy_one, METH_VARARGS, nullptr}, - {"SetShowOutlineFlag", sys_dummy_none, METH_VARARGS, nullptr}, - {"IsSoftwareCursor", sys_dummy_zero, METH_VARARGS, nullptr}, - {"isInterfaceConfig", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SaveWindowStatus", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetWindowStatus", sys_dummy_zero, METH_VARARGS, nullptr}, - {"GetResolutionCount", sys_dummy_one, METH_VARARGS, nullptr}, - {"GetFrequencyCount", sys_dummy_one, METH_VARARGS, nullptr}, - {"GetCurrentResolution", sys_dummy_tuple3, METH_VARARGS, nullptr}, - {"GetResolution", sys_dummy_tuple3, METH_VARARGS, nullptr}, - {"GetFrequency", sys_dummy_zero, METH_VARARGS, nullptr}, - {"ApplyConfig", sys_dummy_none, METH_VARARGS, nullptr}, - {"SetConfig", sys_dummy_none, METH_VARARGS, nullptr}, - {"SaveConfig", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetConfig", sys_dummy_none, METH_VARARGS, nullptr}, - {"SetInterfaceHandler", sys_dummy_none, METH_VARARGS, nullptr}, - {"DestroyInterfaceHandler", sys_dummy_none, METH_VARARGS, nullptr}, - {"ReserveResource", sys_dummy_none, METH_VARARGS, nullptr}, - {"SetCollectEquipment", sys_dummy_none, METH_VARARGS, nullptr}, - {"IsCollectEquipment", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetFastPickup", sys_dummy_none, METH_VARARGS, nullptr}, - {"IsEnabledFastPickup", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetSnowTexturesMode", sys_dummy_none, METH_VARARGS, nullptr}, - {"IsSnowTexturesMode", sys_dummy_zero, METH_VARARGS, nullptr}, - {"IsShowMobAIFlag", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetShowMobAIFlag", sys_dummy_none, METH_VARARGS, nullptr}, - {"IsShowMobLevel", sys_dummy_one, METH_VARARGS, nullptr}, - {"SetShowMobLevel", sys_dummy_none, METH_VARARGS, nullptr}, - {"SetShopNamesRange", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetShopNamesRange", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetQuestIconMode", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetQuestIconMode", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetCountryFlag", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetCountryFlag", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetAffectIcons", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetAffectIcons", sys_dummy_zero, METH_VARARGS, nullptr}, - {"GetFOVLevel", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetFOVLevel", sys_dummy_none, METH_VARARGS, nullptr}, - {"SetEffectLevel", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetEffectLevel", sys_dummy_zero, METH_VARARGS, nullptr}, - {"GetPetRender", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetPetRender", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetMountRender", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetMountRender", sys_dummy_none, METH_VARARGS, nullptr}, - {"SetShopNameStatus", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetShopNameStatus", sys_dummy_zero, METH_VARARGS, nullptr}, - {"GetNightMode", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetNightMode", sys_dummy_none, METH_VARARGS, nullptr}, - {"SetStuffMessage", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetStuffMessage", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetDungeonTrack", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetDungeonTrack", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetBossTrack", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetBossTrack", sys_dummy_zero, METH_VARARGS, nullptr}, - {"SetMapObjectDistance", sys_dummy_none, METH_VARARGS, nullptr}, - {"GetMapObjectDistance", sys_dummy_zero, METH_VARARGS, nullptr}, - {nullptr, nullptr, 0, nullptr} +CPythonSystem& CPythonSystem::Instance() +{ + static CPythonSystem s_instance; + return s_instance; +} + +void CPythonSystem::SetConfigDirectory(const std::string& directory) +{ + ConfigDirectory() = directory; +} + +const std::string& CPythonSystem::GetConfigDirectory() +{ + return ConfigDirectory(); +} + +std::string CPythonSystem::__ConfigPath(const char* c_szFileName) const +{ + const std::string& directory = ConfigDirectory(); + if (directory.empty()) + return c_szFileName; + if (directory.back() == '/' || directory.back() == '\\') + return directory + c_szFileName; + return directory + "/" + c_szFileName; +} + +void CPythonSystem::SetInterfaceHandler(PyObject* poHandler) +{ + // NOTE: the reference count is not changed; the handler's __del__ clears it (levites). + m_poInterfaceHandler = poHandler; +} + +void CPythonSystem::DestroyInterfaceHandler() +{ + m_poInterfaceHandler = nullptr; +} + +void CPythonSystem::SaveWindowStatus(int iIndex, int iVisible, int iMinimized, int ix, int iy, int iHeight) +{ + // Windows indexes m_WindowStatus unchecked; an out-of-range index is dropped here. + if (iIndex < 0 || iIndex >= WINDOW_MAX_NUM) + return; + + m_WindowStatus[iIndex].isVisible = iVisible; + m_WindowStatus[iIndex].isMinimized = iMinimized; + m_WindowStatus[iIndex].ixPosition = ix; + m_WindowStatus[iIndex].iyPosition = iy; + m_WindowStatus[iIndex].iHeight = iHeight; +} + +void CPythonSystem::ClearDisplaySettings() +{ + memset(m_ResolutionList, 0, sizeof(TResolution) * RESOLUTION_MAX_NUM); + m_ResolutionCount = 0; +} + +void CPythonSystem::AddDisplayMode(uint32_t width, uint32_t height, uint32_t bpp, uint32_t frequency) +{ + // Only 800x600 and up. + if (width < 800 || height < 600) + return; + + // Only 16 and 32 bpp (D3DFMT_R5G6B5 / D3DFMT_X8R8G8B8). + if (bpp != 16 && bpp != 32) + return; + + for (int i = 0; i < m_ResolutionCount; ++i) + { + TResolution& r = m_ResolutionList[i]; + if (r.bpp != bpp || r.width != width || r.height != height) + continue; + + // Same resolution: only the frequency is new. + for (int j = 0; j < r.frequency_count; ++j) + if (r.frequency[j] == frequency) + return; + + // Windows guards with FREQUENCY_MAX_NUM (30) against a 20-entry array; the array bound is used. + if (r.frequency_count < int(sizeof(r.frequency) / sizeof(r.frequency[0]))) + r.frequency[r.frequency_count++] = frequency; + return; + } + + if (m_ResolutionCount < RESOLUTION_MAX_NUM) + { + TResolution& r = m_ResolutionList[m_ResolutionCount]; + r.width = width; + r.height = height; + r.bpp = bpp; + r.frequency[0] = frequency; + r.frequency_count = 1; + ++m_ResolutionCount; + } +} + +void CPythonSystem::GetDisplaySettings() +{ + ClearDisplaySettings(); + + if (!SDL_WasInit(SDL_INIT_VIDEO)) + return; + + int count = 0; + SDL_DisplayMode** modes = SDL_GetFullscreenDisplayModes(SDL_GetPrimaryDisplay(), &count); + if (!modes) + return; + + for (int i = 0; i < count; ++i) + { + const SDL_DisplayMode* mode = modes[i]; + const uint32_t bpp = uint32_t(SDL_BYTESPERPIXEL(mode->format)) * 8; + AddDisplayMode(uint32_t(mode->w), uint32_t(mode->h), bpp, uint32_t(std::lround(mode->refresh_rate))); + } + SDL_free(modes); +} + +int CPythonSystem::GetResolutionCount() +{ + return m_ResolutionCount; +} + +int CPythonSystem::GetFrequencyCount(int index) +{ + if (index >= m_ResolutionCount) + return 0; + + return m_ResolutionList[index].frequency_count; +} + +bool CPythonSystem::GetResolution(int index, uint32_t* width, uint32_t* height, uint32_t* bpp) +{ + if (index >= m_ResolutionCount) + return false; + + *width = m_ResolutionList[index].width; + *height = m_ResolutionList[index].height; + *bpp = m_ResolutionList[index].bpp; + return true; +} + +bool CPythonSystem::GetFrequency(int index, int freq_index, uint32_t* frequncy) +{ + if (index >= m_ResolutionCount) + return false; + + if (freq_index >= m_ResolutionList[index].frequency_count) + return false; + + *frequncy = m_ResolutionList[index].frequency[freq_index]; + return true; +} + +int CPythonSystem::GetResolutionIndex(uint32_t width, uint32_t height, uint32_t bit) +{ + uint32_t re_width, re_height, re_bit; + int i = 0; + + while (GetResolution(i, &re_width, &re_height, &re_bit)) + { + if (re_width == width) + if (re_height == height) + if (re_bit == bit) + return i; + i++; + } + + return 0; +} + +int CPythonSystem::GetFrequencyIndex(int res_index, uint32_t frequency) +{ + uint32_t re_frequency; + int i = 0; + + while (GetFrequency(res_index, i, &re_frequency)) + { + if (re_frequency == frequency) + return i; + + i++; + } + + return 0; +} + +uint32_t CPythonSystem::GetWidth() +{ + return m_Config.width; +} + +uint32_t CPythonSystem::GetHeight() +{ + return m_Config.height; +} + +uint32_t CPythonSystem::GetBPP() +{ + return m_Config.bpp; +} + +uint32_t CPythonSystem::GetFrequency() +{ + return m_Config.frequency; +} + +bool CPythonSystem::IsNoSoundCard() +{ + return m_Config.bNoSoundCard; +} + +bool CPythonSystem::IsSoftwareCursor() +{ + return m_Config.is_software_cursor; +} + +float CPythonSystem::GetMusicVolume() +{ + return m_Config.music_volume; +} + +int CPythonSystem::GetSoundVolume() +{ + return m_Config.voice_volume; +} + +void CPythonSystem::SetMusicVolume(float fVolume) +{ + m_Config.music_volume = fVolume; +} + +void CPythonSystem::SetSoundVolumef(float fVolume) +{ + m_Config.voice_volume = uint8_t(int(5 * fVolume)); +} + +int CPythonSystem::GetDistance() +{ + return m_Config.iDistance; +} + +int CPythonSystem::GetShadowLevel() +{ + return m_Config.iShadowLevel; +} + +void CPythonSystem::SetShadowLevel(unsigned int level) +{ + m_Config.iShadowLevel = int(std::min(level, 5u)); + // CPythonBackground::RefreshShadowLevel: no CPythonBackground in this port yet (PORT-PLAN pass 25). +} + +int CPythonSystem::IsSaveID() +{ + return m_Config.isSaveID; +} + +const char* CPythonSystem::GetSaveID() +{ + return m_Config.SaveID; +} + +bool CPythonSystem::isViewCulling() +{ + return m_Config.is_object_culling; +} + +void CPythonSystem::SetSaveID(int iValue, const char* c_szSaveID) +{ + if (iValue != 1) + return; + + m_Config.isSaveID = iValue; + strncpy(m_Config.SaveID, c_szSaveID, sizeof(m_Config.SaveID) - 1); +} + +CPythonSystem::TConfig* CPythonSystem::GetConfig() +{ + return &m_Config; +} + +void CPythonSystem::SetConfig(TConfig* pNewConfig) +{ + m_Config = *pNewConfig; +} + +void CPythonSystem::SetDefaultConfig() +{ + memset(&m_Config, 0, sizeof(m_Config)); + + m_Config.width = 1024; + m_Config.height = 768; + m_Config.bpp = 32; + m_Config.bWindowed = false; + + m_Config.is_software_cursor = false; + m_Config.is_object_culling = true; + m_Config.iDistance = 3; + + m_Config.gamma = 3; + m_Config.music_volume = 1.0f; + m_Config.voice_volume = 5; + + m_Config.bDecompressDDS = 0; + m_Config.bSoftwareTiling = 0; + m_Config.iShadowLevel = 3; + m_Config.bViewChat = true; + m_Config.bAlwaysShowName = DEFAULT_VALUE_ALWAYS_SHOW_NAME; + m_Config.bShowDamage = true; + m_Config.bShowSalesText = true; + m_Config.bShowMobAIFlag = true; + m_Config.bShowMobLevel = true; + m_Config.bSnowTexturesMode = false; + m_Config.shopnames_range = 0; + m_Config.questLetter = true; + m_Config.countryFlag = true; + m_Config.affectIcons = true; + m_Config.iFOVLevel = 30.0f; + m_Config.iEffectLevel = 0; + m_Config.bPetStatus = true; + m_Config.bMountStatus = true; + m_Config.bNpcStatus = true; + m_Config.bNightMode = false; + m_Config.bMessage = true; + m_Config.bDungeonTrack = false; + m_Config.bBossTrack = false; + m_Config.fobjectDist = 25600.0; +} + +bool CPythonSystem::IsWindowed() +{ + return m_Config.bWindowed; +} + +bool CPythonSystem::IsViewChat() +{ + return m_Config.bViewChat; +} + +void CPythonSystem::SetViewChatFlag(int iFlag) +{ + m_Config.bViewChat = iFlag == 1 ? true : false; +} + +bool CPythonSystem::IsAlwaysShowName() +{ + return m_Config.bAlwaysShowName; +} + +void CPythonSystem::SetAlwaysShowNameFlag(int iFlag) +{ + m_Config.bAlwaysShowName = iFlag == 1 ? true : false; +} + +bool CPythonSystem::IsShowDamage() +{ + return m_Config.bShowDamage; +} + +void CPythonSystem::SetShowDamageFlag(int iFlag) +{ + m_Config.bShowDamage = iFlag == 1 ? true : false; +} + +bool CPythonSystem::IsShowSalesText() +{ + return m_Config.bShowSalesText; +} + +void CPythonSystem::SetShowSalesTextFlag(int iFlag) +{ + m_Config.bShowSalesText = iFlag == 1 ? true : false; +} + +bool CPythonSystem::IsShowMobAIFlag() +{ + return m_Config.bShowMobAIFlag; +} + +void CPythonSystem::SetShowMobAIFlagFlag(int iFlag) +{ + m_Config.bShowMobAIFlag = iFlag == 1 ? true : false; +} + +bool CPythonSystem::IsShowMobLevel() +{ + return m_Config.bShowMobLevel; +} + +void CPythonSystem::SetShowMobLevelFlag(int iFlag) +{ + m_Config.bShowMobLevel = iFlag == 1 ? true : false; +} + +bool CPythonSystem::IsSnowTexturesMode() +{ + return m_Config.bSnowTexturesMode; +} + +void CPythonSystem::SetSnowTexturesMode(int iFlag) +{ + m_Config.bSnowTexturesMode = iFlag == 1 ? true : false; +} + +bool CPythonSystem::IsAutoTiling() +{ + if (m_Config.bSoftwareTiling == 0) + return true; + + return false; +} + +void CPythonSystem::SetSoftwareTiling(bool isEnable) +{ + if (isEnable) + m_Config.bSoftwareTiling = 1; + else + m_Config.bSoftwareTiling = 2; +} + +bool CPythonSystem::IsSoftwareTiling() +{ + if (m_Config.bSoftwareTiling == 1) + return true; + + return false; +} + +bool CPythonSystem::IsUseDefaultIME() +{ + return m_Config.bUseDefaultIME; +} + +void CPythonSystem::SetFOVLevel(const float fFOV) +{ + m_Config.iFOVLevel = std::min(std::max(fFOV, 30.0f), 100.0f); +} + +void CPythonSystem::SetObjectDistance(float fDist) +{ + if (fDist > 25600.0) + fDist = 25600.0; + m_Config.fobjectDist = fDist; +} + +bool CPythonSystem::LoadConfig() +{ + FILE* fp = fopen(__ConfigPath("metin2.cfg").c_str(), "rt"); + if (!fp) + return false; + + char buf[256]; + char command[256]; + char value[256]; + + while (fgets(buf, 256, fp)) + { + if (sscanf(buf, " %255s %255s\n", command, value) == EOF) + break; + + if (!SDL_strcasecmp(command, "WIDTH")) + m_Config.width = atoi(value); + else if (!SDL_strcasecmp(command, "HEIGHT")) + m_Config.height = atoi(value); + else if (!SDL_strcasecmp(command, "BPP")) + m_Config.bpp = atoi(value); + else if (!SDL_strcasecmp(command, "FREQUENCY")) + m_Config.frequency = atoi(value); + else if (!SDL_strcasecmp(command, "SOFTWARE_CURSOR")) + m_Config.is_software_cursor = atoi(value) ? true : false; + else if (!SDL_strcasecmp(command, "OBJECT_CULLING")) + m_Config.is_object_culling = atoi(value) ? true : false; + else if (!SDL_strcasecmp(command, "VISIBILITY")) + m_Config.iDistance = atoi(value); + else if (!SDL_strcasecmp(command, "MUSIC_VOLUME")) { + if (strchr(value, '.') == 0) { // Old compatiability + m_Config.music_volume = std::pow(10.0f, (-1.0f + (((float)atoi(value)) / 5.0f))); + if (atoi(value) == 0) + m_Config.music_volume = 0.0f; + } else + m_Config.music_volume = float(atof(value)); + } else if (!SDL_strcasecmp(command, "VOICE_VOLUME")) + m_Config.voice_volume = uint8_t(char(atoi(value))); + else if (!SDL_strcasecmp(command, "GAMMA")) + m_Config.gamma = atoi(value); + else if (!SDL_strcasecmp(command, "IS_SAVE_ID")) + m_Config.isSaveID = atoi(value); + else if (!SDL_strcasecmp(command, "SAVE_ID")) + strncpy(m_Config.SaveID, value, 20); + else if (!SDL_strcasecmp(command, "PRE_LOADING_DELAY_TIME")) + g_iLoadingDelayTime = atoi(value); + else if (!SDL_strcasecmp(command, "WINDOWED")) + m_Config.bWindowed = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "USE_DEFAULT_IME")) + m_Config.bUseDefaultIME = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "SOFTWARE_TILING")) + m_Config.bSoftwareTiling = uint8_t(atoi(value)); + else if (!SDL_strcasecmp(command, "SHADOW_LEVEL")) + m_Config.iShadowLevel = atoi(value); + else if (!SDL_strcasecmp(command, "DECOMPRESSED_TEXTURE")) + m_Config.bDecompressDDS = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "NO_SOUND_CARD")) + m_Config.bNoSoundCard = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "VIEW_CHAT")) + m_Config.bViewChat = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "ALWAYS_VIEW_NAME")) + m_Config.bAlwaysShowName = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "SHOW_DAMAGE")) + m_Config.bShowDamage = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "SHOW_SALESTEXT")) + m_Config.bShowSalesText = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "SHOW_OUTLINE")) + m_Config.bShowOutline = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "SHOW_MOBAIFLAG")) + m_Config.bShowMobAIFlag = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "SHOW_MOBLEVEL")) + m_Config.bShowMobLevel = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "SNOW_TEXTURE_MODE")) + m_Config.bSnowTexturesMode = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "SHOW_SHADOW")) + m_Config.bShowShadow = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "QUEST_LETTER")) + m_Config.questLetter = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "COUNTRY_FLAG")) + m_Config.countryFlag = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "AFFECT_ICONS")) + m_Config.affectIcons = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "shop_range")) + m_Config.shopnames_range = uint8_t(atoi(value)); + else if (!SDL_strcasecmp(command, "perspective")) + m_Config.iFOVLevel = float(atof(value)); + else if (!SDL_strcasecmp(command, "effect_level")) + m_Config.iEffectLevel = uint8_t(atoi(value)); + else if (!SDL_strcasecmp(command, "pet_status")) + m_Config.bPetStatus = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "mount_status")) + m_Config.bMountStatus = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "npc_status")) + m_Config.bNpcStatus = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "night_mode")) + m_Config.bNightMode = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "special_message")) + m_Config.bMessage = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "DUNGEON_TRACK")) + m_Config.bDungeonTrack = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "BOSS_TRACK")) + m_Config.bBossTrack = atoi(value) == 1 ? true : false; + else if (!SDL_strcasecmp(command, "OBJECT_DIST")) + m_Config.fobjectDist = float(atof(value) > 25600.0 ? 25600.0 : atof(value)); + } + + if (m_Config.bWindowed && SDL_WasInit(SDL_INIT_VIDEO)) + { + // GetSystemMetrics(SM_CXFULLSCREEN / SM_CYFULLSCREEN): the primary display's client area. + SDL_Rect bounds{}; + if (SDL_GetDisplayUsableBounds(SDL_GetPrimaryDisplay(), &bounds)) + { + const unsigned screen_width = unsigned(bounds.w); + const unsigned screen_height = unsigned(bounds.h); + + if (m_Config.width >= screen_width) + m_Config.width = screen_width; + if (m_Config.height >= screen_height) + m_Config.height = screen_height; + } + } + + m_OldConfig = m_Config; + + fclose(fp); + return true; +} + +bool CPythonSystem::SaveConfig() +{ + FILE* fp = fopen(__ConfigPath("metin2.cfg").c_str(), "wt"); + if (!fp) + return false; + + fprintf(fp, "WIDTH %d\n" + "HEIGHT %d\n" + "BPP %d\n" + "FREQUENCY %d\n" + "SOFTWARE_CURSOR %d\n" + "OBJECT_CULLING %d\n" + "VISIBILITY %d\n" + "MUSIC_VOLUME %.3f\n" + "VOICE_VOLUME %d\n" + "GAMMA %d\n" + "IS_SAVE_ID %d\n" + "SAVE_ID %s\n" + "PRE_LOADING_DELAY_TIME %d\n" + "DECOMPRESSED_TEXTURE %d\n", + int(m_Config.width), + int(m_Config.height), + int(m_Config.bpp), + int(m_Config.frequency), + int(m_Config.is_software_cursor), + int(m_Config.is_object_culling), + m_Config.iDistance, + double(m_Config.music_volume), + int(m_Config.voice_volume), + m_Config.gamma, + m_Config.isSaveID, + m_Config.SaveID, + g_iLoadingDelayTime, + int(m_Config.bDecompressDDS)); + + if (m_Config.bWindowed == 1) + fprintf(fp, "WINDOWED %d\n", int(m_Config.bWindowed)); + if (m_Config.bViewChat == 0) + fprintf(fp, "VIEW_CHAT %d\n", int(m_Config.bViewChat)); + if (m_Config.bAlwaysShowName != DEFAULT_VALUE_ALWAYS_SHOW_NAME) + fprintf(fp, "ALWAYS_VIEW_NAME %d\n", int(m_Config.bAlwaysShowName)); + if (m_Config.bShowDamage == 0) + fprintf(fp, "SHOW_DAMAGE %d\n", int(m_Config.bShowDamage)); + if (m_Config.bShowSalesText == 0) + fprintf(fp, "SHOW_SALESTEXT %d\n", int(m_Config.bShowSalesText)); + if (m_Config.bShowMobAIFlag == 0) + fprintf(fp, "SHOW_MOBAIFLAG %d\n", int(m_Config.bShowMobAIFlag)); + if (m_Config.bShowMobLevel == 0) + fprintf(fp, "SHOW_MOBLEVEL %d\n", int(m_Config.bShowMobLevel)); + fprintf(fp, "SHOW_OUTLINE %d\n", int(m_Config.bShowOutline)); + fprintf(fp, "USE_DEFAULT_IME %d\n", int(m_Config.bUseDefaultIME)); + fprintf(fp, "SOFTWARE_TILING %d\n", int(m_Config.bSoftwareTiling)); + fprintf(fp, "SHADOW_LEVEL %d\n", m_Config.iShadowLevel); + fprintf(fp, "SNOW_TEXTURE_MODE %d\n", int(m_Config.bSnowTexturesMode)); + fprintf(fp, "SHOW_SHADOW %d\n", int(m_Config.bShowShadow)); + fprintf(fp, "shop_range\t%d\n", int(m_Config.shopnames_range)); + fprintf(fp, "QUEST_LETTER %d\n", int(m_Config.questLetter)); + fprintf(fp, "COUNTRY_FLAG %d\n", int(m_Config.countryFlag)); + fprintf(fp, "AFFECT_ICONS %d\n", int(m_Config.affectIcons)); + + fprintf(fp, "perspective\t%.1f\n", double(m_Config.iFOVLevel)); + + fprintf(fp, "effect_level\t%d\n", int(m_Config.iEffectLevel)); + fprintf(fp, "pet_status\t%d\n", int(m_Config.bPetStatus)); + fprintf(fp, "mount_status\t%d\n", int(m_Config.bMountStatus)); + fprintf(fp, "npc_status\t%d\n", int(m_Config.bNpcStatus)); + fprintf(fp, "night_mode\t%d\n", int(m_Config.bNightMode)); + fprintf(fp, "special_message\t%d\n", int(m_Config.bMessage)); + fprintf(fp, "DUNGEON_TRACK\t%d\n", int(m_Config.bDungeonTrack)); + fprintf(fp, "BOSS_TRACK\t%d\n", int(m_Config.bBossTrack)); + + fprintf(fp, "OBJECT_DIST\t%.5f\n", double(m_Config.fobjectDist)); + + fprintf(fp, "\n"); + + fclose(fp); + return true; +} + +bool CPythonSystem::LoadInterfaceStatus() +{ + FILE* File = fopen(__ConfigPath("interface.cfg").c_str(), "rb"); + if (!File) + return false; + + // fread of the Win32 TWindowStatus[WINDOW_MAX_NUM]; a short file fills only its whole leading bytes. + unsigned char raw[sizeof(int32_t) * 5 * WINDOW_MAX_NUM] = {}; + const size_t read = fread(raw, 1, sizeof(raw), File); + fclose(File); + + for (size_t i = 0; i < WINDOW_MAX_NUM; ++i) + { + int32_t* fields[5] = { + &m_WindowStatus[i].isVisible, &m_WindowStatus[i].isMinimized, + &m_WindowStatus[i].ixPosition, &m_WindowStatus[i].iyPosition, &m_WindowStatus[i].iHeight, + }; + for (size_t f = 0; f < 5; ++f) + { + const size_t offset = (i * 5 + f) * sizeof(int32_t); + if (offset + sizeof(int32_t) <= read) + *fields[f] = GetInt32(raw + offset); + } + } + return true; +} + +void CPythonSystem::SaveInterfaceStatus() +{ + if (!m_poInterfaceHandler) + return; + + PyCallClassMemberFunc(m_poInterfaceHandler, "OnSaveInterfaceStatus", Py_BuildValue("()")); + + FILE* File = fopen(__ConfigPath("interface.cfg").c_str(), "wb"); + if (!File) + { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Cannot open interface.cfg"); + return; + } + + unsigned char raw[sizeof(int32_t) * 5 * WINDOW_MAX_NUM]; + for (size_t i = 0; i < WINDOW_MAX_NUM; ++i) + { + const TWindowStatus& s = m_WindowStatus[i]; + const int32_t fields[5] = { s.isVisible, s.isMinimized, s.ixPosition, s.iyPosition, s.iHeight }; + for (size_t f = 0; f < 5; ++f) + PutInt32(raw + (i * 5 + f) * sizeof(int32_t), fields[f]); + } + fwrite(raw, 1, sizeof(raw), File); + fclose(File); +} + +bool CPythonSystem::isInterfaceConfig() +{ + return m_isInterfaceConfig; +} + +const CPythonSystem::TWindowStatus& CPythonSystem::GetWindowStatusReference(int iIndex) +{ + // Windows returns m_WindowStatus[iIndex] unchecked; out of range reads a zeroed status here. + static const TWindowStatus s_kEmpty = {}; + if (iIndex < 0 || iIndex >= WINDOW_MAX_NUM) + return s_kEmpty; + return m_WindowStatus[iIndex]; +} + +void CPythonSystem::ApplyConfig() +{ + if (m_OldConfig.gamma != m_Config.gamma) + { + float val = 1.0f; + + switch (m_Config.gamma) + { + case 0: val = 0.4f; break; + case 1: val = 0.7f; break; + case 2: val = 1.0f; break; + case 3: val = 1.2f; break; + case 4: val = 1.4f; break; + } + + // CPythonGraphic::SetGamma (D3D gamma ramp): no gamma ramp in the SDL renderer yet. + m_fAppliedGamma = val; + } + + // is_software_cursor -> CPythonApplication::SetCursorMode: the port always uses the system cursor. + + m_OldConfig = m_Config; + + ChangeSystem(); +} + +void CPythonSystem::ChangeSystem() +{ + SoundManager& rkSndMgr = SoundManager::Instance(); + rkSndMgr.SetMusicVolume(m_Config.music_volume); + rkSndMgr.SetSoundVolumeGrade(m_Config.voice_volume); +} + +void CPythonSystem::Clear() +{ + SetInterfaceHandler(nullptr); +} + +CPythonSystem::CPythonSystem() +{ + Reload(); +} + +void CPythonSystem::Reload() +{ + memset(&m_Config, 0, sizeof(TConfig)); + memset(m_WindowStatus, 0, sizeof(m_WindowStatus)); + ClearDisplaySettings(); + + m_poInterfaceHandler = nullptr; + m_fAppliedGamma = 0.0f; + + SetDefaultConfig(); + // LoadConfig copies m_OldConfig only on success; without metin2.cfg Windows leaves it zeroed. + memset(&m_OldConfig, 0, sizeof(TConfig)); + + LoadConfig(); + + ChangeSystem(); + + if (LoadInterfaceStatus()) + m_isInterfaceConfig = true; + else + m_isInterfaceConfig = false; +} + +// --------------------------------------------------------------------------------------------- +// systemSetting module (PythonSystemModule.cpp) + +namespace { + +PyObject* systemGetWidth(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetWidth()); +} + +PyObject* systemGetHeight(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetHeight()); +} + +PyObject* systemSetInterfaceHandler(PyObject* poSelf, PyObject* poArgs) +{ + PyObject* poHandler; + if (!PyTuple_GetObject(poArgs, 0, &poHandler)) + return Py_BuildException(); + + CPythonSystem::Instance().SetInterfaceHandler(poHandler); + return Py_BuildNone(); +} + +PyObject* systemDestroyInterfaceHandler(PyObject* poSelf, PyObject* poArgs) +{ + CPythonSystem::Instance().DestroyInterfaceHandler(); + return Py_BuildNone(); +} + +PyObject* systemReserveResource(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildNone(); +} + +PyObject* systemisInterfaceConfig(PyObject* poSelf, PyObject* poArgs) +{ + int isInterfaceConfig = CPythonSystem::Instance().isInterfaceConfig(); + return Py_BuildValue("i", isInterfaceConfig); +} + +PyObject* systemSaveWindowStatus(PyObject* poSelf, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + + int iVisible; + if (!PyTuple_GetInteger(poArgs, 1, &iVisible)) + return Py_BuildException(); + + int iMinimized; + if (!PyTuple_GetInteger(poArgs, 2, &iMinimized)) + return Py_BuildException(); + + int ix; + if (!PyTuple_GetInteger(poArgs, 3, &ix)) + return Py_BuildException(); + + int iy; + if (!PyTuple_GetInteger(poArgs, 4, &iy)) + return Py_BuildException(); + + int iHeight; + if (!PyTuple_GetInteger(poArgs, 5, &iHeight)) + return Py_BuildException(); + + CPythonSystem::Instance().SaveWindowStatus(iIndex, iVisible, iMinimized, ix, iy, iHeight); + return Py_BuildNone(); +} + +PyObject* systemGetWindowStatus(PyObject* poSelf, PyObject* poArgs) +{ + int iIndex; + if (!PyTuple_GetInteger(poArgs, 0, &iIndex)) + return Py_BuildException(); + + const CPythonSystem::TWindowStatus& c_rWindowStatus = CPythonSystem::Instance().GetWindowStatusReference(iIndex); + return Py_BuildValue("iiiii", c_rWindowStatus.isVisible, + c_rWindowStatus.isMinimized, + c_rWindowStatus.ixPosition, + c_rWindowStatus.iyPosition, + c_rWindowStatus.iHeight); +} + +PyObject* systemGetConfig(PyObject* poSelf, PyObject* poArgs) +{ + CPythonSystem::TConfig* tmp = CPythonSystem::Instance().GetConfig(); + + int iRes = CPythonSystem::Instance().GetResolutionIndex(tmp->width, tmp->height, tmp->bpp); + int iFrequency = CPythonSystem::Instance().GetFrequencyIndex(iRes, tmp->frequency); + + // Windows passes the float music_volume to an "i" slot of the 32-bit x86 varargs list: it is + // promoted to a double that fills two int slots, so every later field shifts one place and + // iDistance falls off the end. + const double fMusicVolume = tmp->music_volume; + uint64_t uBits; + memcpy(&uBits, &fMusicVolume, sizeof(uBits)); + return Py_BuildValue("iiiiiiii", iRes, + iFrequency, + int(tmp->is_software_cursor), + int(tmp->is_object_culling), + int(uint32_t(uBits)), + int(uint32_t(uBits >> 32)), + int(tmp->voice_volume), + tmp->gamma); +} + +PyObject* systemSetSaveID(PyObject* poSelf, PyObject* poArgs) +{ + int iValue; + if (!PyTuple_GetInteger(poArgs, 0, &iValue)) + return Py_BuildException(); + + char* szSaveID; + if (!PyTuple_GetString(poArgs, 1, &szSaveID)) + return Py_BuildException(); + + CPythonSystem::Instance().SetSaveID(iValue, szSaveID); + return Py_BuildNone(); +} + +PyObject* systemisSaveID(PyObject* poSelf, PyObject* poArgs) +{ + int value = CPythonSystem::Instance().IsSaveID(); + return Py_BuildValue("i", value); +} + +PyObject* systemGetSaveID(PyObject* poSelf, PyObject* poArgs) +{ + const char* c_szSaveID = CPythonSystem::Instance().GetSaveID(); + return Py_BuildValue("s", c_szSaveID); +} + +PyObject* systemGetMusicVolume(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("f", CPythonSystem::Instance().GetMusicVolume()); +} + +PyObject* systemGetSoundVolume(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetSoundVolume()); +} + +PyObject* systemSetMusicVolume(PyObject* poSelf, PyObject* poArgs) +{ + float fVolume; + if (!PyTuple_GetFloat(poArgs, 0, &fVolume)) + return Py_BuildException(); + + CPythonSystem::Instance().SetMusicVolume(fVolume); + return Py_BuildNone(); +} + +PyObject* systemSetSoundVolumef(PyObject* poSelf, PyObject* poArgs) +{ + float fVolume; + if (!PyTuple_GetFloat(poArgs, 0, &fVolume)) + return Py_BuildException(); + + CPythonSystem::Instance().SetSoundVolumef(fVolume); + return Py_BuildNone(); +} + +PyObject* systemIsSoftwareCursor(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().IsSoftwareCursor()); +} + +PyObject* systemSetViewChatFlag(PyObject* poSelf, PyObject* poArgs) +{ + int iFlag; + if (!PyTuple_GetInteger(poArgs, 0, &iFlag)) + return Py_BuildException(); + + CPythonSystem::Instance().SetViewChatFlag(iFlag); + + return Py_BuildNone(); +} + +PyObject* systemIsViewChat(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().IsViewChat()); +} + +PyObject* systemSetAlwaysShowNameFlag(PyObject* poSelf, PyObject* poArgs) +{ + int iFlag; + if (!PyTuple_GetInteger(poArgs, 0, &iFlag)) + return Py_BuildException(); + + CPythonSystem::Instance().SetAlwaysShowNameFlag(iFlag); + + return Py_BuildNone(); +} + +PyObject* systemSetShowDamageFlag(PyObject* poSelf, PyObject* poArgs) +{ + int iFlag; + if (!PyTuple_GetInteger(poArgs, 0, &iFlag)) + return Py_BuildException(); + + CPythonSystem::Instance().SetShowDamageFlag(iFlag); + + return Py_BuildNone(); +} + +PyObject* systemSetShowSalesTextFlag(PyObject* poSelf, PyObject* poArgs) +{ + int iFlag; + if (!PyTuple_GetInteger(poArgs, 0, &iFlag)) + return Py_BuildException(); + + CPythonSystem::Instance().SetShowSalesTextFlag(iFlag); + + return Py_BuildNone(); +} + +PyObject* systemIsShowMobAIFlag(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().IsShowMobAIFlag()); +} + +PyObject* systemSetShowMobAIFlag(PyObject* poSelf, PyObject* poArgs) +{ + int iFlag; + if (!PyTuple_GetInteger(poArgs, 0, &iFlag)) + return Py_BuildException(); + + CPythonSystem::Instance().SetShowMobAIFlagFlag(iFlag); + // Windows then calls MobInfoAiFlagRefresh on every enemy CInstanceBase; the port has no + // CInstanceBase mob-info tail yet (PORT-PLAN pass 25). + return Py_BuildNone(); +} + +PyObject* systemIsShowMobLevel(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().IsShowMobLevel()); +} + +PyObject* systemSetShowMobLevel(PyObject* poSelf, PyObject* poArgs) +{ + int iFlag; + if (!PyTuple_GetInteger(poArgs, 0, &iFlag)) + return Py_BuildException(); + + CPythonSystem::Instance().SetShowMobLevelFlag(iFlag); + // Windows: MobInfoLevelRefresh on every enemy CInstanceBase (see systemSetShowMobAIFlag). + return Py_BuildNone(); +} + +PyObject* systemIsAlwaysShowName(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().IsAlwaysShowName()); +} + +PyObject* systemIsShowDamage(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().IsShowDamage()); +} + +PyObject* systemIsShowOutline(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("b", CPythonSystem::Instance().IsShowOutline()); +} + +PyObject* systemSetShowOutlineFlag(PyObject* poSelf, PyObject* poArgs) +{ + // The parse result is ignored on Windows (isShow stays uninitialised); false here. + bool isShow = false; + PyTuple_GetBoolean(poArgs, 0, &isShow); + + CPythonSystem::Instance().SetShowOutlineFlag(isShow); + return Py_BuildNone(); +} + +PyObject* systemIsShowSalesText(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().IsShowSalesText()); +} + +PyObject* systemIsSnowTexturesMode(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().IsSnowTexturesMode()); +} + +PyObject* systemSetSnowTexturesMode(PyObject* poSelf, PyObject* poArgs) +{ + int iFlag; + if (!PyTuple_GetInteger(poArgs, 0, &iFlag)) + return Py_BuildException(); + CPythonSystem::Instance().SetSnowTexturesMode(iFlag); + return Py_BuildNone(); +} + +PyObject* systemSetConfig(PyObject* poSelf, PyObject* poArgs) +{ + int res_index; + uint32_t width; + uint32_t height; + uint32_t bpp; + int frequency_index; + uint32_t frequency; + int software_cursor; + int shadow; + int object_culling; + int music_volume; + int voice_volume; + int gamma; + int distance; + + if (!PyTuple_GetInteger(poArgs, 0, &res_index)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 1, &frequency_index)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 2, &software_cursor)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 3, &shadow)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 4, &object_culling)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 5, &music_volume)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 6, &voice_volume)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 7, &gamma)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 8, &distance)) + return Py_BuildException(); + + if (!CPythonSystem::Instance().GetResolution(res_index, &width, &height, &bpp)) + return Py_BuildNone(); + + if (!CPythonSystem::Instance().GetFrequency(res_index, frequency_index, &frequency)) + return Py_BuildNone(); + + CPythonSystem::TConfig tmp; + + memcpy(&tmp, CPythonSystem::Instance().GetConfig(), sizeof(tmp)); + + tmp.width = width; + tmp.height = height; + tmp.bpp = bpp; + tmp.frequency = frequency; + tmp.is_software_cursor = software_cursor ? true : false; + tmp.is_object_culling = object_culling ? true : false; + tmp.music_volume = (char)music_volume; + tmp.voice_volume = uint8_t((char)voice_volume); + tmp.gamma = gamma; + tmp.iDistance = distance; + + CPythonSystem::Instance().SetConfig(&tmp); + return Py_BuildNone(); +} + +PyObject* systemApplyConfig(PyObject* poSelf, PyObject* poArgs) +{ + CPythonSystem::Instance().ApplyConfig(); + return Py_BuildNone(); +} + +PyObject* systemSaveConfig(PyObject* poSelf, PyObject* poArgs) +{ + int ret = CPythonSystem::Instance().SaveConfig(); + return Py_BuildValue("i", ret); +} + +PyObject* systemGetResolutionCount(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetResolutionCount()); +} + +PyObject* systemGetFrequencyCount(PyObject* poSelf, PyObject* poArgs) +{ + int index; + + if (!PyTuple_GetInteger(poArgs, 0, &index)) + return Py_BuildException(); + + return Py_BuildValue("i", CPythonSystem::Instance().GetFrequencyCount(index)); +} + +PyObject* systemGetResolution(PyObject* poSelf, PyObject* poArgs) +{ + int index; + uint32_t width = 0, height = 0, bpp = 0; + + if (!PyTuple_GetInteger(poArgs, 0, &index)) + return Py_BuildException(); + + CPythonSystem::Instance().GetResolution(index, &width, &height, &bpp); + return Py_BuildValue("iii", width, height, bpp); +} + +PyObject* systemGetCurrentResolution(PyObject* poSelf, PyObject* poArgs) +{ + CPythonSystem::TConfig* tmp = CPythonSystem::Instance().GetConfig(); + return Py_BuildValue("iii", tmp->width, tmp->height, tmp->bpp); +} + +PyObject* systemGetFrequency(PyObject* poSelf, PyObject* poArgs) +{ + int index, frequency_index; + uint32_t frequency = 0; + + if (!PyTuple_GetInteger(poArgs, 0, &index)) + return Py_BuildException(); + + if (!PyTuple_GetInteger(poArgs, 1, &frequency_index)) + return Py_BuildException(); + + CPythonSystem::Instance().GetFrequency(index, frequency_index, &frequency); + return Py_BuildValue("i", frequency); +} + +PyObject* systemGetShadowLevel(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetShadowLevel()); +} + +PyObject* systemSetShadowLevel(PyObject* poSelf, PyObject* poArgs) +{ + int level; + + if (!PyTuple_GetInteger(poArgs, 0, &level)) + return Py_BuildException(); + + if (level > 0) + CPythonSystem::Instance().SetShadowLevel(level); + + return Py_BuildNone(); +} + +PyObject* systemIsShowShadow(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("b", CPythonSystem::Instance().IsShadow()); +} + +PyObject* systemSetShowShadow(PyObject* poSelf, PyObject* poArgs) +{ + bool isShow = false; + PyTuple_GetBoolean(poArgs, 0, &isShow); + + CPythonSystem::Instance().SetShadow(isShow); + return Py_BuildNone(); +} + +PyObject* systemSetShopNamesRange(PyObject* poSelf, PyObject* poArgs) +{ + unsigned char fIndex; + if (!PyTuple_GetByte(poArgs, 0, &fIndex)) + return Py_BuildException(); + + CPythonSystem::Instance().SetShopNamesRange(fIndex); + return Py_BuildNone(); +} + +PyObject* systemGetShopNamesRange(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetShopNamesRange()); +} + +PyObject* systemSetQuestIconMode(PyObject* poSelf, PyObject* poArgs) +{ + int iValue; + if (!PyTuple_GetInteger(poArgs, 0, &iValue)) + return Py_BuildException(); + CPythonSystem::Instance().SetQuestLetter(iValue ? true : false); + return Py_BuildNone(); +} + +PyObject* systemGetQuestIconMode(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetQuestLetter()); +} + +PyObject* systemSetCountryFlag(PyObject* poSelf, PyObject* poArgs) +{ + int iValue; + if (!PyTuple_GetInteger(poArgs, 0, &iValue)) + return Py_BuildException(); + CPythonSystem::Instance().SetCountryFlag(iValue ? true : false); + return Py_BuildNone(); +} + +PyObject* systemGetCountryFlag(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetCountryFlag()); +} + +PyObject* systemSetAffectIcons(PyObject* poSelf, PyObject* poArgs) +{ + int iValue; + if (!PyTuple_GetInteger(poArgs, 0, &iValue)) + return Py_BuildException(); + CPythonSystem::Instance().SetAffectIcons(iValue ? true : false); + return Py_BuildNone(); +} + +PyObject* systemGetAffectIcons(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetAffectIcons()); +} + +PyObject* systemSetFOVLevel(PyObject* poSelf, PyObject* poArgs) +{ + float fFOV; + if (!PyTuple_GetFloat(poArgs, 0, &fFOV)) + return Py_BuildException(); + CPythonSystem::Instance().SetFOVLevel(fFOV); + return Py_BuildNone(); +} + +PyObject* systemGetFOVLevel(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("f", CPythonSystem::Instance().GetFOVLevel()); +} + +PyObject* systemSetEffectLevel(PyObject* poSelf, PyObject* poArgs) +{ + unsigned char iIndex; + if (!PyTuple_GetByte(poArgs, 0, &iIndex)) + return Py_BuildException(); + CPythonSystem::Instance().SetEffectLevel(iIndex); + return Py_BuildNone(); +} + +PyObject* systemGetEffectLevel(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetEffectLevel()); +} + +PyObject* systemSetPetRender(PyObject* poSelf, PyObject* poArgs) +{ + bool bFlag; + if (!PyTuple_GetBoolean(poArgs, 0, &bFlag)) + return Py_BuildException(); + CPythonSystem::Instance().SetPetRender(bFlag); + return Py_BuildNone(); +} + +PyObject* systemGetPetRender(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetPetRender()); +} + +PyObject* systemSetMountRender(PyObject* poSelf, PyObject* poArgs) +{ + bool bFlag; + if (!PyTuple_GetBoolean(poArgs, 0, &bFlag)) + return Py_BuildException(); + CPythonSystem::Instance().SetMountRender(bFlag); + return Py_BuildNone(); +} + +PyObject* systemGetMountRender(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetMountRender()); +} + +PyObject* systemSetShopNameStatus(PyObject* poSelf, PyObject* poArgs) +{ + bool bFlag; + if (!PyTuple_GetBoolean(poArgs, 0, &bFlag)) + return Py_BuildException(); + CPythonSystem::Instance().SetShopNameStatus(bFlag); + return Py_BuildNone(); +} + +PyObject* systemGetShopNameStatus(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetShopNameStatus()); +} + +PyObject* systemSetNightMode(PyObject* poSelf, PyObject* poArgs) +{ + bool bFlag; + if (!PyTuple_GetBoolean(poArgs, 0, &bFlag)) + return Py_BuildException(); + CPythonSystem::Instance().SetNightMode(bFlag); + return Py_BuildNone(); +} + +PyObject* systemGetNightMode(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetNightMode()); +} + +PyObject* systemSetStuffMessage(PyObject* poSelf, PyObject* poArgs) +{ + int iValue; + if (!PyTuple_GetInteger(poArgs, 0, &iValue)) + return Py_BuildException(); + CPythonSystem::Instance().SetStuffMessage(iValue); + return Py_BuildNone(); +} + +PyObject* systemGetStuffMessage(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetStuffMessage()); +} + +PyObject* systemSetDungeonTrack(PyObject* poSelf, PyObject* poArgs) +{ + int iValue; + if (!PyTuple_GetInteger(poArgs, 0, &iValue)) + return Py_BuildException(); + CPythonSystem::Instance().SetDungeonTrack(iValue); + return Py_BuildNone(); +} + +PyObject* systemGetDungeonTrack(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetDungeonTrack()); +} + +PyObject* systemSetBossTrack(PyObject* poSelf, PyObject* poArgs) +{ + int iValue; + if (!PyTuple_GetInteger(poArgs, 0, &iValue)) + return Py_BuildException(); + CPythonSystem::Instance().SetBossTrack(iValue); + return Py_BuildNone(); +} + +PyObject* systemGetBossTrack(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("i", CPythonSystem::Instance().GetBossTrack()); +} + +PyObject* systemSetMapObjectDistance(PyObject* poSelf, PyObject* poArgs) +{ + float fValue; + if (!PyTuple_GetFloat(poArgs, 0, &fValue)) + return Py_BuildException(); + CPythonSystem::Instance().SetObjectDistance(fValue); + return Py_BuildNone(); +} + +PyObject* systemGetMapObjectDistance(PyObject* poSelf, PyObject* poArgs) +{ + return Py_BuildValue("f", CPythonSystem::Instance().GetObjectDistance()); +} + +} // namespace + +void initsystemSetting() +{ + static PyMethodDef s_methods[] = + { + { "GetWidth", systemGetWidth, METH_VARARGS }, + { "GetHeight", systemGetHeight, METH_VARARGS }, + + { "SetShadow", systemSetShowShadow, METH_VARARGS }, + { "IsShadow", systemIsShowShadow, METH_VARARGS }, + + { "SetInterfaceHandler", systemSetInterfaceHandler, METH_VARARGS }, + { "DestroyInterfaceHandler", systemDestroyInterfaceHandler, METH_VARARGS }, + { "ReserveResource", systemReserveResource, METH_VARARGS }, + + { "isInterfaceConfig", systemisInterfaceConfig, METH_VARARGS }, + { "SaveWindowStatus", systemSaveWindowStatus, METH_VARARGS }, + { "GetWindowStatus", systemGetWindowStatus, METH_VARARGS }, + + { "GetResolutionCount", systemGetResolutionCount, METH_VARARGS }, + { "GetFrequencyCount", systemGetFrequencyCount, METH_VARARGS }, + + { "GetCurrentResolution", systemGetCurrentResolution, METH_VARARGS }, + + { "GetResolution", systemGetResolution, METH_VARARGS }, + { "GetFrequency", systemGetFrequency, METH_VARARGS }, + + { "ApplyConfig", systemApplyConfig, METH_VARARGS }, + { "SetConfig", systemSetConfig, METH_VARARGS }, + { "SaveConfig", systemSaveConfig, METH_VARARGS }, + { "GetConfig", systemGetConfig, METH_VARARGS }, + + { "SetSaveID", systemSetSaveID, METH_VARARGS }, + { "isSaveID", systemisSaveID, METH_VARARGS }, + { "GetSaveID", systemGetSaveID, METH_VARARGS }, + + { "GetMusicVolume", systemGetMusicVolume, METH_VARARGS }, + { "GetSoundVolume", systemGetSoundVolume, METH_VARARGS }, + + { "SetMusicVolume", systemSetMusicVolume, METH_VARARGS }, + { "SetSoundVolumef", systemSetSoundVolumef, METH_VARARGS }, + { "IsSoftwareCursor", systemIsSoftwareCursor, METH_VARARGS }, + + { "SetViewChatFlag", systemSetViewChatFlag, METH_VARARGS }, + { "IsViewChat", systemIsViewChat, METH_VARARGS }, + + { "SetAlwaysShowNameFlag", systemSetAlwaysShowNameFlag, METH_VARARGS }, + { "IsAlwaysShowName", systemIsAlwaysShowName, METH_VARARGS }, + + { "SetShowDamageFlag", systemSetShowDamageFlag, METH_VARARGS }, + { "IsShowDamage", systemIsShowDamage, METH_VARARGS }, + + { "SetShowSalesTextFlag", systemSetShowSalesTextFlag, METH_VARARGS }, + { "IsShowSalesText", systemIsShowSalesText, METH_VARARGS }, + { "SetShowOutlineFlag", systemSetShowOutlineFlag, METH_VARARGS }, + { "IsShowOutline", systemIsShowOutline, METH_VARARGS }, + { "GetShadowLevel", systemGetShadowLevel, METH_VARARGS }, + { "SetShadowLevel", systemSetShadowLevel, METH_VARARGS }, + { "SetSnowTexturesMode", systemSetSnowTexturesMode, METH_VARARGS }, + { "IsSnowTexturesMode", systemIsSnowTexturesMode, METH_VARARGS }, + + { "IsShowMobAIFlag", systemIsShowMobAIFlag, METH_VARARGS }, + { "SetShowMobAIFlag", systemSetShowMobAIFlag, METH_VARARGS }, + + { "IsShowMobLevel", systemIsShowMobLevel, METH_VARARGS }, + { "SetShowMobLevel", systemSetShowMobLevel, METH_VARARGS }, + + { "SetShopNamesRange", systemSetShopNamesRange, METH_VARARGS }, + { "GetShopNamesRange", systemGetShopNamesRange, METH_VARARGS }, + + { "SetQuestIconMode", systemSetQuestIconMode, METH_VARARGS }, + { "GetQuestIconMode", systemGetQuestIconMode, METH_VARARGS }, + { "SetCountryFlag", systemSetCountryFlag, METH_VARARGS }, + { "GetCountryFlag", systemGetCountryFlag, METH_VARARGS }, + { "SetAffectIcons", systemSetAffectIcons, METH_VARARGS }, + { "GetAffectIcons", systemGetAffectIcons, METH_VARARGS }, + + { "GetFOVLevel", systemGetFOVLevel, METH_VARARGS }, + { "SetFOVLevel", systemSetFOVLevel, METH_VARARGS }, + { "SetEffectLevel", systemSetEffectLevel, METH_VARARGS }, + { "GetEffectLevel", systemGetEffectLevel, METH_VARARGS }, + + { "GetPetRender", systemGetPetRender, METH_VARARGS }, + { "SetPetRender", systemSetPetRender, METH_VARARGS }, + { "GetMountRender", systemGetMountRender, METH_VARARGS }, + { "SetMountRender", systemSetMountRender, METH_VARARGS }, + { "SetShopNameStatus", systemSetShopNameStatus, METH_VARARGS }, + { "GetShopNameStatus", systemGetShopNameStatus, METH_VARARGS }, + + { "GetNightMode", systemGetNightMode, METH_VARARGS }, + { "SetNightMode", systemSetNightMode, METH_VARARGS }, + + { "SetStuffMessage", systemSetStuffMessage, METH_VARARGS }, + { "GetStuffMessage", systemGetStuffMessage, METH_VARARGS }, + { "SetDungeonTrack", systemSetDungeonTrack, METH_VARARGS }, + { "GetDungeonTrack", systemGetDungeonTrack, METH_VARARGS }, + { "SetBossTrack", systemSetBossTrack, METH_VARARGS }, + { "GetBossTrack", systemGetBossTrack, METH_VARARGS }, + + { "SetMapObjectDistance", systemSetMapObjectDistance, METH_VARARGS }, + { "GetMapObjectDistance", systemGetMapObjectDistance, METH_VARARGS }, + + { NULL, NULL, 0 } }; - auto* module = Py_InitModule("systemSetting", methods); - if (!module) return; - PyModule_AddIntConstant(module, "WINDOW_STATUS", 0); - PyModule_AddIntConstant(module, "WINDOW_INVENTORY", 1); - PyModule_AddIntConstant(module, "WINDOW_ABILITY", 2); - PyModule_AddIntConstant(module, "WINDOW_SOCIETY", 3); - PyModule_AddIntConstant(module, "WINDOW_JOURNAL", 4); - PyModule_AddIntConstant(module, "WINDOW_COMMAND", 5); - PyModule_AddIntConstant(module, "WINDOW_QUICK", 6); - PyModule_AddIntConstant(module, "WINDOW_GAUGE", 7); - PyModule_AddIntConstant(module, "WINDOW_MINIMAP", 8); + + PyObject* poModule = Py_InitModule("systemSetting", s_methods); + + PyModule_AddIntConstant(poModule, "WINDOW_STATUS", CPythonSystem::WINDOW_STATUS); + PyModule_AddIntConstant(poModule, "WINDOW_INVENTORY", CPythonSystem::WINDOW_INVENTORY); + PyModule_AddIntConstant(poModule, "WINDOW_ABILITY", CPythonSystem::WINDOW_ABILITY); + PyModule_AddIntConstant(poModule, "WINDOW_SOCIETY", CPythonSystem::WINDOW_SOCIETY); + PyModule_AddIntConstant(poModule, "WINDOW_JOURNAL", CPythonSystem::WINDOW_JOURNAL); + PyModule_AddIntConstant(poModule, "WINDOW_COMMAND", CPythonSystem::WINDOW_COMMAND); + + PyModule_AddIntConstant(poModule, "WINDOW_QUICK", CPythonSystem::WINDOW_QUICK); + PyModule_AddIntConstant(poModule, "WINDOW_GAUGE", CPythonSystem::WINDOW_GAUGE); + PyModule_AddIntConstant(poModule, "WINDOW_MINIMAP", CPythonSystem::WINDOW_MINIMAP); + PyModule_AddIntConstant(poModule, "WINDOW_CHAT", CPythonSystem::WINDOW_CHAT); } } // namespace ava2 diff --git a/src/python_system.h b/src/python_system.h index 777b21bd..122ef986 100644 --- a/src/python_system.h +++ b/src/python_system.h @@ -1,5 +1,274 @@ #pragma once +// CPythonSystem: the metin2.cfg / interface.cfg backed option store behind the "systemSetting" module. +// Provenance: AVA2 UserInterface/PythonSystem.{h,cpp} and PythonSystemModule.cpp, compiled with the +// Locale_inc.h set WJ_SHOW_MOB_INFO + ENABLE_SHOW_MOBAIFLAG/MOBLEVEL, ENABLE_SNOW_MODE, +// ENABLE_OFFLINESHOP_SYSTEM, ENABLE_NEW_GAMEOPTION, ENABLE_GRAPHIC_ON_OFF, ENABLE_DISCORD_STUFF, +// ENABLE_TRACK_WINDOW and ENABLE_MAP_OBJECT_OPTIMIZATION; ENABLE_OPTION_COLLECT_EQUIPMENT is off. +#include +#include +#include namespace ava2 { + +// EterLib/ResourceManager.cpp: read and written through metin2.cfg PRE_LOADING_DELAY_TIME. +extern int g_iLoadingDelayTime; + +class CPythonSystem +{ +public: + enum EWindow + { + WINDOW_STATUS, + WINDOW_INVENTORY, + WINDOW_ABILITY, + WINDOW_SOCIETY, + WINDOW_JOURNAL, + WINDOW_COMMAND, + + WINDOW_QUICK, + WINDOW_GAUGE, + WINDOW_MINIMAP, + WINDOW_CHAT, + + WINDOW_MAX_NUM, + }; + + enum + { + FREQUENCY_MAX_NUM = 30, + RESOLUTION_MAX_NUM = 100 + }; + + typedef struct SResolution + { + uint32_t width; + uint32_t height; + uint32_t bpp; + + uint32_t frequency[20]; + uint8_t frequency_count; + } TResolution; + + // interface.cfg is the raw Win32 array of these: five little-endian int32 per window. + typedef struct SWindowStatus + { + int32_t isVisible; + int32_t isMinimized; + + int32_t ixPosition; + int32_t iyPosition; + int32_t iHeight; + } TWindowStatus; + + typedef struct SConfig + { + uint32_t width; + uint32_t height; + uint32_t bpp; + uint32_t frequency; + + bool is_software_cursor; + bool is_object_culling; + int iDistance; + int iShadowLevel; + + float music_volume; + uint8_t voice_volume; + + int gamma; + + int isSaveID; + char SaveID[20]; + + bool bWindowed; + bool bDecompressDDS; + bool bNoSoundCard; + bool bUseDefaultIME; + uint8_t bSoftwareTiling; + bool bViewChat; + bool bAlwaysShowName; + bool bShowDamage; + bool bShowSalesText; + bool bShowOutline; + bool bShowShadow; + bool bShowMobAIFlag; + bool bShowMobLevel; + bool bSnowTexturesMode; + uint8_t shopnames_range; + bool questLetter; + bool countryFlag; + bool affectIcons; + float iFOVLevel; + uint8_t iEffectLevel; + bool bPetStatus; + bool bMountStatus; + bool bNpcStatus; + bool bNightMode; + bool bMessage; + bool bDungeonTrack; + bool bBossTrack; + float fobjectDist; + } TConfig; + +public: + static CPythonSystem& Instance(); + + // Windows reads and writes both files in the client's working directory; hosts whose working + // directory is not writable (Android) point this at a per-user directory before first use. + // Reload() re-runs the constructor sequence against the current directory. + static void SetConfigDirectory(const std::string& directory); + static const std::string& GetConfigDirectory(); + void Reload(); + + void Clear(); + void SetInterfaceHandler(PyObject* poHandler); + void DestroyInterfaceHandler(); + PyObject* GetInterfaceHandler() const { return m_poInterfaceHandler; } + + float GetObjectDistance() { return m_Config.fobjectDist; } + void SetObjectDistance(float fDist); + + // Config + void SetDefaultConfig(); + bool LoadConfig(); + bool SaveConfig(); + void ApplyConfig(); + void SetConfig(TConfig* set_config); + TConfig* GetConfig(); + void ChangeSystem(); + + // Interface + bool LoadInterfaceStatus(); + void SaveInterfaceStatus(); + bool isInterfaceConfig(); + const TWindowStatus& GetWindowStatusReference(int iIndex); + + uint32_t GetWidth(); + uint32_t GetHeight(); + uint32_t GetBPP(); + uint32_t GetFrequency(); + bool IsSoftwareCursor(); + bool IsWindowed(); + bool IsViewChat(); + bool IsAlwaysShowName(); + bool IsShowDamage(); + bool IsShowSalesText(); + bool IsUseDefaultIME(); + bool IsNoSoundCard(); + bool IsAutoTiling(); + bool IsSoftwareTiling(); + void SetSoftwareTiling(bool isEnable); + void SetViewChatFlag(int iFlag); + void SetAlwaysShowNameFlag(int iFlag); + void SetShowDamageFlag(int iFlag); + void SetShowSalesTextFlag(int iFlag); + bool IsShowOutline() const { return m_Config.bShowOutline; } + + void SetShopNamesRange(uint8_t iIndex) { m_Config.shopnames_range = iIndex; } + uint8_t GetShopNamesRange() { return m_Config.shopnames_range; } + + uint8_t GetEffectLevel() { return m_Config.iEffectLevel; } + void SetEffectLevel(uint8_t iLevel) { m_Config.iEffectLevel = iLevel; } + + bool GetPetRender() { return m_Config.bPetStatus; } + void SetPetRender(bool bStatus) { m_Config.bPetStatus = bStatus; } + + bool GetMountRender() { return m_Config.bMountStatus; } + void SetMountRender(bool bStatus) { m_Config.bMountStatus = bStatus; } + + bool GetShopNameStatus() { return m_Config.bNpcStatus; } + void SetShopNameStatus(bool bStatus) { m_Config.bNpcStatus = bStatus; } + + bool GetNightMode() { return m_Config.bNightMode; } + void SetNightMode(bool bStatus) { m_Config.bNightMode = bStatus; } + + bool GetDungeonTrack() { return m_Config.bDungeonTrack; } + void SetDungeonTrack(bool flag) { m_Config.bDungeonTrack = flag; } + + bool GetBossTrack() { return m_Config.bBossTrack; } + void SetBossTrack(bool flag) { m_Config.bBossTrack = flag; } + + float GetFOVLevel() { return m_Config.iFOVLevel; } + void SetFOVLevel(const float fFOV); + + void SetShowOutlineFlag(const bool bShow) { m_Config.bShowOutline = bShow; } + + bool IsShadow() const { return m_Config.bShowShadow; } + void SetShadow(const bool bShow) { m_Config.bShowShadow = bShow; } + + bool IsSnowTexturesMode(); + void SetSnowTexturesMode(int iFlag); + + bool IsShowMobAIFlag(); + void SetShowMobAIFlagFlag(int iFlag); + + bool IsShowMobLevel(); + void SetShowMobLevelFlag(int iFlag); + + // Window + void SaveWindowStatus(int iIndex, int iVisible, int iMinimized, int ix, int iy, int iHeight); + + // SaveID + int IsSaveID(); + const char* GetSaveID(); + void SetSaveID(int iValue, const char* c_szSaveID); + + /// Display + void GetDisplaySettings(); + // One D3D adapter mode through GetDisplaySettings' filter/merge; exposed for tests. + void AddDisplayMode(uint32_t width, uint32_t height, uint32_t bpp, uint32_t frequency); + void ClearDisplaySettings(); + + int GetResolutionCount(); + int GetFrequencyCount(int index); + bool GetResolution(int index, uint32_t* width, uint32_t* height, uint32_t* bpp); + bool GetFrequency(int index, int freq_index, uint32_t* frequncy); + int GetResolutionIndex(uint32_t width, uint32_t height, uint32_t bpp); + int GetFrequencyIndex(int res_index, uint32_t frequency); + bool isViewCulling(); + + // Sound + float GetMusicVolume(); + int GetSoundVolume(); + void SetMusicVolume(float fVolume); + void SetSoundVolumef(float fVolume); + + int GetDistance(); + int GetShadowLevel(); + void SetShadowLevel(unsigned int level); + + void SetQuestLetter(bool flag) { m_Config.questLetter = flag; } + bool GetQuestLetter() { return m_Config.questLetter; } + void SetCountryFlag(bool flag) { m_Config.countryFlag = flag; } + bool GetCountryFlag() { return m_Config.countryFlag; } + void SetAffectIcons(bool flag) { m_Config.affectIcons = flag; } + bool GetAffectIcons() { return m_Config.affectIcons; } + + bool GetStuffMessage() { return m_Config.bMessage; } + void SetStuffMessage(bool flag) { m_Config.bMessage = flag; } + + // Test access: what ApplyConfig handed to CPythonGraphic::SetGamma, 0 before any change. + float GetAppliedGamma() const { return m_fAppliedGamma; } + +protected: + CPythonSystem(); + + std::string __ConfigPath(const char* c_szFileName) const; + +protected: + TResolution m_ResolutionList[RESOLUTION_MAX_NUM]; + int m_ResolutionCount = 0; + + TConfig m_Config; + TConfig m_OldConfig; + + bool m_isInterfaceConfig = false; + PyObject* m_poInterfaceHandler = nullptr; + TWindowStatus m_WindowStatus[WINDOW_MAX_NUM]; + + float m_fAppliedGamma = 0.0f; +}; + void initsystemSetting(); -} + +} // namespace ava2 diff --git a/src/python_wiki.cpp b/src/python_wiki.cpp new file mode 100644 index 00000000..1da5771d --- /dev/null +++ b/src/python_wiki.cpp @@ -0,0 +1,458 @@ +// CPythonWiki port (AVA2 UserInterface/PythonWiki.{h,cpp}, ENABLE_WIKI). +// Provenance: AVA2 Windows client only; nothing here comes from metin2-client/40250. +// Tables (chests, eventBoss, costume map, item/monster blacklists) are copied verbatim. +#include "python_wiki.h" +#include "ava2_text_file_loader.h" +#include "item_proto.h" +#include "nonplayer_data.h" +#include "python_gameplay_modules.h" +#include "python_runtime.h" +#include +#include +#include +#include +#include +#include +#include + +namespace ava2 { +namespace { +void wiki_trace_error(const std::string& text) { std::cerr << "[AVA2 TraceError] " << text << std::endl; } + +constexpr uint32_t bossChests[][2] = { + {50070,691}, {50071,791}, {50073,2091}, {50076,2191}, {50079,2206}, {50078,1304}, {50077,1901}, {51115,4140}, +}; +constexpr uint32_t dangeonChests[][2] = { + {50082,1093}, {80030,2092}, {50186,2598}, {51110,6091}, {51111,6191}, {54705,6812}, {51116,6231}, + // {51117,6231}, +}; +constexpr uint32_t otherChests[][2] = { + {77904,0}, {77910,0}, {77911,0}, {77912,0}, {77901,0}, {77902,0}, {77903,0}, +}; +constexpr uint32_t eventChests[][2] = { + {50011,0}, {77916,0}, {50928,0}, {50929,0}, {50930,0}, {50275,0}, {50276,0}, {50277,0}, +}; +constexpr uint32_t eventBoss[] = { 1093, 2493 }; + +const std::map> s_costumeData = { + {0, //Weapon + { + 40101, 40102, 40103, 40104, 40105, 40106, 40129, 40130, 40131, 40132, 40133, 40134, 40445, 40446, 40447, 40448, 40449, 40450, 34503, 34504, 34505, 34506, 34507, 34508, 34509, 40431, 40432, 40433, 40434, 40435, 40436, 40437, 40600, 40601, 40602, 40603, 40604, 40605, 40606, 40610, 40611, 40612, 40613, 40614, 40615, 40616, 40620, 40621, 40622, 40623, 40624, 40625, 40626 + } + }, + {1, //Armor + { + 41120, 41122, 41121, 41119, 41003, 41004, 34500, 34501, 34044, 34045, 34090, 34091, 34092, 34093, 34094, 34095 + } + }, + {2, //Hair + { + 45003, 45004, 45058, 45057, 45006, 45005, 34502, 34510, 45309, 45310, 45500, 45501, 45502, 45503, 45504, 45504 + } + }, + {3, //Sash + { + 86008, 86014, 86018, 86024, 86044, 86048, 86054, 86058, 86004, 86028, 86034, 86038, 86064, 86065, 86066 + } + }, + {4, //Shining + { + 65000, 65001, 65002, 65003, 65100, 65101, 65102, 65103 + } + }, + {5, //Mount + { + 71124, 71502, 71505, 71508, 71511, 71243, 71261, 71262, 71247, 71253, 71252, 71246, 71255, 71254, 71248, 71249, 71236, 71235, 71234, 71233, 71230 + } + }, + {6, //Pet + { + 53001, 53004, 53007, 53010, 53013 + } + }, + {7, //Levelable Pet + { + 55701, 55703, 55704, 55702, 55707, 55705, 55706 + } + }, +}; + +// CPythonWiki::BlackList switch cases (warrior/ninja/shaman/sura weapon+armour+helmet, shields, earrings, +// bracelets, necklaces, belts, shoes); every listed vnum returns false. +constexpr uint32_t s_itemBlackList[] = { + 529, 269, 3189, 329, 579, 569, 3239, 359, 3249, 1909, 1949, 709, 749, 809, 849, 909, 949, 3209, + 3200, 229, 239, 3179, 19299, 21219, 12949, 12909, 1209, 1149, 539, 519, 1199, 2219, 2229, 1929, + 1939, 729, 739, 829, 929, 939, 1920, 1930, 930, 920, 720, 730, 530, 4039, 1159, 839, 19499, 12959, + 12919, 5189, 5179, 7319, 509, 5159, 7329, 1959, 759, 859, 869, 959, 1950, 950, 750, 7189, 5139, + 5149, 7179, 1969, 19899, 21279, 12009, 12979, 21239, 12939, 369, 349, 559, 219, 1919, 719, 819, + 919, 190, 710, 209, 910, 19699, 21259, 12969, 12929, 13189, 13159, 13309, 13219, 13229, 13239, + 13249, 17309, 14309, 16309, 18209, 18129, 18139, 18149, 18159, 15469, 15479, 15249 +}; + +// CItemData constants with AVA2 Locale_inc.h (ITEM_TYPE_BELT/RINGS, ARMOR_PENDANT on). +enum : uint8_t { + ITEM_TYPE_WEAPON=1, ITEM_TYPE_ARMOR=2, ITEM_TYPE_BELT=34, ITEM_TYPE_RINGS=36, + ARMOR_BODY=0, ARMOR_HEAD=1, ARMOR_SHIELD=2, ARMOR_WRIST=3, ARMOR_FOOTS=4, ARMOR_NECK=5, ARMOR_EAR=6, ARMOR_PENDANT=8, + LIMIT_LEVEL=1, MOB_RANK_BOSS=4, +}; +constexpr uint32_t ITEM_ANTIFLAG_WARRIOR=1u<<2, ITEM_ANTIFLAG_ASSASSIN=1u<<3, ITEM_ANTIFLAG_SURA=1u<<4, ITEM_ANTIFLAG_SHAMAN=1u<<5; +constexpr int MAX_REFINE_ITEM=5, JOB_MAX_NUM=4; + +struct RefineTable { uint32_t id=0,item_vnums[MAX_REFINE_ITEM]={},item_count[MAX_REFINE_ITEM]={},cost=0,prob=0,refine_count=0; }; +struct CharacterData { uint32_t itemVnum,level; }; +struct SpecialData { uint32_t itemVnum,count; }; + +struct Wiki { + std::unordered_map refineTable; + std::vector boss[3],monster[3],stone[3]; + // 4 character... [WARRIOR-ASSASSIN-SHAMAN-SURA] + std::vector weapon[4],armor[4],helmets[4],shields[4],earrings[4],bracelet[4],necklace[4],shoes[4],belt[4],talisman[4],rings[4]; + std::unordered_map> specialDrop,mobDrop; + std::vector* category(int type,int cat) { + if(type<0||type>3)return nullptr; + switch(cat) { + case 0:return &weapon[type];case 1:return &armor[type];case 2:return &helmets[type];case 3:return &shields[type]; + case 4:return &earrings[type];case 5:return &bracelet[type];case 6:return &necklace[type];case 7:return &shoes[type]; + case 8:return &belt[type];case 9:return &talisman[type];case 10:return &rings[type]; + } + return nullptr; + } +}; +Wiki& wiki() { static Wiki w;return w; } + +bool BlackList(uint32_t vnum) { + // Talisman blacklist (type/subtype) is commented out in the original. + return std::find(std::begin(s_itemBlackList),std::end(s_itemBlackList),vnum)==std::end(s_itemBlackList); +} +uint8_t GetRefineLevel(uint32_t,uint32_t type,uint32_t subtype) { + if(type==ITEM_TYPE_ARMOR&&subtype==ARMOR_PENDANT)return 200; + return 9; +} +bool isLastItem(uint32_t vnum,const std::string& name,uint8_t type,uint8_t subtype) { + return name.find("+"+std::to_string(GetRefineLevel(vnum,type,subtype)))!=std::string::npos; +} + +bool BlackListMonster(uint32_t vnum) { + if(vnum>=8001&&vnum<=8014)return false; + if(vnum>=8024&&vnum<=8027)return false; + if(vnum>=8051&&vnum<=8056)return false; + switch(vnum) { + case 191: case 192: case 193: case 194: case 491: case 492: case 493: case 494: case 591: case 691: case 791: + case 1091: case 1092: case 1093: case 2191: case 1304: case 2206: case 1901: case 1191: case 2091: case 2092: + case 2307: case 2493: case 2598: case 3190: case 3191: case 3290: case 3291: case 3390: case 3391: case 3490: + case 3491: case 3590: case 3591: case 3690: case 3691: case 3790: case 3791: case 3890: case 3891: case 6091: + case 6191: case 9018: case 20442: case 533: case 9836: case 9838: case 9840: case 9842: case 9844: + return false; + } + return true; +} + +void LoadItem(const ItemProtoRecord& item) { + constexpr uint32_t flagList[JOB_MAX_NUM]={ITEM_ANTIFLAG_WARRIOR,ITEM_ANTIFLAG_ASSASSIN,ITEM_ANTIFLAG_SHAMAN,ITEM_ANTIFLAG_SURA}; + if(!isLastItem(item.vnum,item.name,item.type,item.subtype))return; + if(!BlackList(item.vnum))return; + uint32_t itemLevel=0; + for(const auto& limit:item.limits) if(limit.first==LIMIT_LEVEL) {itemLevel=uint32_t(limit.second);break;} + std::vector* lists=nullptr;Wiki& w=wiki(); + if(item.type==ITEM_TYPE_WEAPON)lists=w.weapon; + else if(item.type==ITEM_TYPE_ARMOR) { + switch(item.subtype) { + case ARMOR_BODY:lists=w.armor;break;case ARMOR_HEAD:lists=w.helmets;break;case ARMOR_SHIELD:lists=w.shields;break; + case ARMOR_WRIST:lists=w.bracelet;break;case ARMOR_FOOTS:lists=w.shoes;break;case ARMOR_NECK:lists=w.necklace;break; + case ARMOR_EAR:lists=w.earrings;break;case ARMOR_PENDANT:lists=w.talisman;break; + } + } + else if(item.type==ITEM_TYPE_BELT)lists=w.belt; + else if(item.type==ITEM_TYPE_RINGS)lists=w.rings; + if(!lists)return; + for(int j=0;jj.level;}; + Wiki& w=wiki(); + for(int j=0;j<4;++j) + for(auto* v:{&w.weapon[j],&w.armor[j],&w.helmets[j],&w.shields[j],&w.earrings[j],&w.bracelet[j],&w.necklace[j],&w.shoes[j],&w.belt[j],&w.talisman[j],&w.rings[j]}) + std::stable_sort(v->begin(),v->end(),byLevelDesc); + return true; +} + +bool LoadRefineTable(const std::string& fileName,const std::string& text) { + auto lines=ava2TextLines(text);std::vector tok; + for(size_t i=0;i>& out) { + TextFileLoader loader;std::vector errors; + if(!loader.load(text,&errors))return false; + for(const auto& e:errors)wiki_trace_error(e+" ("+fileName+")"); + std::vector data; + for(size_t i=0;iat(0))),uint32_t(std::stoi(tok->at(1)))});} + catch(const std::exception&) {wiki_trace_error(std::string(func)+": malformed row "+std::to_string(k)+" in "+fileName);return false;} + } + if(!data.empty())out.emplace(uint32_t(vnum),data); + loader.setParent(); + } + return true; +} + +int tupleInt(PyObject* args,Py_ssize_t pos,int* out) { + // ScriptLib PyTuple_GetInteger: bounds check, then PyLong_AsLong without a type check. + if(pos>=PyTuple_Size(args))return 0; + PyObject* item=PyTuple_GetItem(args,pos);if(!item)return 0; + *out=int(PyLong_AsLong(item));return 1; +} +PyObject* badArgument() { PyErr_BadArgument();return nullptr; } +PyObject* buildException() { PyErr_Clear();Py_RETURN_NONE; } +// Windows indexes std::vector without bounds checks (UB); the port returns 0 instead. +template const T* at(const std::vector& v,int i) { return i>=0&&size_t(i)second; + return Py_BuildValue("iiiiiiiiiiiiii",r.id,r.item_vnums[0],r.item_count[0],r.item_vnums[1],r.item_count[1],r.item_vnums[2],r.item_count[2], + r.item_vnums[3],r.item_count[3],r.item_vnums[4],r.item_count[4],r.cost,r.prob,r.refine_count); +} +PyObject* wikiIsBlackList(PyObject*,PyObject* args) { + // The original reads all three arguments into iItemVnum (iType/iSubtype stay uninitialised and are + // unused by BlackList), so the last argument is the vnum that gets tested. + int vnum; + if(!tupleInt(args,0,&vnum)||!tupleInt(args,1,&vnum)||!tupleInt(args,2,&vnum))return badArgument(); + return Py_BuildValue("i",BlackList(uint32_t(vnum))); +} +PyObject* wikiGetCategorySize(PyObject*,PyObject* args) { + int type,cat;if(!tupleInt(args,0,&type)||!tupleInt(args,1,&cat))return badArgument(); + auto* v=wiki().category(type,cat); + return Py_BuildValue("i",v?int(v->size()):0); +} +PyObject* wikiGetCategoryData(PyObject*,PyObject* args) { + int type,cat,index;if(!tupleInt(args,0,&type)||!tupleInt(args,1,&cat)||!tupleInt(args,2,&index))return badArgument(); + auto* v=wiki().category(type,cat);auto* d=v?at(*v,index):nullptr; + return Py_BuildValue("i",d?d->itemVnum:0); +} +PyObject* wikiReadData(PyObject*,PyObject* args) { + const char* locale; + if(PyTuple_Size(args)<1||!PyString_Check(PyTuple_GetItem(args,0)))return buildException(); + locale=PyString_AsString(PyTuple_GetItem(args,0)); + WikiReadData(locale); + Py_RETURN_NONE; +} +PyObject* wikiGetRefineMaxLevel(PyObject*,PyObject* args) { + int vnum;if(!tupleInt(args,0,&vnum))return buildException(); + int type=0,subType=0; + if(!GetItemTypeAndSubType(uint32_t(vnum),&type,&subType))return Py_BuildValue("i",GetRefineLevel(vnum,0,0)); + return Py_BuildValue("i",GetRefineLevel(vnum,type,subType)); +} +template PyObject* chestPair(const uint32_t (&t)[N][2],int i) { + if(i<0||size_t(i)>=N)return Py_BuildValue("ii",0,0); // UB in the original + return Py_BuildValue("ii",t[i][0],t[i][1]); +} +PyObject* wikiGetChestSize(PyObject*,PyObject* args) { + int type;if(!tupleInt(args,0,&type))return buildException(); + if(type==0)return Py_BuildValue("i",int(std::size(bossChests))); + if(type==1)return Py_BuildValue("i",int(std::size(dangeonChests))); + if(type==2)return Py_BuildValue("i",int(std::size(otherChests))); + if(type==3)return Py_BuildValue("i",int(std::size(eventChests))); + return Py_BuildValue("i",0); +} +PyObject* wikiGetChestData(PyObject*,PyObject* args) { + int type,index;if(!tupleInt(args,0,&type)||!tupleInt(args,1,&index))return buildException(); + if(type==0)return chestPair(bossChests,index); + if(type==1)return chestPair(dangeonChests,index); + if(type==2)return chestPair(otherChests,index); + if(type==3)return chestPair(eventChests,index); + return Py_BuildValue("ii",0,0); +} +PyObject* dropSize(const std::unordered_map>& m,PyObject* args) { + int vnum;if(!tupleInt(args,0,&vnum))return buildException(); + auto it=m.find(uint32_t(vnum)); + return Py_BuildValue("i",it==m.end()?0:int(it->second.size())); +} +PyObject* dropData(const std::unordered_map>& m,PyObject* args) { + int vnum,index;if(!tupleInt(args,0,&vnum)||!tupleInt(args,1,&index))return buildException(); + auto it=m.find(uint32_t(vnum));auto* d=it==m.end()?nullptr:at(it->second,index); + return d?Py_BuildValue("ii",d->itemVnum,d->count):Py_BuildValue("ii",0,0); +} +PyObject* wikiGetSpecialInfoSize(PyObject*,PyObject* args) { return dropSize(wiki().specialDrop,args); } +PyObject* wikiGetSpecialInfoData(PyObject*,PyObject* args) { return dropData(wiki().specialDrop,args); } +PyObject* wikiGetMobInfoSize(PyObject*,PyObject* args) { return dropSize(wiki().mobDrop,args); } +PyObject* wikiGetMobInfoData(PyObject*,PyObject* args) { return dropData(wiki().mobDrop,args); } +// GetBoss/Monster/StoneData pass a character_data struct to Py_BuildValue("i"); MSVC pushes it by value, +// so the first DWORD (itemVnum) is what Python sees. +PyObject* levelListSize(std::vector* lists,PyObject* args) { + int type;if(!tupleInt(args,0,&type))return badArgument(); + return Py_BuildValue("i",type>=0&&type<3?int(lists[type].size()):0); +} +PyObject* levelListData(std::vector* lists,PyObject* args) { + int type,index;if(!tupleInt(args,0,&type)||!tupleInt(args,1,&index))return badArgument(); + auto* d=type>=0&&type<3?at(lists[type],index):nullptr; + return Py_BuildValue("i",d?d->itemVnum:0); +} +PyObject* wikiGetBossSize(PyObject*,PyObject* args) { + int type;if(!tupleInt(args,0,&type))return badArgument(); + if(type==3)return Py_BuildValue("i",int(std::size(eventBoss))); // event boss + return levelListSize(wiki().boss,args); +} +PyObject* wikiGetBossData(PyObject*,PyObject* args) { + int type,index;if(!tupleInt(args,0,&type)||!tupleInt(args,1,&index))return badArgument(); + if(type==3)return Py_BuildValue("i",index>=0&&size_t(index)second.size())); +} +PyObject* wikiCostumeData(PyObject*,PyObject* args) { + int type,index;if(!tupleInt(args,0,&type)||!tupleInt(args,1,&index))return badArgument(); + auto it=s_costumeData.find(uint8_t(type)); + auto* d=it==s_costumeData.end()?nullptr:at(it->second,index); + return Py_BuildValue("i",d?*d:0u); +} +PyObject* wikiGetMonsterSize(PyObject*,PyObject* args) { return levelListSize(wiki().monster,args); } +PyObject* wikiGetMonsterData(PyObject*,PyObject* args) { return levelListData(wiki().monster,args); } +PyObject* wikiGetStoneSize(PyObject*,PyObject* args) { return levelListSize(wiki().stone,args); } +PyObject* wikiGetStoneData(PyObject*,PyObject* args) { return levelListData(wiki().stone,args); } +// Iterates the std::unordered_map like the original; bucket order (and so list order) follows the +// standard library, which differs between MSVC and libc++. +PyObject* itemDropFrom(const std::unordered_map>& drops,PyObject* args) { + int vnum=0,refineArg=0; + if(!tupleInt(args,0,&vnum)||!tupleInt(args,1,&refineArg))return badArgument(); + const bool isRefine=refineArg!=0; + PyObject* list=PyList_New(0); + const uint32_t refineLevel=isRefine?GetRefineLevel(vnum,0,0):0; + for(const auto& [owner,items]:drops) { + for(const auto& d:items) { + const bool hit=isRefine?(uint32_t(vnum)>=d.itemVnum&&uint32_t(vnum)<=d.itemVnum+refineLevel):uint32_t(vnum)==d.itemVnum; + if(hit) {PyObject* obj=Py_BuildValue("i",owner);PyList_Append(list,obj);Py_DECREF(obj);break;} + } + } + return list; +} +PyObject* wikiGetItemDropFromChest(PyObject*,PyObject* args) { return itemDropFrom(wiki().specialDrop,args); } +PyObject* wikiGetItemDropFromMonster(PyObject*,PyObject* args) { return itemDropFrom(wiki().mobDrop,args); } +} // namespace + +bool WikiLoadText(WikiTextFile file,const std::string& fileName,const std::string& text) { + switch(file) { + case WikiTextFile::RefineTable:return LoadRefineTable(fileName,text); + case WikiTextFile::SpecialItemGroup:return ReadDropFile(fileName,text,"vnum","ReadSpecialDropItemFile",wiki().specialDrop); + case WikiTextFile::MobDropItem:return ReadDropFile(fileName,text,"mob","ReadMobDropItemFile",wiki().mobDrop); + } + return false; +} + +void WikiReadData(const std::string& localeFile) { + auto loadFile=[](WikiTextFile file,const std::string& fileName) { + std::string text; + try {text=ReadPackedText(fileName);} catch(const std::exception&) {return false;} + return WikiLoadText(file,fileName,text); + }; + if(!loadFile(WikiTextFile::RefineTable,"locale/common/refine_table.txt")) + wiki_trace_error("CPythonApplication - CPythonWiki::LoadRefineTable(locale/common/refine_table.txt)"); + const std::string itemProto=localeFile+"/item_proto"; + if(!WikiLoadItemTable(itemProto)) + wiki_trace_error("CPythonWiki - LoadItemTable("+itemProto+") Error"); + loadFile(WikiTextFile::SpecialItemGroup,"locale/common/special_item_group.txt"); + loadFile(WikiTextFile::MobDropItem,"locale/common/mob_drop_item.txt"); +} + +void WikiLoadMonster(const MobRecord& monster) { + if(BlackListMonster(monster.vnum))return; + if(monster.type!=0&&monster.type!=2)return; // monster & stone + int bucket; + if(monster.level>=1&&monster.level<=99)bucket=0; + else if(monster.level>=100&&monster.level<=120)bucket=1; + else if(monster.level>=121)bucket=2; + else return; + Wiki& w=wiki(); + if(monster.type==2)w.stone[bucket].push_back({monster.vnum,monster.level}); + else if(monster.rank>=MOB_RANK_BOSS)w.boss[bucket].push_back({monster.vnum,monster.level}); + else w.monster[bucket].push_back({monster.vnum,monster.level}); +} + +void WikiListReverse() { + auto byLevelAsc=[](const CharacterData& i,const CharacterData& j){return i.level +namespace ava2 { +struct MobRecord; +// CPythonWiki (AVA2 ENABLE_WIKI): see src/python_wiki.cpp. +void WikiReadData(const std::string& localeFile); +// The locale/common text loaders behind ReadData, fed from memory (tests / non-pack callers). +enum class WikiTextFile { RefineTable, SpecialItemGroup, MobDropItem }; +bool WikiLoadText(WikiTextFile file,const std::string& fileName,const std::string& text); +void WikiLoadMonster(const MobRecord& monster); +void WikiListReverse(); +void initWiki(); +} diff --git a/src/quest_state.h b/src/quest_state.h new file mode 100644 index 00000000..50b3461c --- /dev/null +++ b/src/quest_state.h @@ -0,0 +1,55 @@ +#pragma once +// CPythonQuest from AVA2 UserInterface/PythonQuest.cpp/.h. The vector order is +// observable through Python's array-index getters; quest IDs are a separate key. +#include +#include +#include +#include + +namespace ava2 { +enum QuestSendFlag : uint8_t { + QUEST_SEND_IS_BEGIN=1, QUEST_SEND_TITLE=2, QUEST_SEND_CLOCK_NAME=4, + QUEST_SEND_CLOCK_VALUE=8, QUEST_SEND_COUNTER_NAME=16, + QUEST_SEND_COUNTER_VALUE=32, QUEST_SEND_ICON_FILE=64 +}; +struct QuestRecord { + uint32_t index=0; + std::string title,clockName,counterName,iconFile; + int32_t clockValue=0,counterValue=0,startTime=0; +}; +class QuestState { +public: + std::vector records; + QuestRecord* find(uint32_t id) { + auto it=std::find_if(records.begin(),records.end(),[id](const auto& q){return q.index==id;}); + return it==records.end()?nullptr:&*it; + } + void erase(uint32_t id) { + auto it=std::find_if(records.begin(),records.end(),[id](const auto& q){return q.index==id;}); + if(it!=records.end())records.erase(it); + } + void apply(unsigned type,const QuestRecord& data,uint8_t flags,int32_t now,bool pythonAdd=false) { + if(type==3) { if(!pythonAdd)erase(data.index);return; } + if(type==1) { + // Wire BEGIN replaces and moves to the end; quest.Add BEGIN rejects duplicates. + if(pythonAdd && find(data.index))return; + erase(data.index); + records.push_back(data);records.back().startTime=now; + } else if(type==2) { + auto* q=find(data.index); + if(!q) { records.push_back({});q=&records.back();q->index=data.index;q->startTime=now; } + if(!data.title.empty())q->title=data.title; + if(!data.clockName.empty())q->clockName=data.clockName; + if(!data.counterName.empty())q->counterName=data.counterName; + if(!data.iconFile.empty())q->iconFile=data.iconFile; + if(flags&QUEST_SEND_CLOCK_VALUE) { q->clockValue=data.clockValue;q->startTime=now; } + if(flags&QUEST_SEND_COUNTER_VALUE)q->counterValue=data.counterValue; + } + } + static int32_t remaining(const QuestRecord& q,int32_t now) { + return q.clockValue<0?0:int32_t(uint32_t(q.startTime)+uint32_t(q.clockValue)-uint32_t(now)); + } +}; +QuestState& GetQuestState(); +int32_t GetQuestTime(); +} diff --git a/src/shop_search_state.h b/src/shop_search_state.h new file mode 100644 index 00000000..fd7164a4 --- /dev/null +++ b/src/shop_search_state.h @@ -0,0 +1,7 @@ +#pragma once +#include "eter_net/Packet.h" +#include +namespace ava2 { +// AVA2 PythonPrivateShopSearch: append-only result vector until explicit ClearSearchItems. +std::vector& GetShopSearchItems(); +} diff --git a/src/skill_description.h b/src/skill_description.h index a670676d..bf82dd89 100644 --- a/src/skill_description.h +++ b/src/skill_description.h @@ -8,6 +8,7 @@ #include #include #include +#include namespace ava2 { // Source: AVA2 Windows PythonSkill::RegisterSkillDesc; no 40250 data. struct SkillAffectDescription { std::string description, minFormula, maxFormula; }; @@ -25,24 +26,48 @@ struct SkillDescription { std::string needSPFormula, cooldownFormula, continuationSPFormula, durationFormula; uint32_t targetRange=0; std::vector affects; + // TSkillData fields only RegisterSkill (the per-skill text file) or the icon step fill. + uint32_t skillIndex=0; + std::string iconFileName; + uint16_t motionForMe=0; // never initialised by SSkillData(); 0 here + // GradeData[SKILL_EFFECT_COUNT].pImage / pImage as the file the original handed to + // CResourceManager::GetResourcePointer ("" = NULL); resolved when Python asks for the image. + std::array gradeImageFiles; + std::string imageFile; }; class SkillDescriptions { public: std::map records; + // CPythonSkill() m_SkillTypeIndexMap / m_SkillAttributeIndexMap (bit = index) / m_SkillNeedWeaponIndexMap. + static const std::map& typeMap() { + static const std::map types={{"none",0},{"active",1},{"support",2},{"guild",3},{"horse",4},{"warrior",1},{"assassin",1},{"sura",1},{"shaman",1},{"passive",1}}; + return types; + } + static const std::array& attributeNames() { + static const std::array attrs={"NEED_TARGET","TOGGLE","WEAPON_LIMITATION","MELEE_ATTACK","USE_HP","CAN_CHANGE_DIRECTION","STANDING_SKILL","ONLY_FOR_ALLIANCE","CAN_USE_FOR_ME","NEED_CORPSE","FAN_RANGE","CAN_USE_IF_NOT_ENOUGH","NEED_EMPTY_BOTTLE","NEED_POISON_BOTTLE","ATTACK_SKILL","TIME_INCREASE_SKILL","CHARGE_ATTACK","PASSIVE","CANNOT_LEVEL_UP","ONLY_FOR_GUILD_WAR","MOVING_SKILL","HORSE_SKILL","CIRCLE_RANGE","SEARCH_TARGET"}; + return attrs; + } + // Preserve the original ARROW logical-OR expression (mask1). + static const std::map& weaponMap() { + static const std::map weapons={{"SWORD",1u},{"DAGGER",2u},{"DOUBLE_SWORD",2u},{"BOW",4u},{"TWO_HANDED",8u},{"BELL",16u},{"FAN",32u},{"ARROW",1u},{"MOUNT_SPEAR",128u},{"EMPTY_HAND",1u<<11}}; + return weapons; + } static std::vector split(const std::string& text,char sep) { std::vector out; size_t start=0; for (;;) { auto end=text.find(sep,start);out.push_back(text.substr(start,end-start));if(end==std::string::npos)break;start=end+1; } return out; } - bool load(const std::string& text) { - static const std::map types={{"none",0},{"active",1},{"support",2},{"guild",3},{"horse",4},{"warrior",1},{"assassin",1},{"sura",1},{"shaman",1},{"passive",1}}; - static const std::array attrs={"NEED_TARGET","TOGGLE","WEAPON_LIMITATION","MELEE_ATTACK","USE_HP","CAN_CHANGE_DIRECTION","STANDING_SKILL","ONLY_FOR_ALLIANCE","CAN_USE_FOR_ME","NEED_CORPSE","FAN_RANGE","CAN_USE_IF_NOT_ENOUGH","NEED_EMPTY_BOTTLE","NEED_POISON_BOTTLE","ATTACK_SKILL","TIME_INCREASE_SKILL","CHARGE_ATTACK","PASSIVE","CANNOT_LEVEL_UP","ONLY_FOR_GUILD_WAR","MOVING_SKILL","HORSE_SKILL","CIRCLE_RANGE","SEARCH_TARGET"}; + // Called where RegisterSkillDesc registers the icon images (after the type lookup succeeded), + // with the raw (not lower-cased) job token and the icon column. + using IconHook=std::function; + bool load(const std::string& text,const IconHook& registerIcons=nullptr) { + const auto& types=typeMap();const auto& attrs=attributeNames(); std::istringstream input(text);std::string line; while(std::getline(input,line)) { if(!line.empty()&&line.back()=='\r')line.pop_back(); auto t=split(line,'\t');if(!line.empty()&&line.back()=='\t')t.pop_back();if(t.size()<2)continue; uint32_t id=uint32_t(std::atoi(t[0].c_str()));if(!id)continue; - auto& data=records[id];auto job=t[1]; + auto& data=records[id];data.skillIndex=id;auto job=t[1]; std::transform(job.begin(),job.end(),job.begin(),[](unsigned char c){return std::tolower(c);}); auto type=types.find(job);if(type==types.end())continue; data.type=type->second; @@ -53,9 +78,9 @@ public: data.conditions.clear();for(int i=6;i<9;++i)if(!t[i].empty())data.conditions.push_back(t[i]); // Re-registering a row ORs attributes, matching the original. for(const auto& token:split(t[10],'|'))for(size_t bit=0;bit weapons={{"SWORD",1u},{"DAGGER",2u},{"DOUBLE_SWORD",2u},{"BOW",4u},{"TWO_HANDED",8u},{"BELL",16u},{"FAN",32u},{"ARROW",1u},{"MOUNT_SPEAR",128u},{"EMPTY_HAND",1u<<11}}; + const auto& weapons=weaponMap(); for(const auto& token:split(t[11],'|')) {auto it=weapons.find(token);if(it!=weapons.end())data.needWeapon|=it->second;} + if(registerIcons)registerIcons(id,data,t[1],t[12]); if(t.size()>13) {data.noMotion=t[13].empty();data.motion=uint16_t(std::atoi(t[13].c_str()));} else data.motion=0; if(t.size()>15)data.targetCountFormula=t[15]; if(t.size()>16)data.motionLoopCountFormula=t[16]; diff --git a/src/switchbot_state.h b/src/switchbot_state.h new file mode 100644 index 00000000..7a3c1c02 --- /dev/null +++ b/src/switchbot_state.h @@ -0,0 +1,13 @@ +#pragma once +// AVA2 PythonSwitchbot.cpp, active Locale_inc.h attribute set profile. +#include "eter_net/Packet.h" +#include +namespace ava2 { +struct SwitchbotState { + TSwitchbotTable table{}; + std::map> attributes; + int AttributeSet(uint8_t slot) const; + void ClearSlot(uint8_t slot); +}; +SwitchbotState& GetSwitchbotState(); +} diff --git a/tests/ava2_render_3d_test.cpp b/tests/ava2_render_3d_test.cpp index 685b050a..1e929db8 100644 --- a/tests/ava2_render_3d_test.cpp +++ b/tests/ava2_render_3d_test.cpp @@ -16,8 +16,14 @@ #include #include #include +#include "test_rundir.h" + +using ava2_test::kSkip; +using ava2_test::PackMaker; int main(int argc, char** argv) { + if (!ava2_test::EnterTestRunDir()) return kSkip; + std::string model_path = "ymir work/pc/warrior/warrior_assasin1.gr2"; if (argc > 1) { model_path = argv[1]; @@ -29,8 +35,20 @@ int main(int argc, char** argv) { } else if (std::filesystem::exists("../" + model_path)) { model_path = "../" + model_path; } else { - std::cerr << "Model file not found: " << model_path << std::endl; - return 1; + std::cerr << "SKIP: model file not found: " << model_path << std::endl; + return kSkip; + } + } + + // The scene below loads cwd-relative client assets (merged `ymir work`, bgm, sound), + // like the Windows client root. Without them the asserts would only report the + // environment, so skip instead; when they are present every check runs. + for (const char* required : {"ymir work/zone/b/obj/b_general_obj_01_2.gr2", + "bgm/login_window.mp3", + "sound/ui/click.wav"}) { + if (!std::filesystem::exists(required)) { + std::cerr << "SKIP: client asset missing from working directory: " << required << std::endl; + return kSkip; } } @@ -259,13 +277,13 @@ int main(int argc, char** argv) { // ── Test Terrain Heightmap & Outdoor Scene Rendering ──────────────────── std::cout << "\n── Testing Terrain Heightmap & Outdoor Scene Rendering ──" << std::endl; ava2::TerrainHeightmap terrain; - std::string raw_path = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/height.raw"; + std::string raw_path = PackMaker() + "/Maps/metin2_map_a1/001003/height.raw"; if (std::filesystem::exists(raw_path)) { bool raw_ok = terrain.LoadRaw(raw_path, 0.5f, 50.0f); std::cout << "Loaded Metin2 height.raw: " << (raw_ok ? "SUCCESS" : "FAILED") << std::endl; assert(raw_ok && "Metin2 height.raw must load successfully"); - std::string tile_path = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/tile.raw"; + std::string tile_path = PackMaker() + "/Maps/metin2_map_a1/001003/tile.raw"; if (std::filesystem::exists(tile_path)) { bool tile_ok = terrain.LoadTileRaw(tile_path); std::cout << "Loaded Metin2 tile.raw: " << (tile_ok ? "SUCCESS" : "FAILED") << std::endl; @@ -306,11 +324,11 @@ int main(int argc, char** argv) { assert(added_bldg && "Building model must instantiate successfully"); // Test AreaData & Property scanning - std::string prop_dir = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/property/property"; + std::string prop_dir = PackMaker() + "/property/property"; if (std::filesystem::exists(prop_dir)) { obj_mgr.RegisterProperty(234517142, bldg_path); assert(obj_mgr.GetPropertyCount() >= 1); - std::string areadata_path = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/areadata.txt"; + std::string areadata_path = PackMaker() + "/Maps/metin2_map_a1/001003/areadata.txt"; if (std::filesystem::exists(areadata_path)) { obj_mgr.LoadAreaData(areadata_path, 0.05f); std::cout << "Loaded objects from areadata.txt: " << obj_mgr.GetObjectCount() << std::endl; @@ -369,7 +387,7 @@ int main(int argc, char** argv) { // ── Test WaterManager & Fog Rendering ────────────────────────────────── std::cout << "\n── Testing WaterManager & Depth Fog System ──" << std::endl; ava2::WaterManager water_mgr; - std::string water_file = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/water.wtr"; + std::string water_file = PackMaker() + "/Maps/metin2_map_a1/001003/water.wtr"; if (std::filesystem::exists(water_file)) { bool water_loaded = water_mgr.LoadWater(water_file, 40.0f, 0.5f, 40.0f, -2560.0f, -2560.0f); assert(water_loaded && "Failed to load water.wtr"); @@ -521,7 +539,7 @@ int main(int argc, char** argv) { // ── Test MinimapManager (Radar Minimap System) ────────────────────────── std::cout << "\n── Testing MinimapManager (Radar Minimap System) ──" << std::endl; ava2::MinimapManager minimap; - std::string minimap_test_path = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/minimap.dds"; + std::string minimap_test_path = PackMaker() + "/Maps/metin2_map_a1/001003/minimap.dds"; if (std::filesystem::exists(minimap_test_path)) { bool m_ok = minimap.LoadMinimap(minimap_test_path); std::cout << "Loaded Metin2 minimap.dds: " << (m_ok ? "SUCCESS" : "FAILED") @@ -830,19 +848,19 @@ int main(int argc, char** argv) { std::string test_raw = "map/metin2_map_a1/001003/height.raw"; if (!std::filesystem::exists(test_raw)) { - test_raw = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/height.raw"; + test_raw = PackMaker() + "/Maps/metin2_map_a1/001003/height.raw"; } std::string test_tile = "map/metin2_map_a1/001003/tile.raw"; if (!std::filesystem::exists(test_tile)) { - test_tile = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/tile.raw"; + test_tile = PackMaker() + "/Maps/metin2_map_a1/001003/tile.raw"; } std::string test_attr = "map/metin2_map_a1/001003/attr.atr"; if (!std::filesystem::exists(test_attr)) { - test_attr = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/metin2_map_a1/001003/attr.atr"; + test_attr = PackMaker() + "/Maps/metin2_map_a1/001003/attr.atr"; } std::string test_tset = "textureset/metin2_map1.txt"; if (!std::filesystem::exists(test_tset)) { - test_tset = "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Maps/textureset/metin2_map1.txt"; + test_tset = PackMaker() + "/textureset/textureset/metin2_map1.txt"; } if (std::filesystem::exists(test_raw)) { @@ -1003,7 +1021,7 @@ int main(int argc, char** argv) { std::vector mss_events; bool mss_loaded = snd.LoadCharacterSoundScript("sound/pc/warrior/skill/samyeon.mss", mss_events); if (!mss_loaded) { - mss_loaded = snd.LoadCharacterSoundScript("/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Sound/sound/pc/warrior/skill/samyeon.mss", mss_events); + mss_loaded = snd.LoadCharacterSoundScript(PackMaker() + "/Sound/sound/pc/warrior/skill/samyeon.mss", mss_events); } assert(mss_loaded && "Samyeon .mss script must be loaded"); assert(mss_events.size() == 2 && "Samyeon .mss must have exactly 2 sound events"); diff --git a/tests/ava2_window_tree_test.cpp b/tests/ava2_window_tree_test.cpp index 217481ee..c868d02c 100644 --- a/tests/ava2_window_tree_test.cpp +++ b/tests/ava2_window_tree_test.cpp @@ -5,9 +5,11 @@ #include #include #include +#include "test_rundir.h" int main(int argc, char** argv) { if (argc != 3) return 2; + if (!ava2_test::EnterTestRunDir()) return ava2_test::kSkip; try { ava2::PythonRuntime runtime(argv[1], argv[2]); auto* wm = runtime.window_manager(); diff --git a/tests/battlepass_test.cpp b/tests/battlepass_test.cpp new file mode 100644 index 00000000..d296b74a --- /dev/null +++ b/tests/battlepass_test.cpp @@ -0,0 +1,75 @@ +#include "battlepass_state.h" +#include "python_runtime.h" +#include "eter_net/PythonNetworkStream.h" +#include +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void u32(Bytes& b,uint32_t value) {for(unsigned i=0;i<4;++i)b.push_back(uint8_t(value>>(8*i)));} +Bytes record(uint8_t sub) { + Bytes b{230,sub};u32(b,uint32_t(-100));u32(b,0x80000001);u32(b,0xffffffff);u32(b,uint32_t(-10));u32(b,50);u32(b,0xffffffff); + for(unsigned i=0;i<4;++i) {u32(b,100+i);u32(b,i==3?0x80000001:i+1);} + return b; +} +Bytes control(uint8_t sub) {Bytes b(58);b[0]=230;b[1]=sub;return b;} +void send(const Bytes& b) {auto& stream=PythonNetworkStream::Instance();stream.PushRecvData(b);stream.ProcessRecvData();} +int main(int argc,char** argv) { + if(argc!=3)return 2; + try { + { + PythonRuntime python(argv[1],argv[2]);auto& stream=PythonNetworkStream::Instance();stream.ResetConnection();stream.SetPhase(PHASE_GAME); + python.execute(R"PY(import battlepass as bp,net,weakref,gc +assert bp.CountDates()==0 and bp.GetTime()==0 +assert bp.GetDates(-1)==(0,0) and bp.GetDatesCount(0)==(0,0,0) +assert bp.GetDatesItems(0,0)==0 +assert bp.GetDates() is None and bp.GetDatesItems(0) is None +assert bp.Reward('x') is None and bp.SetBattlePassHandler() is None +class Game: + def __init__(self): self.events=[] + def BINARY_BATTLEPASS_OPEN(self): self.events.append('open') + def BINARY_BATTLEPASS_MP(self): self.events.append('mp') +class Loader: + def __init__(self): self.events=[] + def BINARY_BATTLEPASS_LOADING(self,sub): + self.events.append((sub,bp.CountDates(),bp.GetDatesCount(0),bp.GetTime())) +game=Game() +loader=Loader() +net.SetPhaseWindow(net.PHASE_WINDOW_GAME,game) +bp.SetBattlePassHandler(loader) +)PY"); + auto data=record(2);require(data.size()==58,"battlepass literal wire size");data.push_back(44); + stream.PushRecvData(data.data(),57);stream.ProcessRecvData();python.execute("assert bp.CountDates()==0\n"); + stream.PushRecvData(data.data()+57,2);stream.ProcessRecvData();require(stream.PopSendBytes()==Bytes{254},"battlepass consumed following ping"); + send(record(2));send(record(7));send(record(7));send(record(3));send(control(4));send(control(8));send(control(0));send(control(9)); + python.execute(R"PY(assert bp.CountDates()==2 +assert bp.GetDates(0)==(-2147483647,-1) and bp.GetDates(1)==bp.GetDates(0) +assert bp.GetDates(2)==(0,0) +assert bp.GetDatesCount(0)==(-10,50,-1) and bp.GetDatesCount(1)==bp.GetDatesCount(0) +assert bp.GetDatesCount(2)==(0,0,0) +assert bp.GetDatesItems(0,0)==(100,1) and bp.GetDatesItems(0,3)==(103,-2147483647) +assert bp.GetDatesItems(0,4)==(0,0) and bp.GetDatesItems(0,-1)==(0,0) +assert bp.GetDatesItems(-1,4)==0 +assert bp.GetTime()==-100 +assert loader.events==[(4,2,(-10,50,-1),-100),(8,2,(-10,50,-1),-100)] +assert game.events==['open','mp'] +)PY"); + send(control(6));python.execute("assert bp.CountDates()==2 and bp.GetTime()==-100\nassert bp.GetDatesCount(0)==(0,0,0)\n"); + send(record(7));send(control(1));send(control(255));send(control(5));send(control(8)); + python.execute("assert bp.CountDates()==0 and bp.GetTime()==0\nassert bp.GetDatesCount(0)==(-10,50,-1)\nassert loader.events[-1]==(8,0,(-10,50,-1),0)\nbp.Open()\nbp.Reward(1)\n");require(stream.PopSendBytes().empty(),"battlepass sent without actionable main actor"); + SNetworkActorData actor{};actor.m_dwVID=1001;actor.m_stName="BattlePassFixture";NetworkActorManager::Instance().AppendActor(actor);stream.SetMainActorVID(1001); + auto instance=NetworkActorManager::Instance().GetActorInstance(1001);require(bool(instance),"missing native actor"); + python.execute("bp.Open()\nbp.Reward(-1)\nbp.Reward(2147483649)\n"); + auto packets=stream.PopSendPacketsWithSequence();require(packets.size()==3,"battlepass request count"); + require(packets[0].first==Bytes{230,0,0,0,0,0} && packets[1].first==Bytes{230,5,255,255,255,255} && packets[2].first==Bytes{230,5,1,0,0,128},"battlepass request Win32 byte conversion"); + require(packets[0].second && packets[1].second && packets[2].second,"battlepass missing SendSequence"); + instance->SetSleep(true);python.execute("bp.Open()\nbp.Reward(0)\n");require(stream.PopSendBytes().empty(),"sleeping actor sent battlepass request");instance->SetSleep(false); + python.execute("temporary=Loader()\nref=weakref.ref(temporary)\nbp.SetBattlePassHandler(temporary)\ndel temporary\ngc.collect()\nassert ref() is not None\n"); + send(control(1));send(control(6));python.execute("assert ref() is not None\nbp.SetBattlePassHandler(None)\ngc.collect()\nassert ref() is None\nclass Broken:\n def BINARY_BATTLEPASS_LOADING(self,*args): raise ValueError('expected failure')\nbp.SetBattlePassHandler(Broken())\n"); + send(record(2));send(control(4));python.execute("assert bp.CountDates()==1\n"); + require(stream.GetUnportedPackets().empty(),"battlepass still routed through skip handler");stream.ResetConnection(); + } + {PythonRuntime python(argv[1],argv[2]);python.execute("import battlepass as bp\nassert bp.CountDates()==0 and bp.GetTime()==0 and bp.GetDatesCount(0)==(0,0,0)\n");} + std::cout<<"AVA2 battlepass state, wire and Python parity passed\n"; + }catch(const std::exception& e){std::cerr< +#include +#include +#include +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +void u32(Bytes& b,uint32_t v) { for(unsigned i=0;i<4;++i)b.push_back(uint8_t(v>>(8*i))); } +// One-row MIPX item_proto (literal LZO run), as tests/item_data_test.cpp builds it. +void proto(const std::filesystem::path& p,uint32_t id,const std::string& name) { + Bytes raw;u32(raw,id);raw.resize(172);std::copy(name.begin(),name.end(),raw.begin()+4);std::copy(name.begin(),name.end(),raw.begin()+29);raw[54]=1;raw[57]=1; + Bytes compressed{uint8_t(17+raw.size())};compressed.insert(compressed.end(),raw.begin(),raw.end());compressed.insert(compressed.end(),{17,0,0}); + Bytes file{'M','I','P','X'};u32(file,1);u32(file,172);u32(file,1);u32(file,20+compressed.size()); + file.insert(file.end(),{'M','C','O','Z'});u32(file,0);u32(file,compressed.size());u32(file,raw.size());file.insert(file.end(),{'M','C','O','Z'}); + file.insert(file.end(),compressed.begin(),compressed.end()); + std::filesystem::create_directories(p.parent_path());std::ofstream out(p,std::ios::binary);out.write(reinterpret_cast(file.data()),file.size()); +} +std::vector showing(DWORD id) { + std::vector out; + for(const auto* line:CPythonChat::Instance().GetChatSet(id)->m_ShowingChatLineList) out.push_back(line->text); + return out; +} +int main(int argc,char** argv) { + if(argc!=3)return 2; + auto root=std::filesystem::temp_directory_path()/("ava2-chat-"+std::to_string(getpid())); + std::filesystem::create_directories(root); + int rc=0; + try { + PythonRuntime python(argv[1],root); + proto(root/"proto",0x13,"Sword"); + require(LoadItemTable("proto"),"item proto fixture rejected"); + auto& chat=CPythonChat::Instance(); + chat.SetCurrentMillisecond(1000); + python.execute( + "import chat\n" + "assert (chat.CHAT_TYPE_TALKING,chat.CHAT_TYPE_SHOUT,chat.CHAT_TYPE_DICE_INFO,chat.CHAT_TYPE_MISSION)==(0,6,10,14)\n" + "assert (chat.WHISPER_TYPE_CHAT,chat.WHISPER_TYPE_GM,chat.WHISPER_TYPE_SYSTEM)==(0,5,255)\n" + "assert (chat.BOARD_STATE_VIEW,chat.BOARD_STATE_EDIT,chat.BOARD_STATE_LOG)==(0,1,2)\n" + "assert (chat.CHAT_SET_CHAT_WINDOW,chat.CHAT_SET_LOG_WINDOW)==(0,1)\n" + "assert chat.GetLineCount(0)==0 and chat.GetLineCount(1)==0 and chat.GetLineCount(7)==0\n" + "assert chat.GetLineStep(0)==15 and chat.GetLineStep(7)==0\n"); + + // __Initialize colours; SetChatColor packs 0xff RRGGBB. + require(chat.GetChatColorValue(0)==0xffffffffu,"talking colour"); + require(chat.GetChatColorValue(CPythonChat::CHAT_TYPE_WHISPER)==0xff4AE14Au,"whisper colour"); + require(chat.GetChatColorValue(CPythonChat::CHAT_TYPE_DICE_INFO)==0xffcc00ccu,"dice colour"); + require(chat.GetChatColorValue(CPythonChat::CHAT_TYPE_INFO)==DWORD(D3DXCOLOR(1.0f,0.785f,0.785f,1.0f)),"info colour"); + require(chat.GetChatColorValue(99)==DWORD(D3DXCOLOR(0.0f,0.0f,1.0f,1.0f)),"out-of-range colour"); + python.execute("chat.SetChatColor(chat.CHAT_TYPE_PARTY,1,2,3)\nchat.SetChatColor(15,1,2,3)\n"); + require(chat.GetChatColorValue(CPythonChat::CHAT_TYPE_PARTY)==0xff010203u,"SetChatColor"); + + // Every line store receives the line; "#ebvs" lines are dropped. + python.execute( + "chat.AppendChat(chat.CHAT_TYPE_TALKING,'a : hello')\n" + "chat.AppendChat(chat.CHAT_TYPE_INFO,'x #ebvs y')\n" + "assert chat.GetLineCount(0)==1 and chat.GetLineCount(1)==1\n" + "assert chat.GetVisibleLineCount(0)==1\n"); + require(chat.GetChatLineDeque(0)->front()->text=="a : hello","line text"); + require(chat.GetChatLineDeque(0)->front()->fAppendedTime==1.0f,"appended time is CTimer seconds"); + + // Item hyperlinks take this client's item name. + python.execute("chat.AppendChat(chat.CHAT_TYPE_INFO,'|cfff1e6c0|Hitem:13:0:0:0:0|h[Old]|h|r and |Hitem:zz:0|h[q]|h')\n"); + require(chat.GetChatLineDeque(0)->back()->text=="|cfff1e6c0|Hitem:13:0:0:0:0|h[Sword]|h|r and |Hitem:zz:0|h[q]|h","item link rename"); + + // SHOUT: "|lang|N|" / "|empire|N|" prefixes are stripped; a bad language becomes 1. + python.execute( + "chat.AppendChat(chat.CHAT_TYPE_SHOUT,'|lang|3||empire|2|Bob : hi')\n" + "chat.AppendChat(chat.CHAT_TYPE_SHOUT,'|lang|99|Al : yo')\n" + "chat.AppendChat(chat.CHAT_TYPE_SHOUT,'|lang|5')\n"); + { + const auto& lines=*chat.GetChatLineDeque(0); + const auto* bob=lines[lines.size()-3];const auto* al=lines[lines.size()-2];const auto* bare=lines.back(); + require(bob->text=="Bob : hi" && bob->countryIndex==3 && bob->empireIndex==2,"shout prefixes"); + require(al->text=="Al : yo" && al->countryIndex==1 && al->empireIndex==0,"shout language clamp"); + require(bare->text=="5" && bare->countryIndex==5,"shout without closing bar"); + } + python.execute( + "assert chat.GetLineCount(0)==5,(chat.GetLineCount(0),chat.GetLineCount(1))\n" + "chat.DisableCountryMode(0,3)\nassert chat.GetLineCount(0)==4 and chat.GetLineCount(1)==5,(chat.GetLineCount(0),chat.GetLineCount(1))\n" + "chat.EnableCountryMode(0,3)\nchat.DisableCountryMode(0,99)\nassert chat.GetLineCount(0)==5\n" + "chat.DisableChatMode(0,chat.CHAT_TYPE_SHOUT)\nassert chat.GetLineCount(0)==2\n" + "chat.ToggleChatMode(0,chat.CHAT_TYPE_SHOUT)\nassert chat.GetLineCount(0)==5\n" + "chat.ToggleChatMode(0,-1)\nchat.EnableChatMode(0,1000)\n"); + + // ArrangeShowingChat: (height+step)/step lines ending at SetEndPos. + python.execute("chat.Clear()\nfor i in range(5):\n chat.AppendChat(chat.CHAT_TYPE_TALKING,'l%d'%i)\nchat.SetHeight(0,30)\nchat.ArrangeShowingChat(0)\n"); + require(showing(0)==std::vector{"l2","l3","l4"},"end-position 1 window"); + require(showing(1)==std::vector{"l4"},"zero-height window shows one line"); + python.execute("chat.SetEndPos(0,0.0)\nassert chat.GetVisibleLineCount(0)==3\n"); + require(showing(0)==std::vector{"l1","l2","l3"},"end-position 0 window"); + python.execute("chat.SetEndPos(0,5.0)\nchat.SetStep(0,10)\nassert chat.GetLineStep(0)==10\nchat.ArrangeShowingChat(0)\nassert chat.GetVisibleLineCount(0)==3\n"); + require(showing(0)==std::vector{"l2","l3","l4"},"step 10: iHeight starts at 12, so 12/22/32 fit under 40"); + python.execute("chat.SetStep(0,0)\nchat.ArrangeShowingChat(0)\nassert chat.GetVisibleLineCount(0)==0\nchat.SetStep(0,15)\nchat.ArrangeShowingChat(0)\n"); + + // VIEW mode fades lines older than 5 s by a tenth per update; a new append re-arranges. + chat.SetCurrentMillisecond(7000); + python.execute("chat.SetPosition(0,10,500)\nchat.Update(0)\nchat.Render(0)\n"); + require(std::abs(chat.GetChatLineDeque(0)->back()->GetColorRef(0).a-0.9f)<1e-4f,"view mode fade"); + require(chat.GetChatLineDeque(0)->back()->GetColorRef(1).a==1.0f,"fade is per chat set"); + python.execute("chat.SetBoardState(0,chat.BOARD_STATE_EDIT)\nchat.Update(0)\nchat.SetBoardState(0,chat.BOARD_STATE_LOG)\nchat.Update(0)\nchat.Close()\n"); + require(chat.GetChatSet(0)->m_ShowingChatLineList.front()->fAppendedTime==0.0f,"Close zeroes appended time"); + + // 300-line cap per store. + python.execute("for i in range(305):\n chat.AppendChat(chat.CHAT_TYPE_TALKING,'n%d'%i)\nassert chat.GetLineCount(0)==300\n"); + require(chat.GetChatLineDeque(0)->front()->text=="n5","oldest lines dropped"); + + // AppendChatWithDelay waits for CTimer ms past the delay; Update on an existing set flushes + // into every set (an unknown id returns before the flush). + python.execute("chat.Clear()\nchat.AppendChatWithDelay(chat.CHAT_TYPE_NOTICE,'later',500)\nchat.Update(0)\nassert chat.GetLineCount(0)==0\n"); + require(chat.GetWaitChatCount()==1,"delayed chat queued"); + chat.SetCurrentMillisecond(7500);python.execute("chat.Update(0)\nassert chat.GetLineCount(0)==0\n"); + chat.SetCurrentMillisecond(7501);python.execute("chat.Update(5)\nassert chat.GetLineCount(0)==0\nchat.Update(1)\nassert chat.GetLineCount(0)==1 and chat.GetLineCount(1)==1\n"); + require(chat.GetWaitChatCount()==0,"delayed chat flushed"); + + // CreateChatSet copies set 0; ids are stored by BYTE, colours index by set id. + python.execute( + "assert chat.CreateChatSet(2)==2 and chat.GetLineCount(2)==1\n" + "assert chat.CreateChatSet(256)==256 and chat.GetLineCount(256)==0\n" + "chat.AppendChat(chat.CHAT_TYPE_TALKING,'more')\nassert chat.GetLineCount(2)==2\n" + "chat.DeleteChatSet(2)\nassert chat.GetLineCount(2)==0 and chat.GetLineStep(2)==0\n"); + + // Ignore toggles; chat.IsIgnoreCharacter returns None as on Windows. + python.execute("chat.IgnoreCharacter('troll')\nassert chat.IsIgnoreCharacter('troll') is None\n"); + require(chat.IsIgnoreCharacter("troll"),"ignore set"); + python.execute("chat.IgnoreCharacter('troll')\n"); + require(!chat.IsIgnoreCharacter("troll"),"ignore toggled off"); + + // Whispers. + python.execute( + "chat.AppendWhisper(chat.WHISPER_TYPE_CHAT,'bob','hi')\n" + "chat.AppendWhisper(chat.WHISPER_TYPE_GM,'bob','gm')\n" + "chat.CreateWhisper('al')\nchat.CreateWhisper('al')\n"); + require(chat.GetNewChatCount()==2 && chat.GetWhisperMap().size()==2,"whisper line count"); + require(chat.GetWhisperMap().at("bob")->GetLines().size()==2,"whisper lines"); + python.execute("chat.SetWhisperBoxSize('bob',200.0,90.0)\nchat.SetWhisperPosition('bob',0.5)\nchat.RenderWhisper('bob',1.0,2.0)\nchat.SetWhisperBoxSize('nobody',1.0,1.0)\n"); + { + const auto* bob=chat.GetWhisperMap().at("bob"); + require(bob->GetWidth()==200.0f && bob->GetHeight()==90.0f && bob->GetCurPosition()==0.5f,"whisper box"); + require(chat.GetNewChatCount()==0,"GetWhisper marks lines read"); + } + python.execute( + "class Iface:\n def __init__(self):\n self.names=[]\n def MakeWhisperButton(self,n):\n self.names.append(n)\n" + "f=Iface()\nchat.InitWhisper(f)\nassert f.names==['al','bob'],f.names\n" + "chat.ClearWhisper('bob')\nchat.ClearWhisper('bob')\n"); + require(chat.GetWhisperMap().size()==1,"ClearWhisper"); + + // GetLinkFromHyperlink. + python.execute( + "assert chat.GetLinkFromHyperlink('item:13:1:0:0:0')=='|cfff1e6c0|Hitem:13:1:0:0:0|h[Sword]|h|r'\n" + "assert chat.GetLinkFromHyperlink('item:13:0:0:0:0:1:50:2:30')=='|cffffc700|Hitem:13:0:0:0:0:1:50:2:30|h[Sword]|h|r'\n" + "assert chat.GetLinkFromHyperlink('item:13:0:0:0:0:1:50:2')=='|cffffc700|Hitem:13:0:0:0:0:1:50:2:0|h[Sword]|h|r'\n" + "assert chat.GetLinkFromHyperlink('item:13:0:0:0:0:1')=='|cfff1e6c0|Hitem:13:0:0:0:0|h[Sword]|h|r'\n" + "assert chat.GetLinkFromHyperlink('item:13:0:zz:0:0')=='|cfff1e6c0|Hitem:13:0:ffffffff:0:0|h[Sword]|h|r'\n" + "assert chat.GetLinkFromHyperlink('item:14:0:0:0:0')==''\n" + "assert chat.GetLinkFromHyperlink('item:13')==''\n" + "assert chat.GetLinkFromHyperlink('nolink')==''\n" + "assert chat.GetLinkFromHyperlink('pm:bob')==''\n"); + + // Bad arguments return None (Py_BuildException without a message). + python.execute( + "assert chat.AppendChat('x') is None and chat.GetLineCount() is None\n" + "assert chat.CreateChatSet('a') is None and chat.SetEndPos(0,'z') is None\n"); + + python.execute("chat.Clear()\nassert chat.GetLineCount(0)==0 and chat.GetLineStep(1)==15\n"); + require(chat.GetWhisperMap().empty(),"Clear destroys whispers"); + chat.SetCurrentMillisecond(0); + std::cout<<"AVA2 chat parity passed\n"; + } catch(const std::exception& e) { std::cerr< 0 else 1) +if marker.encode() not in result.stdout: + print("Test stopped before its completion marker", file=sys.stderr) + sys.exit(1) diff --git a/tests/chr_test.cpp b/tests/chr_test.cpp new file mode 100644 index 00000000..33b8ff98 --- /dev/null +++ b/tests/chr_test.cpp @@ -0,0 +1,144 @@ +// chr / chrmgr against the original AVA2 PythonCharacterModule.cpp + PythonCharacterManagerModule.cpp: +// the module surfaces, the no-instance getter answers, Py_BuildException (chr) vs Py_BadArgument +// (chrmgr) argument errors, the rotation/direction conversions, CreateInstance's dict path (with the +// "y" -> m_lPosX bug), GetVIDInfo, SetPathName's d:/ymir guard, SetRaceHeight and testSetRideMan. +#include "python_gameplay_modules.h" +#include "python_runtime.h" +#include "eter_net/NetworkActorManager.h" +#include "eter_render/RaceData.h" +#include +#include +#include +using namespace ava2; +namespace fs = std::filesystem; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +int main(int argc,char** argv) { + if(argc!=3)return 2; + try { + const fs::path root=fs::temp_directory_path()/"ava2_chr_test"; + fs::remove_all(root);fs::create_directories(root); + fs::current_path(root); + PythonRuntime python(argv[1],root); + auto& mgr=NetworkActorManager::Instance(); + mgr.Destroy(); + + python.execute( + "import chr, chrmgr\n" + "chr_names=('DismountHorse','MountHorse','SetSash','Destroy','Update','Deform','Render','RenderCollision'," + "'CreateInstance','DeleteInstance','DeleteInstanceByFade','SelectInstance','HasInstance','IsEnemy','IsNPC'," + "'IsGameMaster','IsPartyMember','Select','SetAddRenderMode','SetBlendRenderMode','Unselect','Hide','Show','Pick'," + "'PickAll','SetArmor','SetWeapon','ChangeShape','SetRace','SetHair','ChangeHair','SetVirtualID','SetNameString'," + "'SetInstanceType','SetPixelPosition','SetDirection','Refresh','Revive','Die','AttachEffectByID','AttachEffectByName'," + "'LookAt','SetMotionMode','SetLoopMotion','BlendLoopMotion','PushOnceMotion','PushLoopMotion','GetPixelPosition'," + "'SetRotation','SetRotationAll','BlendRotation','GetRotation','GetRace','GetName','GetNameByVID','GetGuildID'," + "'GetProjectPosition','GetVirtualNumber','GetInstanceType','GetBoundBoxOnlyXY','RaceToJob','RaceToSex'," + "'testGetPKData','FaintTest','SetMoveSpeed','SetAttackSpeed','WeaponTraceSetTexture','WeaponTraceUseAlpha'," + "'WeaponTraceUseTexture','MoveToDestPosition','testSetComboType','testSetAddRenderMode','testSetModulateRenderMode'," + "'testSetAddRenderModeRGB','testSetModulateRenderModeRGB','testSetSpecularRenderMode','testSetSpecularRenderMode2'," + "'testRestoreRenderMode','testSetRideMan','IsStone')\n" + "funcs=sorted(n for n in dir(chr) if callable(getattr(chr,n)))\n" + "assert funcs==sorted(chr_names), set(funcs)^set(chr_names)\n" + "assert not hasattr(chr,'RequestPetName')\n" + "mgr_names=('SetRaceHeight','SetEmpireNameMode','GetVIDInfo','GetPickedVID','SetShapeModel','AppendShapeSkin'," + "'SetPathName','LoadRaceData','LoadLocalRaceData','CreateRace','SelectRace','RegisterAttachingBoneName'," + "'RegisterMotionMode','SetMotionRandomWeight','RegisterNormalAttack','ReserveComboAttack','RegisterComboAttack'," + "'ReserveComboAttackNew','RegisterComboAttackNew','RegisterMotionData','RegisterRaceName','RegisterRaceSrcName'," + "'RegisterCacheMotionData','SetAffect','SetEmoticon','IsPossibleEmoticon','RegisterEffect','RegisterCacheEffect'," + "'RegisterPointEffect','ShowPointEffect','ToggleDirectionLine','SetMovingSpeed','SetDustGap','SetHorseDustGap'," + "'RegisterTitleName','RegisterNameColor','RegisterTitleColor')\n" + "funcs=sorted(n for n in dir(chrmgr) if callable(getattr(chrmgr,n)))\n" + "assert funcs==sorted(mgr_names), set(funcs)^set(mgr_names)\n" + "assert not hasattr(chrmgr,'RegisterMotion')\n" + // No selected / unknown instance answers. + "assert chr.GetRotation()==0.0 and chr.GetRace()==0 and chr.GetName()==0\n" + "assert chr.GetNameByVID(5)=='None' and chr.GetGuildID(5)==0\n" + "assert chr.GetProjectPosition(5,0)==(-100,-100)\n" + "assert chr.GetVirtualNumber(5)==6 and chr.GetInstanceType(5)==6\n" + "assert chr.GetBoundBoxOnlyXY()==(0.0,0.0,0.0,0.0)\n" + "assert chr.testGetPKData()==(0,4)\n" + "assert chr.Pick()==-1 and chr.PickAll()==-1 and chrmgr.GetPickedVID()==-1\n" + "assert chr.GetPixelPosition(5) is None\n" + "assert chr.IsEnemy(5)==0 and chr.IsNPC(5)==0 and chr.IsStone(5)==0 and chr.IsGameMaster(5)==0\n" + "chr.SetDirection(1)\n" + // chr argument errors: Py_BuildException() clears and answers None; chrmgr raises. + "assert chr.HasInstance() is None and chr.SetRace('x') is None\n" + "for f,a in ((chrmgr.CreateRace,()),(chrmgr.SetDustGap,('x',)),(chrmgr.GetVIDInfo,()),(chr.WeaponTraceSetTexture,())," + "(chr.MoveToDestPosition,(1,2)),(chr.testSetRideMan,(1,))):\n" + " try:\n" + " f(*a)\n" + " raise AssertionError('no error: '+f.__name__)\n" + " except TypeError:\n" + " pass\n" + "assert (chr.RaceToJob(5),chr.RaceToSex(5),chr.RaceToSex(1),chr.RaceToSex(7))==(1,1,0,1)\n" + // RegisterInstance (no dict) and the selected-instance setters. + "chr.CreateInstance(10)\n" + "assert chr.HasInstance(10)==1 and chr.GetInstanceType(10)==6\n" + "chr.SelectInstance(10)\n" + "chr.SetRotation(90.0)\n" + "assert abs(chr.GetRotation()-90.0)<1e-3\n" + "chr.SetDirection(2)\n" + "assert abs(chr.GetRotation()-270.0)<1e-3\n" + "chr.SetDirection(9)\n" + "assert abs(chr.GetRotation()-360.0)<1e-3\n" + "chr.BlendRotation(30.0, 0.1)\n" + "assert abs(chr.GetRotation()-30.0)<1e-3\n" + "chr.SetRotationAll(1.0, 2.0, 200.0)\n" + "assert abs(chr.GetRotation()-160.0)<1e-3\n" + "chr.SetPixelPosition(100, 200, 30)\n" + "assert chr.GetPixelPosition(10)==(100.0,200.0,30.0)\n" + "chr.SetPixelPosition(150, 250)\n" + "assert chr.GetPixelPosition(10)==(150.0,250.0,0.0)\n" + "chr.SetNameString('Hero')\n" + "assert chr.GetName()=='Hero' and chr.GetNameByVID(10)=='Hero'\n" + "chr.SetRace(3)\n" + "assert chr.GetRace()==3\n" + "chr.SetInstanceType(2)\n" + "assert chr.IsStone(10)==1 and chr.GetInstanceType(10)==2\n" + "chr.SetInstanceType(1)\n" + "assert chr.IsNPC(10)==1\n" + "chr.SetInstanceType(0)\n" + "assert chr.IsEnemy(10)==1\n" + "assert chr.testGetPKData()[0]==0\n" + "chr.Hide()\n" + "assert chrmgr.GetVIDInfo(10)=='VID 10 (isRegistered=1, isAlive=1, isDead=0) pos=(150, 250)'\n" + "assert chrmgr.GetVIDInfo(99)=='VID 99 (isRegistered=0, isAlive=0, isDead=0) '\n" + // CreateInstance's dict path: "y" lands in m_lPosX like Windows. + "chr.CreateInstance(20, {'x':5, 'y':7, 'horse':0})\n" + "assert chr.HasInstance(20)==1 and chr.GetInstanceType(20)==6 and chr.GetVirtualNumber(20)==0\n" + "assert chr.GetPixelPosition(20)[0]==7.0 and chr.GetPixelPosition(20)[1]==0.0\n" + "assert chr.GetNameByVID(20)=='NONAME'\n" + "chr.CreateInstance(20, {'x':1})\n" + "assert chr.GetPixelPosition(20)[0]==7.0\n" + "assert chr.CreateInstance(30, 5) is None and chr.HasInstance(30)==0\n" + "chr.testSetRideMan(40, 50)\n" + "assert chr.HasInstance(1)==1 and chr.GetPixelPosition(1)[:2]==(40.0,50.0)\n" + "chr.testSetRideMan(60, 70)\n" + "assert chr.GetPixelPosition(1)[:2]==(40.0,50.0)\n" + "chr.DeleteInstance(20)\n" + "assert chr.HasInstance(20)==0\n" + // chrmgr race manager calls. + "chrmgr.SetPathName('c:/other/')\n" + "chrmgr.SetRaceHeight(7, 1.5)\n" + "chrmgr.ToggleDirectionLine()\n" + "assert chrmgr.IsPossibleEmoticon(-1) in (0,1)\n" + "chr.Update()\n" + "print 'chr script ok'\n"); + + const auto* hidden=mgr.GetActorData(10); + require(hidden && hidden->m_isHidden,"chr.Hide marks the selected instance hidden"); + require(RaceManager::Instance().GetFullPathFileName("a.msa")!="c:/other/a.msa","SetPathName ignores paths without d:/ymir"); + require(RaceManager::Instance().GetRaceHeight(7)==1.5f,"SetRaceHeight stores the race height"); + python.execute( + "chrmgr.SetPathName('d:/ymir work/pc/warrior/')\n" + "chr.SelectInstance(10)\n" + "chr.Show()\n"); + require(RaceManager::Instance().GetFullPathFileName("a.msa")=="d:/ymir work/pc/warrior/a.msa","SetPathName keeps d:/ymir paths"); + require(!mgr.GetActorData(10)->m_isHidden,"chr.Show clears the hidden flag"); + python.execute("chr.Destroy()\nassert chr.HasInstance(10)==0 and chr.HasInstance(1)==0\n"); + std::cout<<"AVA2 chr parity passed"< +#include +using namespace ava2; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +void u32(std::vector& p,uint32_t value) { for(unsigned i=0;i<4;++i)p.push_back(uint8_t(value>>(i*8))); } +std::vector recipe() { + std::vector p{221,2};u32(p,20016);u32(p,99);u32(p,0x80000001);u32(p,uint32_t(-5));p.push_back(1); + for(unsigned i=1;i<=5;++i) { u32(p,100+i);u32(p,uint32_t(-int(i))); } + u32(p,uint32_t(-70));u32(p,100);p.resize(167,0);const char category[]="Equipment"; + std::copy_n(category,9,p.begin()+67);return p; +} +void send(const std::vector& data) { + auto& s=PythonNetworkStream::Instance();s.PushRecvData(data);s.ProcessRecvData(); +} +std::vector control(uint8_t sub) { std::vector p(167);p[0]=221;p[1]=sub;return p; } +int main(int argc,char** argv) { + if(argc!=3)return 2; + try { + { + PythonRuntime python(argv[1],argv[2]);auto& s=PythonNetworkStream::Instance();s.ResetConnection();s.SetPhase(PHASE_GAME); + python.execute("import cube_renewal as cube, net, weakref, gc\nassert cube.CountDates()==0\nassert cube.GetDates() is None\nassert cube.GetDates(-1)==(0,)*15+('None',)\nassert cube.CubeRenewalMakeItem('x',1) is None\nassert cube.SetCubeRenewalHandler() is None\nclass Game:\n def __init__(self): self.opens=0\n def BINARY_CUBE_RENEWAL_OPEN(self): self.opens+=1\nclass Loader:\n def __init__(self): self.counts=[]\n def BINARY_CUBE_RENEWAL_LOADING(self): self.counts.append(cube.CountDates())\ngame=Game()\nloader=Loader()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,game)\ncube.SetCubeRenewalHandler(loader)\n"); + auto p=recipe();require(p.size()==167,"literal recipe size");p.push_back(44); + s.PushRecvData(p.data(),166);s.ProcessRecvData();python.execute("assert cube.CountDates()==0\n"); + s.PushRecvData(p.data()+166,2);s.ProcessRecvData();require(s.PopSendBytes()==std::vector{254},"recipe lost following ping"); + python.execute("expected=(-2147483647,-5,1,101,-1,102,-2,103,-3,104,-4,105,-5,-70,100,'Equipment')\nassert cube.GetDates(0)==expected\nassert cube.GetDates(0,'extra')==expected\nassert cube.GetDates(1)==(0,)*15+('None',)\n"); + send(recipe());send(control(3));send(control(0)); + python.execute("assert cube.CountDates()==2\nassert cube.GetDates(1)==expected\nassert loader.counts==[2]\nassert game.opens==1\n"); + // Unknown subheaders are consumed as a whole fixed packet without changing recipes. + send(control(255));send(control(1));send(control(3)); + python.execute("assert cube.CountDates()==0\nassert loader.counts==[2,0]\ncube.CubeRenewalMakeItem(2,3)\ncube.CubeRenewalClose()\n"); + require(s.PopSendBytes().empty(),"craft without main actor sent"); + SNetworkActorData actor{};actor.m_dwVID=1001;actor.m_dwRace=0;actor.m_stName="CubeFixture"; + NetworkActorManager::Instance().AppendActor(actor);s.SetMainActorVID(1001); + auto instance=NetworkActorManager::Instance().GetActorInstance(1001);require(bool(instance),"missing native actor"); + python.execute("cube.CubeRenewalMakeItem(-1,2147483649)\ncube.CubeRenewalClose()\n"); + auto bytes=s.PopSendBytes();std::vector expected{216,4,255,255,255,255,1,0,0,128,216,5,0,0,0,0,0,0,0,0}; + require(bytes==expected,"cube request Win32 byte conversion"); + instance->SetSleep(true);python.execute("cube.CubeRenewalMakeItem(1,2)\ncube.CubeRenewalClose()\n"); + require(s.PopSendBytes().empty(),"controlled actor allowed cube request");instance->SetSleep(false); + python.execute("temporary=Loader()\nref=weakref.ref(temporary)\ncube.SetCubeRenewalHandler(temporary)\ndel temporary\ngc.collect()\nassert ref() is not None\n"); + send(control(1));python.execute("assert ref() is not None\ncube.SetCubeRenewalHandler(None)\ngc.collect()\nassert ref() is None\n"); + send(recipe());s.ResetConnection();NetworkActorManager::Instance().Clear(); + } + { PythonRuntime python(argv[1],argv[2]);python.execute("import cube_renewal as cube\nassert cube.CountDates()==0\n"); } + std::cout<<"AVA2 cube renewal state, wire and Python parity passed\n"; + } catch(const std::exception& e) { std::cerr< +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void u32(Bytes& b,uint32_t value) {for(unsigned i=0;i<4;++i)b.push_back(uint8_t(value>>(8*i)));} +Bytes record(const std::string& name="Wolf") { + Bytes b{220,3};for(unsigned i=0;i<100;++i)b.push_back(iSetSleep(true);python.execute("drop.Open()\ndrop.SearchItem(0)\n");require(stream.PopSendBytes().empty(),"sleeping actor sent drop request");instance->SetSleep(false); + python.execute("temporary=Loader()\nref=weakref.ref(temporary)\ndrop.SetDropItemHandler(temporary)\ndel temporary\ngc.collect()\nassert ref() is not None\n"); + send(control(4));send(control(5));python.execute("assert ref() is not None and ref().events==[(0,1)]\ndrop.SetDropItemHandler(None)\ngc.collect()\nassert ref() is None\nclass Broken:\n def BINARY_DROP_ITEM_LOADING(self): raise ValueError('expected failure')\ndrop.SetDropItemHandler(Broken())\n"); + send(record());send(control(5));python.execute("assert drop.CountDates()==1\ndrop.SetPageSelect(99)\n"); + require(stream.GetUnportedPackets().empty(),"drop receive still uses skip handler");stream.ResetConnection(); + } + {PythonRuntime python(argv[1],argv[2]);python.execute("import drop_item as drop\nassert drop.CountDates()==0 and drop.GetPageActual()==1\n");} + std::cout<<"AVA2 drop item state, wire and Python parity passed\n"; + }catch(const std::exception& e){std::cerr< +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void u32(Bytes& b,uint32_t value) {for(unsigned i=0;i<4;++i)b.push_back(uint8_t(value>>(8*i)));} +void text(Bytes& b,const std::string& value,size_t width) {for(size_t i=0;i expected{{213,0,0,0,0,0},{213,1,255,255,255,255},{213,2,1,0,0,128},{213,9,3,0,0,0}}; + for(size_t i=0;i<4;++i)require(packets[i].first==expected[i] && packets[i].second,"dungeon Win32 bytes or sequence mismatch"); + instance->SetSleep(true);python.execute("dungeon.Open()\ndungeon.Teleport(1)\ndungeon.Mision(2)\ndungeon.Ranking(3)\n");require(stream.PopSendBytes().empty(),"sleeping actor sent dungeon request");instance->SetSleep(false); + python.execute("def broken(): raise ValueError('expected callback failure')\ngame.BINARY_TABLE_DUNGEON_INFO_OPEN=broken\n");send(control(3));send(record(4));python.execute("assert dungeon.CountDate()==2\n"); + require(stream.GetUnportedPackets().empty(),"dungeon still routed through skip handler");stream.ResetConnection(); + } + {PythonRuntime python(argv[1],argv[2]);python.execute("import dungeon_info as dungeon\nassert dungeon.CountDate()==0 and dungeon.CountDateRanking()==0 and dungeon.GetPageCount()==1\nassert dungeon.InfoDateMision(0)==(0,0,0,0)\n");} + std::cout<<"AVA2 dungeon info state, wire and Python parity passed\n"; + }catch(const std::exception& e){std::cerr< +#include +#include +using namespace ava2; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +std::vector literalLzo(const uint8_t* bytes,size_t size) { + std::vector out{uint8_t(17+size)}; + out.insert(out.end(),bytes,bytes+size);out.insert(out.end(),{17,0,0});return out; +} +void put32(std::vector& p,uint32_t n) { for(unsigned i=0;i<4;++i)p.push_back(uint8_t(n>>(i*8))); } +void loadMob(uint32_t vnum) { + ava2_windows_mob::TMobTable_r235 row{};row.dwVnum=vnum; + for(size_t i=0;i(int(i)-5); + auto packed=literalLzo(reinterpret_cast(&row),sizeof(row)); + std::vector p{'M','M','P','T'};put32(p,1);put32(p,uint32_t(20+packed.size())); + p.insert(p.end(),{'M','C','O','Z'});put32(p,0);put32(p,uint32_t(packed.size()));put32(p,sizeof(row));put32(p,0); + p.insert(p.end(),packed.begin(),packed.end()); + NonPlayerData::Instance().clear(); + require(NonPlayerData::Instance().load(std::string(p.begin(),p.end())),"mob fixture failed to load"); +} +int main(int argc,char** argv) { + if(argc!=3)return 2; + try { + // Parser: one LETTER per character, [CMD a;1|b;2] arguments, '\n' outside commands counted. + script::Group group; + require(group.Create("ab\n[QUESTION a;Yes|b;No]\n[DELAY value;0]")==2,"line count"); + script::TCmd cmd; + require(group.GetCmd(cmd) && cmd.name=="LETTER" && cmd.argList.front().strValue=="a","letter"); + require(group.GetCmd(cmd) && group.GetCmd(cmd) && cmd.name=="QUESTION" && cmd.argList.size()==2,"question"); + require(cmd.argList.front().strName=="a" && cmd.argList.back().strValue=="No","question args"); + require(group.ReadCmd(cmd) && cmd.name=="DELAY" && group.GetCmd(cmd) && !group.GetCmd(cmd),"peek/pop"); + require(group.Create("[UNCLOSED")==-1,"syntax error accepted"); + + PythonRuntime python(argv[1],argv[2]); + auto& stream=PythonNetworkStream::Instance();stream.ResetConnection();stream.SetPhase(PHASE_GAME); + auto& events=CPythonEventManager::Instance(); + python.execute( + "import event, net\n" + "assert (event.BUTTON_TYPE_NEXT,event.BUTTON_TYPE_DONE,event.BUTTON_TYPE_CANCEL)==(0,1,2)\n" + "assert event.BOX_VISIBLE_LINE_COUNT==14\n" + "assert not hasattr(event,'GetTotalLineCount')\n" + "class Handler:\n" + " def __init__(self):\n self.calls=[]\n" + " def MakeNextButton(self,t):\n self.calls.append(('next',t))\n" + " def DoneEvent(self):\n self.calls.append(('done',))\n" + " def MakeQuestion(self,n):\n self.calls.append(('question',n))\n" + " def AppendQuestion(self,s,i):\n self.calls.append(('answer',s,i))\n" + " def OnTitleImage(self,s):\n self.calls.append(('title',s))\n" + "h=Handler()\n" + "idx=event.RegisterEventSetFromString('Hi[ENTER]ab[NEXT][QUESTION a;Yes|b;No][TITLE_IMAGE src;t.tga][DONE][WAIT]x\\n')\n" + "assert idx==0\n" + "event.SetEventHandler(idx,h)\n" + "assert event.GetLineCount(idx)==0\n" + "event.AllProcessEventSet(idx)\n" + "assert h.calls==[('next',0),('question',2),('answer','Yes',0),('answer','No',1),('title','t.tga'),('next',1),('done',)],h.calls\n" + "assert event.IsWait(idx)\n" + "assert event.GetProcessedLineCount(idx)==1\n" + "assert event.GetLineCount(idx)==5\n" + "event.Skip(idx)\n" + "assert not event.IsWait(idx)\n" + "event.AllProcessEventSet(idx)\n" + "assert event.IsWait(idx)\n" + "event.SetVisibleStartLine(idx,2)\n" + "assert event.GetVisibleStartLine(idx)==0\n" + "event.SetVisibleStartLine(idx,1)\n" + "assert event.GetVisibleStartLine(idx)==1\n" + "assert event.RegisterEventSetFromString('[UNCLOSED')==-1\n" + "assert event.RegisterEventSetFromString('[RUN_CINEMA value;missing_cinema.txt]')==-1\n"); + const auto* set=events.GetEventSet(0); + require(set && set->strCurrentLine=="abx" && set->iTotalLineCount==1,"current line / total line count"); + // UpdateEventSet: the frame's elapsed time is taken off the delay twice (Windows quirk), then + // spent command by command at the [DELAY] pace. + python.execute("j=event.RegisterEventSetFromString('[DELAY value;100]abc')\nassert j==1\n"); + events.SetElapsedMillisecond(0); + python.execute("event.UpdateEventSet(j,0,0)\n"); + require(events.GetEventSet(1)->strCurrentLine.empty() && events.GetEventSet(1)->lLastDelayTime==0,"zero elapsed processed a command"); + events.SetElapsedMillisecond(15); + python.execute("event.UpdateEventSet(j,0,0)\n"); + require(events.GetEventSet(1)->lWaitingTime==100 && events.GetEventSet(1)->strCurrentLine.empty(),"DELAY command"); + python.execute("event.UpdateEventSet(j,0,0)\n"); + require(events.GetEventSet(1)->strCurrentLine=="a" && events.GetEventSet(1)->lLastDelayTime==85,"first letter"); + python.execute("event.UpdateEventSet(j,0,0)\n"); + require(events.GetEventSet(1)->strCurrentLine=="a" && events.GetEventSet(1)->lLastDelayTime==55,"double elapsed subtraction"); + events.SetElapsedMillisecond(1000); + python.execute("event.UpdateEventSet(j,0,0)\nevent.ClearEventSet(j)\n"); + require(!events.GetEventSet(1),"cleared slot"); + + // Answers and quest buttons reach the wire: CG_SCRIPT_ANSWER (29) / CG_SCRIPT_BUTTON (66). + stream.PopSendBytes(); + python.execute("event.SelectAnswer(idx,3)\nevent.SelectAnswer(99,4)\nevent.QuestButtonClick(0x01020304)\n"); + require(stream.PopSendBytes()==std::vector{29,3,66,4,3,2,1},"answer/button packets"); + + // AddEvent registers, sizes to 30 visible lines and opens the game phase quest window. + python.execute( + "class Game:\n def __init__(self):\n self.opened=[]\n def OpenQuestWindow(self,skin,index):\n self.opened.append((skin,index))\n" + "g=Game()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,g)\n" + "event.AddEvent('[ENTER]',7)\n" + "assert g.opened==[(7,1)],g.opened\n"); + require(events.GetEventSet(1)->iVisibleLineCount==30,"AddEvent visible line count"); + python.execute("event.Destroy()\nassert event.GetLineCount(idx)==0\n"); + + // initNonPlayer clears the table, so the fixture goes in after the first import. + python.execute("import item, player, app, nonplayer\n"); + loadMob(2001); + python.execute( + "assert item.GetApplyPoint(0)==0 and item.GetApplyPoint(1)==6\n" + "assert item.GetApplyPoint(177)==0\n" + "try:\n item.GetApplyPoint('x')\n raise AssertionError('bad apply type accepted')\nexcept TypeError:\n pass\n" + "assert player.SlotTypeToInvenType(1)==1 and player.SlotTypeToInvenType(11)==5\n" + "assert player.SlotTypeToInvenType(18)==12 and player.SlotTypeToInvenType(99)==0\n" + "for n in range(200):\n r=app.GetRandom(5,1)\n assert 1<=r<=5\n" + "assert app.GetRandom(3,3)==3\n" + "assert nonplayer.GetResist(2001,0)==-5 and nonplayer.GetResist(2001,10)==5\n" + "assert nonplayer.GetResist(2001,11)==0 and nonplayer.GetResist(2001,256)==-5\n" + "assert nonplayer.GetResist(9999,0)==0\n" + "assert player.GetGuildID()==0 and player.GetGuildName()=='' and player.GetPKMode()==0\n" + "assert player.IsGameMaster()==0 and player.GetEXP()==0 and player.GetConquerorEXP()==0\n" + "player.SetPlayTime(77)\nassert player.GetPlayTime()==77\n" + "assert player.SetPlayTime('x') is None and player.GetPlayTime()==77\n" + "assert player.GetJob()==player.GetRace()%4\n"); + NonPlayerData::Instance().clear();stream.ResetConnection(); + std::cout<<"AVA2 event manager and simple lookups parity passed\n"; + } catch(const std::exception& e) { std::cerr< &bytes, size_t off, uint32_t value) { bytes[off + 3] = uint8_t(value >> 24); } -std::vector granny_header(size_t size, uint32_t section_count) { +constexpr uint32_t kMagic32LE[] = { 0xCAB067B8, 0x0FB16DF8, 0x7E8C7284, 0x1E00195E }; +constexpr uint32_t kMagic64LE[] = { 0x5E499BE5, 0x141F636F, 0xA9EB131E, 0xC4EDBE90 }; +constexpr uint32_t kMagic32BE[] = { 0xB595110E, 0x4BB5A56A, 0x502828EB, 0x04B37825 }; + +std::vector granny_header(size_t size, uint32_t section_count, const uint32_t *magic = kMagic32LE) { std::vector bytes(size, 0); - const uint32_t magic[] = { 0xCAB067B8, 0x0FB16DF8, 0x7E8C7284, 0x1E00195E }; for (int i = 0; i < 4; ++i) { wr32(bytes, size_t(i) * 4, magic[i]); } @@ -47,14 +50,53 @@ int main() { bool ok = true; ok &= expect_failure(std::vector(80, 0), "header"); ok &= expect_failure(granny_header(80, 0), "fileinfo"); + // 64-bit little-endian Granny (AVA2 plechi_* assets) passes the header stage; + // big-endian is still rejected there. + ok &= expect_failure(granny_header(80, 0, kMagic64LE), "fileinfo"); + ok &= expect_failure(granny_header(80, 0, kMagic32BE), "header"); auto unsupported = granny_header(160, 1); constexpr size_t section = 72; - wr32(unsupported, section + 0, 4); // unsupported BitKnit + wr32(unsupported, section + 0, 3); // BitKnit v1 is not implemented wr32(unsupported, section + 4, uint32_t(unsupported.size())); wr32(unsupported, section + 12, 1); // non-empty expanded section ok &= expect_failure(unsupported, "section"); + // BitKnit2 (Format 4) with an empty stream: no 0x75B1 magic -> clean section failure. + auto bitknit_empty = unsupported; + wr32(bitknit_empty, section + 0, 4); + ok &= expect_failure(bitknit_empty, "section"); + + // BitKnit2 stored quantum: magic 0x75B1, u16 0 marker, 8 raw bytes. The section + // decodes, so loading proceeds to the (empty) type tree instead of failing in "section". + auto bitknit_stored = granny_header(160, 1); + const uint8_t stream[] = { 0xB1, 0x75, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + for (size_t i = 0; i < sizeof(stream); ++i) bitknit_stored[120 + i] = stream[i]; + wr32(bitknit_stored, section + 0, 4); + wr32(bitknit_stored, section + 4, 120); + wr32(bitknit_stored, section + 8, uint32_t(sizeof(stream))); + wr32(bitknit_stored, section + 12, 8); + { + gr2::LoadError err; + auto file = gr2::File::load(bitknit_stored.data(), bitknit_stored.size(), &err); + if (!file && err.stage == "section") { + std::fprintf(stderr, "BitKnit2 stored quantum rejected: %s\n", err.message.c_str()); + ok = false; + } + } + + // Truncated stored quantum (claims 8 bytes, carries 4) must fail cleanly. + auto bitknit_short = bitknit_stored; + wr32(bitknit_short, section + 8, 8); + ok &= expect_failure(bitknit_short, "section"); + + // BitKnit2 fixup table: u32 compressed size pointing past EOF -> clean "fixup" failure. + auto bitknit_fixup = bitknit_stored; + wr32(bitknit_fixup, section + 28, 150); // PointerFixupArrayOffset + wr32(bitknit_fixup, section + 32, 1); // PointerFixupArrayCount + wr32(bitknit_fixup, 150, 1000); + ok &= expect_failure(bitknit_fixup, "fixup"); + auto bad_offset = granny_header(160, 1); wr32(bad_offset, section + 4, UINT32_MAX); ok &= expect_failure(bad_offset, "section"); diff --git a/tests/guild_test.cpp b/tests/guild_test.cpp new file mode 100644 index 00000000..7d8a0517 --- /dev/null +++ b/tests/guild_test.cpp @@ -0,0 +1,131 @@ +#include "guild_state.h" +#include "python_runtime.h" +#include "python_net.h" +#include "python_gameplay_modules.h" +#include "eter_net/PythonNetworkStream.h" +#include +#include +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void u32(Bytes& b,uint32_t v) {for(int i=0;i<4;++i)b.push_back(uint8_t(v>>(8*i)));} +void u16(Bytes& b,uint16_t v) {b.push_back(uint8_t(v));b.push_back(uint8_t(v>>8));} +void str(Bytes& b,const std::string& value,size_t width) {for(size_t i=0;i>(8*i));}; + put(offsetof(TPacketGCCharacterUpdate,dwVID),123);put(offsetof(TPacketGCCharacterUpdate,dwGuildID),7); + net.PushRecvData(actorUpdate);net.ProcessRecvData(); + python.execute("assert net.GetGuildID()==7\nassert net.GetAccountCharacterSlotDataInteger(0,12)==7\nassert net.GetAccountCharacterSlotDataString(0,13)=='Seven'\n"); + send(5,pid(11)); + python.execute(R"PY(assert guild.IsGuildEnable()==0 and guild.GetGuildID()==0 and net.GetGuildID()==0 +assert net.GetAccountCharacterSlotDataInteger(0,12)==0 and net.GetAccountCharacterSlotDataString(0,13)=='' +assert guild.GetGuildBoardCommentCount()==1 and guild.GetGuildExperienceSummary()==800 +assert guild.GetSkillIndex(3)==7 +assert h.events==[('DeleteGuild',),('OnRemoveAllList',1),('RefreshTargetBoard',),('RefreshCharacter',),('RefreshMessenger',)] +guild.Destroy() +assert guild.GetSkillIndex(3)==0 +assert guild.GetGuildBoardCommentCount()==1 and guild.GetGuildExperienceSummary()==800 +h.events=[] +)PY"); + // Original ADD/unknown subheaders do not consume their payload. + send(4,{44});require(net.PopSendBytes()==Bytes{254},"unknown guild subheader handling changed"); + // Reject a truncated member record without reading into the next frame. + auto bad=frame(2,{1});bad.push_back(44);net.PushRecvData(bad);net.ProcessRecvData();require(net.PopSendBytes().empty(),"bad guild list consumed next frame"); + python.execute("assert guild.GetMemberCount()==0 and h.events==[]\n"); + auto& g=GetGuildState();for(uint32_t i=1;i<=7;++i)g.StartWar(i);require(g.enemies[5]==6,"six enemy slot cap changed");g.EndWar(2);g.StartWar(8);require(g.enemies[1]==8 && g.enemies[2]==3,"enemy slot reuse compacted list"); + net.ResetConnection(); + } + {PythonRuntime python(argv[1],argv[2]);python.execute("import guild\nassert guild.GetGuildBoardCommentCount()==0 and guild.GetGuildExperienceSummary()==0\nassert guild.GetMemberCount()==0\n");} + std::cout<<"AVA2 guild state, wire and Python parity passed\n"; + }catch(const std::exception& e){std::cerr< +#include +#include +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void u32(Bytes& b,uint32_t v) {for(unsigned i=0;i<4;++i)b.push_back(uint8_t(v>>(8*i)));} +void write(const std::filesystem::path& p,const Bytes& b) {std::filesystem::create_directories(p.parent_path());std::ofstream out(p,std::ios::binary);out.write(reinterpret_cast(b.data()),b.size());} +void textfile(const std::filesystem::path& p,const std::string& text) {write(p,Bytes(text.begin(),text.end()));} +Bytes row(uint32_t id,const std::string& internal,const std::string& name,uint8_t type=1,uint8_t size=3) { + Bytes b;u32(b,id);b.resize(172);std::copy(internal.begin(),internal.end(),b.begin()+4);std::copy(name.begin(),name.end(),b.begin()+29);b[54]=type;b[57]=size;b[131]=123;return b; +} +void proto(const std::filesystem::path& p,const std::vector& rows) { + Bytes raw;for(const auto& r:rows)raw.insert(raw.end(),r.begin(),r.end());Bytes compressed; + if(raw.size()<=238)compressed.push_back(uint8_t(17+raw.size())); + else {compressed.push_back(0);size_t n=raw.size()-18;while(n>255){compressed.push_back(0);n-=255;}compressed.push_back(n);} + compressed.insert(compressed.end(),raw.begin(),raw.end());compressed.insert(compressed.end(),{17,0,0}); + Bytes file{'M','I','P','X'};u32(file,1);u32(file,172);u32(file,rows.size());u32(file,20+compressed.size()); + file.insert(file.end(),{'M','C','O','Z'});u32(file,0);u32(file,compressed.size());u32(file,raw.size());file.insert(file.end(),{'M','C','O','Z'});file.insert(file.end(),compressed.begin(),compressed.end());write(p,file); +} +void tga(const std::filesystem::path& p) {Bytes b(18,0);b[2]=2;b[12]=64;b[14]=96;b[16]=24;b.resize(18+64*96*3,255);write(p,b);} +int main(int argc,char** argv) { + if(argc!=3)return 2; + auto root=std::filesystem::temp_directory_path()/std::filesystem::path("ava2-item-data-"+std::to_string(getpid()));std::filesystem::create_directories(root); + try { + { + PythonRuntime python(argv[1],root);python.execute("import item\n"); + python.execute(R"PY(for f in (item.GetItemName,item.GetItemDescription,item.GetItemSummary,item.GetItemSize,item.GetItemType,item.GetItemSubType,item.GetIconImage,item.GetIconImageFileName): + try: f() + except RuntimeError: pass + else: raise AssertionError('missing selected item must raise') +item.SelectItem(19) +assert item.SelectItemWiki(19)==0 +assert item.SelectItemWiki(27003)==0 +)PY"); + int type,sub;std::string name;require(!GetItemTypeAndSubType(19,&type,&sub)&&GetWeaponModelPathByVnum(19).empty(),"fabricated seeded weapon remains"); + textfile(root/"locale/en/item_names.txt","19\tFabricated Name\n");require(!GetItemNameAndType(19,&name,&type),"item_names lazy autoload remains"); + textfile(root/"list","500\tWEAPON\ticon/list.tga\tmodel/explicit.gr2\n600\tARMOR\ticon/missing.tga\n700\tUSE\ticon/list.tga\textra\tinvalid\n500\tIGNORED\ticon/list2.tga\n\t800\tunused\ticon/list.tga\t\n900\tunused\t\"icon/with space.tga\"\n"); + require(LoadItemList("list"),"item list fixture rejected");python.execute("item.SelectItem(500)\nassert item.GetItemName()=='' and item.GetItemType()==0 and item.GetItemSize()==(1,0), (item.GetItemName(),item.GetItemType(),item.GetItemSize())\nassert item.GetIconImageFileName()=='Noname'\nassert item.SelectItemWiki(700)==0 and item.SelectItemWiki(800)==1 and item.SelectItemWiki(900)==1\n"); + require(GetWeaponModelPathByVnum(500).empty(),"three-field list did not clear previous model"); + textfile(root/"desc","500\tignored name\t\"Description\"\t\"Summary\"\n600\tignored\t\"Unclosed\t\n777\tx\tShould not create\tx\n900\tignored\t\tSummary only\n");require(LoadItemDescriptions("desc"),"description fixture rejected"); + python.execute("item.SelectItem(500)\nassert item.GetItemDescription()=='Description' and item.GetItemSummary()=='Summary' and item.GetItemName()=='', (item.GetItemDescription(),item.GetItemSummary(),item.GetItemName())\nitem.SelectItem(600)\nassert item.GetItemDescription()=='Unclosed' and item.GetItemSummary()==''\nassert item.SelectItemWiki(777)==0\nitem.SelectItem(900)\nassert item.GetItemDescription()=='' and item.GetItemSummary()=='Summary only'\n"); + tga(root/"icon/list2.tga");tga(root/"icon/item/01002.tga");tga(root/"icon/item/02000.tga");tga(root/"icon/item/27995.tga"); + // Unsorted rows: same-name icon fallback follows original source order, not map order. + proto(root/"proto",{row(1002,"Same","First"),row(1001,"Same","Second"),row(2009,"Different","Base"),row(3333,"Missing","Bowl"),row(500,"List","Listed",2,2)}); + require(LoadItemTable("proto"),"prototype fixture rejected"); + python.execute("item.SelectItem(1001)\nassert item.GetItemName()=='Second' and item.GetIconImageFileName()=='icon/item/01002.tga', (item.GetItemName(),item.GetIconImageFileName())\nitem.SelectItem(2009)\nassert item.GetIconImageFileName()=='icon/item/02000.tga'\nitem.SelectItem(3333)\nassert item.GetIconImageFileName()=='icon/item/27995.tga'\nitem.SelectItem(500)\nassert item.GetItemType()==2 and item.GetItemSize()==(1,2) and item.GetIconImageFileName()=='icon/list2.tga'\nassert item.GetItemDescription()=='Description' and item.GetItemSummary()=='Summary'\nassert item.GetSocket(0)==123\nitem.GetIconImage()\nassert item.GetItemSize()==(1,2)\nitem.SelectItem(999999)\nassert item.GetItemName()=='Listed'\n"); + require(!LoadItemList("absent")&&!LoadItemDescriptions("absent")&&!LoadItemTable("absent"),"missing loader must fail");textfile(root/"bad","invalid proto");require(!LoadItemTable("bad"),"bad proto accepted");python.execute("assert item.GetItemName()=='Listed' and item.LoadItemTable('bad') is None\n"); + textfile(root/"list","500\tignored\ticon/list2.tga\tmodel/new.gr2\n");require(LoadItemList("list"),"reload list failed");require(GetWeaponModelPathByVnum(500)=="model/new.gr2","explicit model path ignored");python.execute("assert item.GetItemType()==2 and item.GetItemName()=='Listed' and item.GetSocket(0)==0 and item.GetItemDescription()==''\n"); + ResetItemDatabase();require(!GetItemTypeAndSubType(500,&type,&sub),"database reset retained records");python.execute("assert item.SelectItemWiki(500)==0\n"); + } + std::filesystem::remove_all(root);std::cout<<"AVA2 item resource loading and selected data parity passed\n"; + }catch(const std::exception& e){std::filesystem::remove_all(root);std::cerr< +#include +#include +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void u32(Bytes& b,uint32_t v) {for(unsigned i=0;i<4;++i)b.push_back(uint8_t(v>>(8*i)));} +void wav(const std::filesystem::path& path) { + Bytes b{'R','I','F','F'};u32(b,38);b.insert(b.end(),{'W','A','V','E','f','m','t',' '});u32(b,16); + b.insert(b.end(),{1,0,1,0});u32(b,8000);u32(b,16000);b.insert(b.end(),{2,0,16,0,'d','a','t','a'});u32(b,2);b.insert(b.end(),{0,0}); + std::ofstream out(path,std::ios::binary);out.write(reinterpret_cast(b.data()),b.size()); +} +void proto(const std::filesystem::path& path,uint32_t id,uint8_t type,uint8_t sub) { + // Independent172-byte AVA2 r152 record and literal LZO stream, no source assets. + Bytes raw;u32(raw,id);raw.resize(172);raw[4]='F';raw[29]='F';raw[54]=type;raw[55]=sub;raw[57]=1; + Bytes compressed{189};compressed.insert(compressed.end(),raw.begin(),raw.end());compressed.insert(compressed.end(),{17,0,0}); + Bytes payload{'M','C','O','Z'};payload.insert(payload.end(),compressed.begin(),compressed.end()); + Bytes file{'M','I','P','X'};u32(file,1);u32(file,172);u32(file,1);u32(file,uint32_t(16+payload.size())); + file.insert(file.end(),{'M','C','O','Z'});u32(file,0);u32(file,uint32_t(compressed.size()));u32(file,172);file.insert(file.end(),payload.begin(),payload.end()); + std::ofstream out(path,std::ios::binary);out.write(reinterpret_cast(file.data()),file.size()); +} +int main(int argc,char** argv) { + if(argc!=3)return 2; + auto root=std::filesystem::temp_directory_path()/std::filesystem::path("ava2-item-sound-"+std::to_string(getpid()));std::filesystem::create_directories(root); + try { + { + PythonRuntime python(argv[1],root); + python.execute("import item\nfor i in range(8): item.SetUseSoundFileName(i,'use'+str(i))\nfor i in range(5): item.SetDropSoundFileName(i,'drop'+str(i))\nitem.SetUseSoundFileName(-1,'bad')\nitem.SetDropSoundFileName(5,'bad')\nitem.SetUseSoundFileName(8,'bad')\n"); + uint32_t id=500000; + for(auto [type,sub,use,drop]:{ + std::tuple{1,0,3,2},std::tuple{1,1,3,2},std::tuple{1,2,4,3},std::tuple{1,3,3,2},std::tuple{1,4,3,2},std::tuple{1,5,3,2},std::tuple{1,6,1,0},std::tuple{1,7,3,2},std::tuple{1,8,3,2},std::tuple{1,9,1,0}, + std::tuple{2,0,2,1},std::tuple{2,1,1,0},std::tuple{2,2,1,0},std::tuple{2,3,1,0},std::tuple{2,4,1,0},std::tuple{2,5,5,4},std::tuple{2,6,5,4},std::tuple{2,7,1,0}, + std::tuple{3,0,-1,0},std::tuple{3,1,7,0},std::tuple{3,7,6,0},std::tuple{3,11,1,0},std::tuple{28,0,1,0},std::tuple{16,0,1,0}}) { + proto(root/"proto",id,type,sub);python.execute("item.LoadItemTable('proto')\nitem.SelectItem("+std::to_string(id)+")\n"); + python.execute("before=(item.GetItemType(),item.GetItemSubType())\n");auto selected=GetItemUseSound(id); + require(use<0?!selected:selected=="use"+std::to_string(use),"original use classification mismatch"); + require(GetItemDropSound(id)=="drop"+std::to_string(drop),"original drop classification mismatch"); + GetItemUseSound(500000);python.execute("assert (item.GetItemType(),item.GetItemSubType())==before\n");++id; + } + require(!GetItemUseSound(0xffffffff)&&!GetItemDropSound(0xffffffff),"missing item must stay silent"); + require(GetPotionSound()=="use6","potion uses sound enum rather than item USE_POTION subtype"); + python.execute("item.SetUseSoundFileName(6,'')\nitem.SetDropSoundFileName(0,'')\n");require(GetPotionSound().empty()&&GetItemDropSound(500006)=="","empty sound filenames retained"); + auto& sound=SoundManager::Instance();sound.Destroy();sound.SetSoundVolume(1); + auto& net=PythonNetworkStream::Instance();net.ResetConnection(); + TItemData data{};data.vnum=500002;SetPlayerItemData(1,0,data); + auto& box=CPythonSafeBox::Instance();box.OpenSafeBox(1);box.OpenMall(1);box.SetItemData(0,data);box.SetMallItemData(0,data); + for(unsigned op=0;op<4;++op) { + auto path=root/("drop"+std::to_string(op)+".wav");wav(path); + python.execute("item.SetDropSoundFileName(item.DROPSOUND_BOW,'"+path.string()+"')\n"); + if(op==0)net.SendSafeBoxCheckinPacket(1,0,0); + if(op==1)net.SendSafeBoxCheckoutPacket(0,1,0); + if(op==2)net.SendSafeBoxItemMovePacket(0,1,2); + if(op==3)net.SendMallCheckoutPacket(0,1,0); + require(sound.GetCachedSoundCount()==op+1,"storage sound did not reach playback manager"); + require(net.PopSendPackets().size()==1,"storage sound changed wire sending"); + } + net.SendSafeBoxCheckoutPacket(255,1,0);net.SendMallCheckoutPacket(255,1,0);require(sound.GetCachedSoundCount()==4,"invalid storage slot played audio");net.ClearSendQueue(); + auto path=root/"potion.wav";wav(path);python.execute("item.SetUseSoundFileName(item.USESOUND_POTION,'"+path.string()+"')\n"); + PlayItemUseSound(500018);require(sound.GetCachedSoundCount()==4,"potion played locally before server effect"); + PlayUsePotionSound();require(sound.GetCachedSoundCount()==5,"potion playback missing"); + python.execute("for method in (item.SetUseSoundFileName,item.SetDropSoundFileName):\n try: method('bad','x')\n except TypeError: pass\n else: raise AssertionError('expected original bad argument error')\n"); + // Inventory requests: sound follows the original action/equipment guards. + SNetworkActorData actor{};actor.m_dwVID=77;actor.m_dwRace=999999;NetworkActorManager::Instance().AppendActor(actor);net.SetMainActorVID(77); + SetPlayerItemData(1,180,data);SetPlayerItemData(1,215,data);SetPlayerItemData(1,216,data); + require(IsPlayerEquipmentItem(1,180)&&IsPlayerEquipmentItem(1,215)&&!IsPlayerEquipmentItem(1,216)&&!IsPlayerEquipmentItem(6,180),"original equipment cell bounds"); + python.execute("import net,shop\nclass Game:\n def __init__(self): self.events=[]\n def BINARY_AppendNotifyMessage(self,message): self.events.append(message)\ngame=Game()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,game)\nshop.Close()\n"); + auto inventoryPath=root/"inventory.wav";wav(inventoryPath);SetItemUseSound(USESOUND_BOW,inventoryPath.string());SetItemDropSound(DROPSOUND_BOW,inventoryPath.string()); + auto& trade=CPythonExchange::Instance();trade.Start(); + net.SendItemUsePacket(1,180);net.SendItemMovePacket(1,180,1,0,1); + require(net.PopSendPackets().empty()&&sound.GetCachedSoundCount()==5,"trading equip action must reject before sound/send"); + python.execute("assert game.events==['CANNOT_EQUIP_EXCHANGE']*2\ngame.events=[]\nshop.Open()\n"); + trade.End();net.SendItemUsePacket(1,180);net.SendItemMovePacket(1,180,1,0,1); + require(net.PopSendPackets().empty()&&sound.GetCachedSoundCount()==5,"shopping equip action must reject before sound/send"); + python.execute("assert game.events==['CANNOT_EQUIP_SHOP']*2\ngame.events=[]\n"); + // Source is an inventory cell: Windows does not apply the equip restriction to destination-only moves. + net.SendItemMovePacket(1,0,1,180,1);require(net.PopSendPackets().size()==1&&sound.GetCachedSoundCount()==6,"inventory-to-equipment move source guard mismatch"); + python.execute("assert game.events==[]\nshop.Close()\n"); + net.SendItemUsePacket(1,180);net.SendItemMovePacket(1,180,1,0,1);require(net.PopSendPackets().size()==2,"allowed equipment requests missing"); + auto blockedPath=root/"blocked.wav";wav(blockedPath);SetItemUseSound(USESOUND_BOW,blockedPath.string());SetItemDropSound(DROPSOUND_BOW,blockedPath.string()); + NetworkActorManager::Instance().GetActorInstance(77)->Stun();net.SendItemUsePacket(1,0);net.SendItemMovePacket(1,0,1,1,1); + require(net.PopSendPackets().empty()&&sound.GetCachedSoundCount()==6,"unable-to-act request must stay silent"); + sound.Destroy();net.ResetConnection(); + } + std::filesystem::remove_all(root);std::cout<<"AVA2 item sound selection and storage playback parity passed\n"; + }catch(const std::exception& e){std::filesystem::remove_all(root);std::cerr< +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void put(Bytes& b,uint64_t v,unsigned width=4) {for(unsigned i=0;i>(8*i)));} +void text(Bytes& b,const std::string& s,size_t width) {for(size_t i=0;i #include #include +#include "test_rundir.h" using namespace ava2; @@ -49,7 +50,7 @@ void TestGuildMarkImageAtlas() { // Load authentic 10_0.tga bool loaded = atlas.LoadTGA("mark/10_0.tga"); if (!loaded) loaded = atlas.LoadTGA("build/dev/mark/10_0.tga"); - if (!loaded) loaded = atlas.LoadTGA("/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/mark/10_0.tga"); + if (!loaded) loaded = atlas.LoadTGA(ava2_test::PackMaker() + "/../mark/10_0.tga"); assert(loaded && "Failed to load authentic 10_0.tga mark atlas"); // Check non-zero pixel in atlas @@ -161,6 +162,7 @@ void TestGuildMarkManager() { } int main() { + if (!ava2_test::EnterTestRunDir()) return ava2_test::kSkip; std::cout << "=== Running Guild Mark & MarkManager Engine Tests ===" << std::endl; TestGuildMarkPrimitives(); TestGuildMarkBlockCRC(); diff --git a/tests/messenger_test.cpp b/tests/messenger_test.cpp new file mode 100644 index 00000000..00bf060f --- /dev/null +++ b/tests/messenger_test.cpp @@ -0,0 +1,53 @@ +#include "messenger_state.h" +#include "python_runtime.h" +#include "eter_net/PythonNetworkStream.h" +#include +#include +using namespace ava2; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +std::vector frame(uint8_t sub,const std::vector& data) { + const auto size=uint16_t(4+data.size()); + std::vector result{74,uint8_t(size),uint8_t(size>>8),sub}; + result.insert(result.end(),data.begin(),data.end());return result; +} +void send(uint8_t sub,const std::vector& data) { + auto& stream=PythonNetworkStream::Instance();stream.PushRecvData(frame(sub,data));stream.ProcessRecvData(); +} +int main(int argc,char** argv) { + if(argc!=3)return 2; + try { + { + PythonRuntime python(argv[1],argv[2]); + auto& stream=PythonNetworkStream::Instance();stream.ResetConnection();stream.SetPhase(PHASE_GAME); + python.execute("import messenger,net,weakref,gc\nassert messenger.IsFriendByName('Alice')==0\nassert messenger.IsFriendByName() is None\nassert messenger.RemoveFriend(1) is None\nassert messenger.SetMessengerHandler() is None\nclass Handler:\n def __init__(self):\n self.events=[]\n def OnLogin(self,group,name):\n if group==0: assert messenger.IsFriendByName(name)==1\n self.events.append(('login',group,name))\n def OnLogout(self,group,name):\n if group==0: assert messenger.IsFriendByName(name)==1\n self.events.append(('logout',group,name))\n def OnMobile(self,group,name,state):\n assert messenger.IsFriendByName(name)==1\n self.events.append(('mobile',group,name,state))\n def RefreshTargetBoardByName(self,name):\n self.events.append(('target',name))\n def OnRemoveList(self,group,name):\n self.events.append(('remove',group,name))\n def OnRemoveAllList(self,group):\n self.events.append(('removeall',group))\nh=Handler()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,h)\nmessenger.SetMessengerHandler(h)\n"); + // connected bit0 is online, bit1 mobile; online/mobile list callback order. + auto list=frame(0,{3,5,'A','l','i','c','e',0,3,'B','o','b',2,3,'E','v','e'}); + list.push_back(44);stream.PushRecvData(list.data(),list.size()-2);stream.ProcessRecvData(); + python.execute("assert h.events==[]\nassert messenger.IsFriendByName('Alice')==0\n"); + stream.PushRecvData(list.data()+list.size()-2,2);stream.ProcessRecvData(); + require(stream.PopSendBytes()==std::vector{254},"messenger list lost following ping"); + python.execute("assert h.events==[('login',0,'Alice'),('mobile',0,'Alice',1),('logout',0,'Bob'),('logout',0,'Eve'),('mobile',0,'Eve',1)]\nassert messenger.IsFriendByName('Bob')==1\nassert messenger.IsFriendByName('alice')==0\nh.events=[]\n"); + send(1,{5,'C','a','r','o','l'});send(2,{5,'A','l','i','c','e'});send(4,{255,3,'B','o','b'}); + python.execute("assert h.events==[('login',0,'Carol'),('target','Carol'),('logout',0,'Alice'),('mobile',0,'Bob',255)]\nassert messenger.IsFriendByName('Alice')==1\nmessenger.RemoveFriend('Alice','ignored')\nassert messenger.IsFriendByName('Alice')==0\nh.events=[]\n"); + auto& state=GetMessengerState();state.AppendGuildMember("Zulu");state.AppendGuildMember("Zulu");state.LoginGuildMember("Alpha"); + python.execute("assert h.events==[('logout',1,'Zulu'),('login',1,'Alpha')]\nh.events=[]\nmessenger.RefreshGuildMember()\nassert h.events==[('login',1,'Alpha'),('logout',1,'Zulu')]\nh.events=[]\n"); + state.RemoveGuildMember("Missing");state.RemoveGuildMember("Alpha");state.RemoveAllGuildMember(); + python.execute("assert h.events==[('remove',1,'Missing'),('remove',1,'Alpha'),('removeall',1)]\nh.events=[]\nmessenger.Destroy()\nassert messenger.IsFriendByName('Bob')==0\nmessenger.RefreshGuildMember()\nassert h.events==[]\n"); + send(2,{3,'B','o','b'}); + python.execute("assert h.events==[('logout',0,'Bob')]\n"); + // The original ignores INVITE; its unconsumed byte still reaches the dispatcher. + send(3,{44});require(stream.PopSendBytes()==std::vector{254},"invite payload handling changed"); + // Malformed lengths cannot consume bytes from a coalesced next packet. + auto bad=frame(1,{24,'x'});bad.push_back(44);stream.PushRecvData(bad);stream.ProcessRecvData(); + require(stream.PopSendBytes().empty(),"malformed messenger name consumed next frame"); + python.execute("assert h.events==[('logout',0,'Bob')]\n"); + send(1,{25});send(0,{1}); + python.execute("assert h.events==[('logout',0,'Bob')]\nclass Broken:\n def OnLogin(self,*args):\n raise ValueError('expected callback failure')\nmessenger.SetMessengerHandler(Broken())\n"); + send(1,{1,'X'});python.execute("assert messenger.IsFriendByName('X')==1\n"); + python.execute("transient=Handler()\nref=weakref.ref(transient)\nmessenger.SetMessengerHandler(transient)\ndel transient\ngc.collect()\nassert ref() is not None\nmessenger.Destroy()\nassert ref() is not None\nmessenger.SetMessengerHandler(None)\ngc.collect()\nassert ref() is None\n"); + stream.ResetConnection(); + } + { PythonRuntime python(argv[1],argv[2]);python.execute("import messenger\nassert messenger.IsFriendByName('X')==0\nmessenger.RefreshGuildMember()\n"); } + std::cout<<"AVA2 messenger state, wire and Python parity passed\n"; + } catch(const std::exception& e) { std::cerr<_point.txt marks (case-sensitive types, start/end +// blocks), Update's mark classification and radius, observers, targets, GetInfo/GetAtlasInfo tuples, +// guild areas, way/signal points, the atlas window callbacks and the module surface. +#include "python_minimap.h" +#include "python_gameplay_modules.h" +#include "python_runtime.h" +#include "guild_state.h" +#include "eter_net/NetworkActorManager.h" +#include +#include +#include +#include +#include +#include +#include +#include +using namespace ava2; +namespace fs = std::filesystem; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +void spit(const fs::path& p,const std::string& s) { fs::create_directories(p.parent_path());std::ofstream f(p,std::ios::binary);f<>8);t[14]=char(h&0xff);t[15]=char(h>>8);t[16]=32;t[17]=8; + return t+std::string(size_t(w)*h*4,'\x7f'); +} +bool near(float a,float b) { return std::fabs(a-b)<1e-3f; } +uint32_t g_now=1000; +uint32_t now() { return g_now; } +SNetworkActorData actor(uint32_t vid,uint8_t type,uint32_t race,long x,long y,const char* name) { + SNetworkActorData a{};a.m_dwVID=vid;a.m_bType=type;a.m_dwRace=race;a.m_lCurX=x;a.m_lCurY=y;a.m_stName=name;return a; +} +int main(int argc,char** argv) { + if(argc!=3)return 2; + try { + const fs::path root=fs::temp_directory_path()/"ava2_minimap_test"; + fs::remove_all(root);fs::create_directories(root); + fs::current_path(root); + spit(root/"locale/en/atlasinfo.txt","testmap 409600 204800 2 3\n"); + spit(root/"map/testmap/setting.txt","ScriptType MapSetting\nMapSize 2 3\nBasePosition 409600 204800\n"); + spit(root/"map/testmap/001002/height.raw",std::string(2*131*131,'\0')); + spit(root/"testmap/atlas.tga",tga(256,384)); + spit(root/"testmap/atlas.sub","title subImage\nversion 2.0\nimage atlas.tga\nleft 0\ntop 0\nright 256\nbottom 384\n"); + spit(root/"ymir work/ui/minimap/whitemark_new.tga",tga(8,8)); + spit(root/"ymir work/ui/minimap/boss_mark_new.tga",tga(12,12)); + spit(root/"locale/en/map/testmap_point.txt", + "0 NPC 2560 5120 Guard\n1\tWARP\t25600\t51200\t\"Gate A\"\n2 MONSTER 1 1 Mob\n3 npc 1 1 lower\n4 NPC 1\n" + "start 5\nWARP 100 200 Blk\nend\n"); + + PythonRuntime python(argv[1],root); + auto& mm=CPythonMiniMap::Instance(); + mm.SetTimeSourceForTest(now); + + // Module surface: the 27 Windows functions, no RegisterColor; no map yet. + python.execute( + "import miniMap as m\n" + "names=('SetScale','ScaleUp','ScaleDown','SetMiniMapSize','SetCenterPosition','Destroy','Create','Update','Render'," + "'Show','Hide','isShow','GetInfo','LoadAtlas','UpdateAtlas','RenderAtlas','ShowAtlas','HideAtlas','isShowAtlas','IsAtlas'," + "'GetAtlasInfo','GetAtlasSize','AddWayPoint','RemoveWayPoint','RegisterAtlasWindow','UnregisterAtlasWindow','GetGuildAreaID')\n" + "assert sorted(n for n in dir(m) if not n.startswith('_') and not n.startswith('TYPE_'))==sorted(names)\n" + "assert (m.TYPE_OPC,m.TYPE_NPC,m.TYPE_WARP,m.TYPE_WAYPOINT,m.TYPE_PARTY,m.TYPE_EMPIRE)==(0,3,5,6,7,8)\n" + "assert m.GetAtlasSize()==(0,0,0) and m.IsAtlas()==0 and m.isShow()==0 and m.isShowAtlas()==0\n" + "assert m.LoadAtlas() is None and m.IsAtlas()==0\n" + "assert m.SetScale('x') is None\n" + "m.Create()\n"); + + // Main actor + the classification set around (40000,60000). + auto& actors=NetworkActorManager::Instance(); + actors.Clear(); + actors.AppendActor(actor(1,6,0,40000,60000,"Hero"));actors.SetMainActorVID(1); + actors.AppendActor(actor(2,6,0,42000,60000,"Other")); + actors.AppendActor(actor(3,6,0,40000,59000,"Mate")); + auto ghost=actor(4,6,0,40500,60500,"Ghost");ghost.m_affectFlags[0]=1u<size()==1 && v.partyPC->size()==1 && v.metin->size()==1 && v.offlineShop->size()==1,"pc/stone/shop"); + require(v.npc->size()==2 && v.monster->size()==1 && v.boss->size()==1 && v.warp->size()==1,"npc/monster/boss/warp"); + require(near((*v.otherPC)[0].m_fX,80.0f) && near((*v.otherPC)[0].m_fY,60.0f),"other pc mark"); + require((*v.partyPC)[0].m_eNameColor==NetworkActorManager::NAMECOLOR_PARTY && near((*v.partyPC)[0].m_fY,50.0f),"party mark"); + + // Observer: 1 s lerp towards the destination. + mm.AddObserver(50,40000,61000); + mm.MoveObserver(50,41000,61000); + g_now+=500; + mm.Update(40000,60000); + v=mm.GetTestView(); + require(v.observers==1 && v.partyPC->size()==2 && near((*v.partyPC)[1].m_fX,65.0f) && near((*v.partyPC)[1].m_fY,70.0f),"observer lerp"); + mm.RemoveObserver(50); + + // Targets: a location target clamps to the 55px window (+2), a VID target follows its actor. + mm.CreateTarget(900,"T"); + mm.UpdateTarget(900,409600+50000,204800+60000); + mm.UpdateTarget(900,409600-1,204800+60000); // below base: ignored + mm.UpdateTarget(900,-5,204800+60000); // unsigned: above base+max, ignored + mm.CreateTarget(901,"V",8); + mm.UpdateTarget(901,409600,204800); // actor exists: ignored + mm.Update(40000,60000); + float tx=0,ty=0; + require(mm.GetTargetMiniMapPosition(900,&tx,&ty) && near(tx,117.0f) && near(ty,62.0f),"location target"); + require(mm.GetTargetMiniMapPosition(901,&tx,&ty) && near(tx,60.0f) && near(ty,90.0f),"vid target"); + mm.DeleteTarget(900);mm.DeleteTarget(901); + require(!mm.GetTargetMiniMapPosition(900,&tx,&ty),"delete target"); + + // Atlas marks from HEADER_GC_NPC_POSITION: the warp name is cut at the first space. + mm.ClearAtlasMarkInfo(); + mm.RegisterAtlasMark(1,20000,"Guard",2560,5120,0); + mm.RegisterAtlasMark(3,0,"North Gate",10000,10000,0); + mm.RegisterAtlasMark(0,691,"Boss",30000,30000,120); + GetGuildState().names[77]="Clan"; + mm.RegisterGuildArea(1,77,1000,1000,2000,2000); + mm.RegisterGuildArea(2,78,20000,40000,1000,1000); + mm.AddSignalPoint(100,100); + require(mm.GetTestView().wayPoints==1,"signal waypoint"); + mm.ClearAllSignalPoint(); + require(mm.GetTestView().wayPoints==0,"signal cleared"); + + const auto& ma=*actors.GetActorData(1);(void)ma; + char script[4096]; + std::snprintf(script,sizeof(script), + "npc=%ld\nwarp=%ld\nwp=%ld\nparty=%ld\nother=%ld\nhero=%ld\n" + "class Atlas:\n def __init__(self):\n self.shown=0\n self.center=None\n" + " def Show(self):\n self.shown+=1\n def SetCenterPositionAdjust(self,x,y):\n self.center=(x,y)\n" + "a=Atlas()\nm.RegisterAtlasWindow(a)\n" + "assert m.GetAtlasSize()==(1,256,384) and m.IsAtlas()==1\n" + "m.ShowAtlas()\nm.UpdateAtlas()\nm.RenderAtlas(10,20)\nassert m.isShowAtlas()==1\n" + "assert m.GetAtlasInfo(22.8,45.6)==(1,'Guard',25,51,npc,0,0),m.GetAtlasInfo(22.8,45.6)\n" + "assert m.GetAtlasInfo(60,70)==(1,'North',100,100,warp,0,0),m.GetAtlasInfo(60,70)\n" + "assert m.GetAtlasInfo(160,170)==(1,'Boss',300,300,-1,0,120)\n" + "assert m.GetAtlasInfo(10+200,20+300)==(1,'Hero',400,600,hero,0,0)\n" + "assert m.GetAtlasInfo(20,30)==(1,'Clan',20,20,party,77,0),m.GetAtlasInfo(20,30)\n" + "assert m.GetAtlasInfo(10+102,20+202)==(1,'empty_guild_area',205,405,party,0,0)\n" + "assert m.GetAtlasInfo(250,400)==(0,'',0,0,0,0,0)\n" + "m.AddWayPoint(5,6000.0,6000.0,'wp')\nm.AddWayPoint(5,1.0,1.0,'dup')\n" + "assert m.GetAtlasInfo(40,50)==(1,'wp',60,60,wp,0,0)\n" + "m.RemoveWayPoint(5)\nassert m.GetAtlasInfo(40,50)==(0,'',0,0,0,0,0)\n" + "assert m.GetGuildAreaID(1500,1500)==77 and m.GetGuildAreaID(999,1500)==-1 and m.GetGuildAreaID(-1.0,0)==-1\n" + "m.LoadAtlas()\nassert a.shown==1\n" + "m.Show()\nassert m.isShow()==1\nm.Render(100,200)\n" + "assert m.GetInfo(164,264)==(1,'Hero',400,600,hero),m.GetInfo(164,264)\n" + "assert m.GetInfo(184,264)==(1,'Other',420,600,other),m.GetInfo(184,264)\n" + "assert m.GetInfo(100,200)==(0,'',0,0,0)\n" + "m.SetScale(9)\nm.ScaleDown()\nm.ScaleDown()\nm.ScaleDown()\nm.ScaleDown()\n" + "assert m.GetInfo(184,264)==(0,'',0,0,0)\n", + long(int32_t(NetworkActorManager::GetIndexedNameColor(NetworkActorManager::NAMECOLOR_NPC))), + long(int32_t(NetworkActorManager::GetIndexedNameColor(NetworkActorManager::NAMECOLOR_WARP))), + long(int32_t(NetworkActorManager::GetIndexedNameColor(NetworkActorManager::NAMECOLOR_WAYPOINT))), + long(int32_t(NetworkActorManager::GetIndexedNameColor(NetworkActorManager::NAMECOLOR_PARTY))), + long(int32_t(NetworkActorManager::GetIndexedNameColor(actors.GetNameColorIndex(2)))), + long(int32_t(NetworkActorManager::GetIndexedNameColor(actors.GetNameColorIndex(1))))); + python.execute(script); + v=mm.GetTestView(); + require(v.scale==0.5f && v.radius==16.0f,"scale clamp"); + mm.SetAtlasCenterPosition(3,4); + python.execute("assert a.center==(3,4)\nm.UnregisterAtlasWindow()\nm.Destroy()\n" + "assert m.isShow()==0 and m.IsAtlas()==0 and m.GetAtlasSize()==(1,0,0)\n"); + // LoadAtlas cleared the guild areas; Destroy keeps the atlas mark vectors, as on Windows. + v=mm.GetTestView(); + require(v.guildAreas==0 && v.npcMarks==1 && v.wayPoints==0 && v.scale==2.0f,"destroy"); + + actors.Clear(); + NetworkActorManager::SetPartyMemberQuery(nullptr); + fs::current_path(fs::temp_directory_path()); + fs::remove_all(root); + std::cout<<"AVA2 miniMap parity passed\n"; + } catch(const std::exception& e) { std::cerr< +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void put(Bytes& b,uint64_t v,unsigned width=4) {for(unsigned i=0;i>(8*i)));} +void text(Bytes& b,const std::string& s,size_t width) {for(size_t i=0;i +#include +#include #include "skill_description.h" #include "python_runtime.h" #include "nonplayer_data.h" +#include "python_wiki.h" #include "python_app.h" +#include "pet_skill_state.h" #include "python_gameplay_modules.h" #include "python_native_modules.h" #include "python_net.h" +#include "python_chat.h" #include "eter_net/PythonNetworkStream.h" #include "eter_net/NetworkActorManager.h" #include "eter_net/PythonSafeBox.h" +#include "eter_render/ActorInstance.h" +#include "eter_resource/ResourceManager.h" +#include "eter_render/RaceData.h" #include #include +#include #include +#include "test_rundir.h" int main(int argc,char** argv) { if(argc!=3) return 2; + if(!ava2_test::EnterTestRunDir()) return ava2_test::kSkip; try { ava2::SkillDescriptions fixture; if(!fixture.load("900\tWARRIOR\tBase\t\t\tDescription\tFirst\t\tThird\tIgnored fourth\tTOGGLE|STANDING_SKILL|USE_HP\t\ticon\r\n")) throw std::runtime_error("fixture load failed"); @@ -61,7 +72,43 @@ int main(int argc,char** argv) { if(!items.load(ava2::ReadPackedText("locale/en/item_proto")))throw std::runtime_error("original item proto rejected"); auto sword=items.records.find(10); if(sword==items.records.end()||sword->second.name!="Sword+0"||sword->second.type!=1||sword->second.size!=2)throw std::runtime_error("original item proto fields mismatch"); - python.execute("import item, app\nitem.LoadItemTable('locale/en/item_proto')\n"); + python.execute("import item, app\n"); + // app.LoadLocaleData: original order item_list -> item_proto -> ... -> mob_scale -> item_scale. + python.execute("import net\nassert app.LoadLocaleData('locale/en')==1\nassert net.IsInsultIn('you SHIT')==1 and net.IsInsultIn('hello')==0\nassert net.IsChatInsultIn('shit')==1\nnet.EnableChatInsultFilter(1)\nassert net.IsChatInsultIn('shit')==0\nnet.EnableChatInsultFilter(0)\n"); + { + auto& pets=ava2::GetPetSkillState().records; + if(pets.size()!=18||pets.at(17).delay!=600||pets.at(17).icon!="d:/ymir work/ui/skill/pet/invincibility.sub"||pets.at(1).type!=ava2::SKILLPET_TYPE_PASSIVE)throw std::runtime_error("LoadLocaleData pet_skill mismatch"); + auto* scale=ava2::NonPlayerData::Instance().getMobScale(8061); + if(!scale||std::fabs(scale->x-1.3f)>1e-6f)throw std::runtime_error("LoadLocaleData mob_scale mismatch"); + ava2::ItemScaleInfo sash; // 85001 JOB_ASSASSIN M 69 68 88 0 0 0.52 -> tInfo[2] for vnum 85001..85005 + if(!ava2::GetItemScale(85005,2,&sash)||std::fabs(sash.scaleX-0.69f)>1e-6f||std::fabs(sash.positionZ-52.0f)>1e-4f)throw std::runtime_error("LoadLocaleData item_scale mismatch"); + char chat[]="Bob : you shit head";auto& stream=ava2::PythonNetworkStream::Instance(); + stream.FilterInsult(chat+6,std::strlen(chat+6)); + if(std::string(chat)!="Bob : you **** head")throw std::runtime_error(std::string("insult filter mismatch: ")+chat); + if(ava2::LoadLocaleData("locale/missing")||!ava2::GetPetSkillState().records.empty())throw std::runtime_error("missing locale must fail after Destroy()"); + if(!ava2::LoadLocaleData("locale/en"))throw std::runtime_error("locale reload failed"); + } + { + // CPythonWiki::ReadData (ENABLE_WIKI): locale/common text tables fed from memory, item_proto/mob_proto from locale/en. + using ava2::WikiTextFile; + if(!ava2::WikiLoadText(WikiTextFile::RefineTable,"refine_table.txt","#id\tv0\n7\t27001\t2\t0\t0\t27002\t1\t0\t0\t0\t0\t1500\t0\t0\t90\r\n8\t1\t2\n")|| + !ava2::WikiLoadText(WikiTextFile::SpecialItemGroup,"special_item_group.txt","Group\tA\n{\n\tVnum\t77900\n\t1\t55101\t1\t30\n\t2\t55108\t1\t30\n}\nGroup\tB\n{\n\tVnum\t77900\n\t1\t1\t1\t1\n}\n")|| + !ava2::WikiLoadText(WikiTextFile::MobDropItem,"mob_drop_item.txt","Group\tBOSS\n{\n\tMob\t191\n\tType\tdrop\n\t1\t30037\t1\t100\n\t2\t76023\t10\t100\n}\n")) + throw std::runtime_error("wiki text tables failed to load"); + python.execute("import wiki\n" + "assert wiki.GetRefineItems(7)==(7,27001,2,0,0,27002,1,0,0,0,0,1500,90,3)\nassert wiki.GetRefineItems(8)==0\n" + "assert wiki.GetSpecialInfoSize(77900)==2 and wiki.GetSpecialInfoData(77900,1)==(55108,1)\n" + "assert wiki.GetMobInfoSize(191)==2 and wiki.GetMobInfoData(191,1)==(76023,10) and wiki.GetMobInfoData(192,0)==(0,0)\n" + "assert wiki.GetItemDropFromMonster(30037,False)==[191] and wiki.GetItemDropFromMonster(30046,True)==[191] and wiki.GetItemDropFromMonster(30047,True)==[]\n" + "assert wiki.GetItemDropFromChest(55108,0)==[77900]\n" + "assert wiki.IsBlackList(529,0,0)==1 and wiki.IsBlackList(10,0,529)==0\n" + "assert wiki.GetBossSize(3)==2 and wiki.GetBossData(3,1)==2493\n" + "assert wiki.GetCostumeSize(0)==53 and wiki.GetCostumeData(4,0)==65000 and wiki.GetCostumeSize(9)==0\n" + "assert wiki.GetRefineMaxLevel(10)==9\n" + "assert wiki.GetCategorySize(0,0)>0 and wiki.GetCategorySize(4,0)==0\n" + "item.SelectItem(wiki.GetCategoryData(0,0,0))\nassert item.GetItemType()==1 and '+9' in item.GetItemName()\n" + "assert wiki.GetStoneSize(0)>0 and 8001<=wiki.GetStoneData(0,0)<=8056\n"); + } python.execute("import shop\nassert shop.IsOpen()==0\nassert shop.GetTabCount()==1\nshop.Open()\nassert shop.IsOpen()==1\nshop.Close()\nassert shop.IsOpen()==0\nshop.Open()\nshop.Clear()\nassert shop.IsOpen()==0\nassert shop.GetTabCount()==1\n"); if(!ava2::SetShopTabCount(3)||ava2::SetShopTabCount(4))throw std::runtime_error("shop tab capacity validation failed"); ava2::SetShopTab(0,"Weapons",0);ava2::SetShopTab(2,"Special",257); @@ -274,10 +321,11 @@ int main(int argc,char** argv) { if(items.load("MIPX")||items.records.size()!=countBefore)throw std::runtime_error("truncated item proto damaged records"); auto originalWorkingDir=std::filesystem::current_path(); std::filesystem::current_path(std::filesystem::temp_directory_path()); - python.execute("import item\nitem.SelectItem(10)\nassert item.GetItemName() == 'Sword+0'\nassert item.GetIconImageFileName() == 'icon/item/00010.tga'\nitem.LoadItemTable('locale/en/item_proto')\nassert item.GetItemName() == 'Sword+0'\nassert item.GetItemType() == 1\n"); + // This fixture mount has proto/text but no icon assets. Windows returns Noname rather than a declared path. + python.execute("import item\nitem.SelectItem(10)\nassert item.GetItemName() == 'Sword+0'\nassert item.GetIconImageFileName() == 'Noname', item.GetIconImageFileName()\nitem.LoadItemTable('locale/en/item_proto')\nassert item.GetItemName() == 'Sword+0'\nassert item.GetItemType() == 1\n"); std::filesystem::current_path(originalWorkingDir); - if(!ava2::LoadSkillDescriptions("locale/en/SkillDesc.txt")) throw std::runtime_error("skill description load failed"); - if(!ava2::LoadSkillTable("locale/en/SkillTable.txt")) throw std::runtime_error("skill table file load failed"); + // SkillDesc/SkillTable were registered by app.LoadLocaleData above; registering again would + // append duplicate affect rows exactly like CPythonSkill::RegisterSkillDesc without Destroy(). ava2::SetPlayerStatusPoint(12,20);ava2::SetPlayerStatusPoint(204,80); if(std::fabs(ava2::EvaluateSkillFormula("str+ar*100+k",0.5f)-100.5f)>0.0001f || ava2::EvaluateSkillFormula("JeungJiFoo+k",0.5f)!=0.5f || ava2::EvaluateSkillFormula("UnknownState+k",0.5f)!=0)throw std::runtime_error("formula status binding mismatch " + std::to_string(ava2::EvaluateSkillFormula("str+ar*100+k",0.5f))+" / "+std::to_string(ava2::EvaluateSkillFormula("JeungJiFoo+k",0.5f))+" / "+std::to_string(ava2::EvaluateSkillFormula("1+",0.5f))); ava2::SetPlayerStatusPoint(12,0);ava2::SetPlayerStatusPoint(204,0); @@ -437,6 +485,7 @@ int main(int argc,char** argv) { "assert chr.HasInstance(101) == 1\n" "chr.SelectInstance(101)\n" "chr.SetRace(0)\n" + "chr.SetArmor(0)\n" "assert chr.GetRace() == 0\n" "chr.SetWeapon(11299)\n" "chr.SetHair(1)\n" @@ -486,7 +535,7 @@ int main(int argc,char** argv) { "chr.SetNameString('DogMaster')\n" "assert chr.GetName() == 'DogMaster'\n" "assert chr.GetNameByVID(201) == 'DogMaster'\n" - "pos = chr.GetPixelPosition()\n" + "pos = chr.GetPixelPosition(201)\n" "assert pos[0] == 500.0 and pos[1] == 600.0\n" "textTail.RegisterItemTextTail(555, 'Full Moon Sword +9', 120, 'TestHero')\n" "textTail.ShowAllTextTail()\n" @@ -546,21 +595,20 @@ int main(int argc,char** argv) { "net.SendGiveItemPacket(1001, 0, 1)\n" "print 'Testing Quest Dialog System (uiquest & event)...'\n" "import event\n" - "assert event.BUTTON_TYPE_CANCEL == 0\n" + "assert event.BUTTON_TYPE_NEXT == 0\n" "assert event.BUTTON_TYPE_DONE == 1\n" - "assert event.BUTTON_TYPE_NEXT == 2\n" - "event.RegisterEventSet(1)\n" - "event.InsertText(1, 'Welcome Adventurer!')\n" - "event.InsertTextInline(1, ' Accept quest:')\n" - "assert event.GetLineCount(1) >= 1\n" - "assert event.GetLineHeight(1) >= 10\n" - "assert event.GetEventSetLocalYPosition(1) >= 10\n" - "event.SelectAnswer(1, 254)\n" - "event.ClearEventSet(1)\n" + "assert event.BUTTON_TYPE_CANCEL == 2\n" + "evt = event.RegisterEventSetFromString('[ENTER]')\n" + "event.InsertText(evt, 'Welcome Adventurer!')\n" + "event.InsertTextInline(evt, ' Accept quest:', 40)\n" + "assert event.GetLineCount(evt) == 2\n" + "assert event.GetEventSetLocalYPosition(evt) >= 10\n" + "event.SelectAnswer(evt, 254)\n" + "event.ClearEventSet(evt)\n" "import uiquest\n" - "event.RegisterEventSet(2)\n" - "event.InsertText(2, 'Quest: Clear Wild Boars')\n" - "questDlg = uiquest.QuestDialog(1, 2)\n" + "evt = event.RegisterEventSetFromString('[ENTER]')\n" + "event.InsertText(evt, 'Quest: Clear Wild Boars')\n" + "questDlg = uiquest.QuestDialog(1, evt)\n" "questDlg.MakeNextButton(event.BUTTON_TYPE_NEXT)\n" "questDlg.MakeQuestion(3)\n" "questDlg.OnUpdate()\n" @@ -819,31 +867,405 @@ int main(int argc,char** argv) { if(netStream.SendSafeBoxMoneyPacket(0,100) || !netStream.GetSendQueue().empty()) throw std::runtime_error("disabled AVA2 storage money emitted party packet"); netStream.SetPhase(ava2::PHASE_GAME); - // Test Chat packet reception - bool chatCallbackFired = false; - netStream.SetChatCallback([&](uint8_t type, const std::string& text, uint32_t vid) { - (void)type; - (void)vid; - chatCallbackFired = true; - if (text != "Server: Welcome to AVA2!") { - throw std::runtime_error("Chat text content mismatch: " + text); - } - }); - std::string chatMsg = "Server: Welcome to AVA2!"; - std::vector chatBuf(sizeof(ava2::TPacketGCChat) + chatMsg.size()); - auto* chatPkt = reinterpret_cast(chatBuf.data()); - chatPkt->header = ava2::HEADER_GC_CHAT; - chatPkt->size = static_cast(chatBuf.size()); - chatPkt->type = ava2::CHAT_TYPE_NOTICE; - chatPkt->dwVID = 0; - chatPkt->bEmpire = 1; - std::memcpy(chatBuf.data() + sizeof(ava2::TPacketGCChat), chatMsg.data(), chatMsg.size()); - netStream.PushRecvData(chatBuf.data(), chatBuf.size()); - netStream.ProcessRecvData(); - if (!chatCallbackFired) { - throw std::runtime_error("Chat callback did not fire upon receiving TPacketGCChat!"); + // AVA2 Windows golden layouts for the net.Send* wrappers that used to be placeholders. + { + using bytes_t=std::vector; + auto le32=[](bytes_t b,uint32_t v){ for(int i=0;i<32;i+=8) b.push_back(uint8_t(v>>i)); return b; }; + auto text=[](bytes_t b,const std::string& value,size_t field){ size_t start=b.size();b.resize(start+field,0);std::copy(value.begin(),value.end(),b.begin()+start);return b; }; + auto expect=[&](const char* call,const bytes_t& expected,const char* what){ + netStream.ClearSendQueue();python.execute(std::string(call)+"\n"); + if(netStream.PopSendBytes()!=expected) throw std::runtime_error(std::string("AVA2 Windows layout mismatch: ")+what); + }; + // Exchange: TPacketCGExchange {header, sub, long long arg1, BYTE arg2, TItemPos(ctor {INVENTORY,WORD_MAX})} + expect("net.SendExchangeStartPacket(0x01020304)",{27,0,4,3,2,1,0,0,0,0,0,1,255,255},"exchange start"); + expect("net.SendExchangeElkAddPacket(0x123456789)",{27,3,0x89,0x67,0x45,0x23,1,0,0,0,0,1,255,255},"exchange elk (long long)"); + expect("net.SendExchangeItemAddPacket(1,0x1234,300)",{27,1,0,0,0,0,0,0,0,0,44,1,0x34,0x12},"exchange item add"); + expect("net.SendExchangeItemDelPacket(3)",{},"exchange item del must be a Windows no-op"); + expect("net.SendExchangeAcceptPacket()",{27,4,0,0,0,0,0,0,0,0,0,1,255,255},"exchange accept"); + expect("net.SendExchangeExitPacket()",{27,5,0,0,0,0,0,0,0,0,0,1,255,255},"exchange cancel"); + // Safebox / mall + expect("net.SendSafeboxCheckinPacket(7,3)",{70,3,1,7,0},"safebox checkin (2 args)"); + expect("net.SendSafeboxCheckinPacket(6,0x0102,3)",{70,3,6,2,1},"safebox checkin (3 args)"); + expect("net.SendSafeboxCheckoutPacket(4,9)",{71,4,1,9,0},"safebox checkout (2 args)"); + expect("net.SendSafeboxItemMovePacket(5,6,70000)",{77,1,5,0,1,6,0,0x70,0x11,1,0},"safebox move = TPacketCGItemMove"); + expect("net.SendMallCheckoutPacket(2,1,8)",{69,2,1,8,0},"mall checkout"); + expect("net.SendMallCheckoutPacket(2)",{},"mall checkout bad arity"); + expect("net.SendSafeboxSaveMoneyPacket(100)\nnet.SendSafeboxWithdrawMoneyPacket(100)",{},"disabled safebox money"); + // Messenger + expect("net.SendMessengerAddByVIDPacket(0x0a0b0c0d)",le32({67,0},0x0a0b0c0d),"messenger add by vid"); + expect("net.SendMessengerAddByNamePacket('A'*30)",text({67,1},std::string(23,'A'),24),"messenger add by name"); + python.execute("class BoardCallbacks:\n def __init__(self):\n self.names=[]\n def RefreshTargetBoardByName(self,name):\n self.names.append(name)\nboard_callbacks=BoardCallbacks()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,board_callbacks)\n"); + expect("net.SendMessengerRemovePacket('Key','Friend')",text({67,2},"Key",24),"messenger remove"); + python.execute("assert board_callbacks.names==['Friend']\nnet.ClearPhaseWindow(net.PHASE_WINDOW_GAME,board_callbacks)\n"); + // Party + expect("net.SendPartyInvitePacket(77)",le32({72},77),"party invite"); + auto answer=le32({73},88);answer.push_back(1); + expect("net.SendPartyInviteAnswerPacket(88,1)",answer,"party invite answer"); + expect("net.SendPartyRemovePacket(99)",le32({74},99),"party remove (PID alias)"); + expect("net.SendPartyRemovePacketVID(54321)\nnet.SendPartyExitPacket()",{},"party VID lookups without party state"); + auto state=le32({75},5);state.push_back(2);state.push_back(1); + expect("net.SendPartySetStatePacket(5,2,1)",state,"party set state"); + expect("net.SendPartyUseSkillPacket(3,6)",le32({76,3},6),"party use skill"); + expect("net.SendPartyParameterPacket(1)",{78,1},"party parameter"); + netStream.SetPhase(ava2::PHASE_SELECT); + expect("net.SendPartyRemovePacketPID(99)",{},"party remove outside Game"); + netStream.SetPhase(ava2::PHASE_GAME); + // Guild + expect("net.SendGuildAddMemberPacket(11)",le32({80,0},11),"guild add member"); + expect("net.SendGuildRemoveMemberPacket('Nobody')",{},"guild remove without member list"); + expect("net.SendGuildChangeGradeNamePacket(2,'Captain12345')",text({80,2,2},"Captain1",9),"guild grade name"); + expect("net.SendGuildChangeGradeAuthorityPacket(2,7)",{80,3,2,7},"guild grade authority"); + expect("net.SendGuildOfferPacket(1000)",le32({80,4},1000),"guild offer"); + expect("net.SendGuildPostCommentPacket('hi')",{80,5,3,'h','i',0},"guild post comment"); + expect("net.SendGuildDeleteCommentPacket(4)",le32({80,6},4),"guild delete comment"); + netStream.ResetGuildCommentRefreshThrottle(); + expect("net.SendGuildRefreshCommentsPacket(0)\nnet.SendGuildRefreshCommentsPacket(0)",{80,7},"guild refresh 1000 ms throttle"); + auto grade=le32({80,8},12);grade.push_back(3); + expect("net.SendGuildChangeMemberGradePacket(12,3)",grade,"guild member grade"); + expect("net.SendGuildUseSkillPacket(151,54321)",le32(le32({80,9},151),54321),"guild use skill"); + auto general=le32({80,10},12);general.push_back(1); + expect("net.SendGuildChangeMemberGeneralPacket(12,1)",general,"guild member general"); + auto invite=le32({80,11},5);invite.push_back(1); + expect("net.SendGuildInviteAnswerPacket(5,1)",invite,"guild invite answer"); + expect("net.SendGuildChargeGSPPacket(10)",le32({80,12},10),"guild charge gsp"); + expect("net.SendGuildDepositMoneyPacket(20)",le32({80,13},20),"guild deposit"); + expect("net.SendGuildWithdrawMoneyPacket(30)",le32({80,14},30),"guild withdraw"); + // Quest / script + expect("net.SendAnswerMakeGuildPacket('GuildNameIsTooLong')",text({81},"GuildNameIsT",13),"answer make guild"); + expect("net.SendQuestInputStringPacket('abc')",text({30},"abc",65),"quest input string"); + expect("net.SendQuestInputLongStringPacket('abc')",text({214},"abc",512),"quest input long string"); + expect("net.SendQuestConfirmPacket(1,0x01020304)",{31,1,4,3,2,1},"quest confirm"); + expect("net.SendSelectItemPacket(9)",le32({114},9),"script select item"); + expect("net.SendTargetInfoLoad(54321)",le32({59},54321),"target info load"); + expect("net.SendRequestRefineInfoPacket(1)",{},"refine info is a Windows no-op"); + expect("net.SendExchangeStartPacket('x')",{},"ScriptLib argument failure returns None"); + // __CanActMainInstance gate on exchange + netStream.SetMainActorVID(999); + expect("net.SendExchangeStartPacket(1)\nnet.SendExchangeAcceptPacket()",{},"exchange without an acting main actor"); + netStream.SetMainActorVID(54321); } + + // Chat / whisper / ServerCommand follow Windows RecvChatPacket, RecvWhisperPacket and + // PythonNetworkStreamCommand.cpp (ENABLE_MULTILANGUAGE_SYSTEM branch). + netStream.ResetConnection();netStream.SetPhase(ava2::PHASE_GAME); + // RecvChatPacket appends into CPythonChat; set 0 (CHAT_SET_CHAT_WINDOW) holds every line. + ava2::CPythonChat::Instance().Destroy(); + auto appendedLines=[]() { + std::vector out; + if(const auto* lines=ava2::CPythonChat::Instance().GetChatLineDeque(0)) + for(const auto* line:*lines) out.push_back(std::to_string(line->iType)+":"+line->text); + return out; + }; + python.execute( + "class ChatWnd:\n" + " def __init__(self):\n self.calls=[]\n self.run=False\n" + " def GetLocaleString(self,t,s):\n self.calls.append(('locale',t,s))\n" + " def BINARY_ServerCommand_Run(self,s):\n self.calls.append(('run',s))\n return self.run\n" + " def BINARY_Cube_Open(self,v):\n self.calls.append(('cube',v))\n" + " def BINARY_Cube_UpdateInfo(self,g,v,c):\n self.calls.append(('cubeinfo',g,v,c))\n" + " def OnMessengerAddFriendQuestion(self,n):\n self.calls.append(('friend',n))\n" + " def OnRecvWhisper(self,t,n,l,lang,emp):\n self.calls.append(('whisper',t,n,l,lang,emp))\n" + " def OnRecvWhisperSystemMessage(self,t,n,b):\n self.calls.append(('wsys',t,n,b))\n" + " def OnRecvWhisperError(self,t,n,b):\n self.calls.append(('werr',t,n,b))\n" + "chat_wnd=ChatWnd()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,chat_wnd)\n"); + auto chatWire=[](uint8_t type,uint32_t vid,const std::string& msg) { + std::vector out(sizeof(ava2::TPacketGCChat)+msg.size()+1,0); + auto* pkt=reinterpret_cast(out.data()); + pkt->header=ava2::HEADER_GC_CHAT;pkt->size=uint16_t(out.size());pkt->type=type;pkt->dwVID=vid;pkt->bEmpire=1; + std::memcpy(out.data()+sizeof(ava2::TPacketGCChat),msg.data(),msg.size()); + return out; + }; + auto feed=[&](const std::vector& bytes) { netStream.PushRecvData(bytes.data(),bytes.size());netStream.ProcessRecvData(); }; + auto check=[&](bool ok,const char* what) { if(!ok) throw std::runtime_error(std::string("AVA2 chat parity: ")+what); }; + feed(chatWire(ava2::CHAT_TYPE_NOTICE,0,"Server: Welcome to AVA2!")); + python.execute("assert chat_wnd.calls==[('locale',2,'Server: Welcome to AVA2!')], chat_wnd.calls\nchat_wnd.calls=[]\n"); + check(appendedLines().empty(),"VID 0 non-shout goes to GetLocaleString, not AppendChat"); + feed(chatWire(ava2::CHAT_TYPE_SHOUT,0,"Bob : hello")); + check(appendedLines()==std::vector{"6:Bob : hello"},"VID 0 shout goes to AppendChat"); + feed(chatWire(15,0,"ignored"));feed(chatWire(ava2::CHAT_TYPE_TALKING,4242,"Nobody : x")); + check(appendedLines().size()==1,"type >= CHAT_TYPE_MAX_NUM and unknown chatter are dropped"); + python.execute("assert chat_wnd.calls==[], chat_wnd.calls\n"); + // CHAT_TYPE_COMMAND -> ServerCommand: BINARY_ServerCommand_Run first, then the C++ fallback. + feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"cube open 20383")); + feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"cube info 100 \"27001\" 2")); + feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"messenger_auth Alice")); + feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"ConsoleEnable")); + python.execute( + "assert chat_wnd.calls==[('run','cube open 20383'),('cube',20383),('run','cube info 100 \"27001\" 2'),('cubeinfo',100,27001,2)," + "('run','messenger_auth Alice'),('friend','Alice')], chat_wnd.calls\n" + "chat_wnd.calls=[]\nchat_wnd.run=True\n"); + feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"cube open 1")); + python.execute("assert chat_wnd.calls==[('run','cube open 1')], chat_wnd.calls\nchat_wnd.calls=[]\n"); + feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"ObserverMode 1"));feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"sms")); + python.execute("assert player.IsObserverMode()==0 and player.HasMobilePhoneNumber()==0\nchat_wnd.run=False\nchat_wnd.calls=[]\n"); + feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"ObserverMode 1"));feed(chatWire(ava2::CHAT_TYPE_COMMAND,0,"sms")); + python.execute("assert player.IsObserverMode()==1 and player.HasMobilePhoneNumber()==1\nchat_wnd.calls=[]\n"); + // Whisper: 31-byte header with bLanguage/bEmpire. + auto whisperWire=[](uint8_t type,const char* from,uint8_t language,uint8_t empire,const std::string& msg) { + std::vector out(31+msg.size()+1,0); + out[0]=ava2::HEADER_GC_WHISPER;out[1]=uint8_t(out.size());out[2]=uint8_t(out.size()>>8);out[3]=type; + std::memcpy(out.data()+4,from,std::strlen(from));out[29]=language;out[30]=empire; + std::memcpy(out.data()+31,msg.data(),msg.size()); + return out; + }; + feed(whisperWire(ava2::WHISPER_TYPE_CHAT,"Alice",2,3,"hi")); + feed(whisperWire(ava2::WHISPER_TYPE_SYSTEM,"Alice",0,0,"sys")); + feed(whisperWire(ava2::WHISPER_TYPE_NOT_EXIST,"Ghost",0,0,"")); + python.execute("assert chat_wnd.calls==[('whisper',0,'Alice','Alice : hi',2,3),('wsys',255,'Alice','sys'),('werr',1,'Ghost','')], chat_wnd.calls\n"); + // PyCallClassMemberFunc: a missing method or a raising callback never aborts the pump. + python.execute("chat_wnd.GetLocaleString=None\ndel ChatWnd.OnRecvWhisper\ndef boom(*a):\n raise ValueError('callback error is printed, not thrown')\nchat_wnd.OnRecvWhisperSystemMessage=boom\n"); + feed(chatWire(ava2::CHAT_TYPE_NOTICE,0,"x")); + feed(whisperWire(ava2::WHISPER_TYPE_CHAT,"Alice",0,0,"hi"));feed(whisperWire(ava2::WHISPER_TYPE_SYSTEM,"Alice",0,0,"sys")); + // '/' repeats the last slash command (SendChatPacket m_strLastCommand). + netStream.ClearSendQueue();netStream.SendChatPacket("/stat ht");netStream.SendChatPacket("/"); + auto sent=netStream.PopSendPackets(); + check(sent.size()==2 && sent[0]==sent[1],"'/' repeats the previous command"); + // CheckPacket framing: a fixed GamePhase packet is consumed, the next one still dispatches; + // a partial dynamic packet waits; an unknown header clears the buffer and requests quit. + ava2::CPythonChat::Instance().Destroy(); + std::vector stream={114,0,0,0,0,0}; // HEADER_GC_SEPCIAL_EFFECT (type 0, unknown VID): fixed packet + auto shout=chatWire(ava2::CHAT_TYPE_SHOUT,0,"A : b"); + stream.insert(stream.end(),shout.begin(),shout.end()); + netStream.PushRecvData(stream.data(),stream.size()-2);netStream.ProcessRecvData(); + check(netStream.GetUnportedPackets().empty() && appendedLines().empty(),"partial packet waits after a fixed packet"); + netStream.PushRecvData(stream.data()+stream.size()-2,2);netStream.ProcessRecvData(); + check(appendedLines().size()==1,"packet after a fixed one is dispatched"); + std::vector unknown={250,1,2,3};unknown.insert(unknown.end(),shout.begin(),shout.end()); + feed(unknown); + check(appendedLines().size()==1 && netStream.IsQuitRequested(),"unknown header clears the buffer and posts quit"); + netStream.ResetConnection();netStream.SetPhase(ava2::PHASE_GAME); + check(!netStream.IsQuitRequested(),"ResetConnection clears the quit request"); + std::vector bgm={ava2::HEADER_GC_MAIN_CHARACTER4_BGM_VOL};bgm.resize(75,0); + bgm.insert(bgm.end(),shout.begin(),shout.end());feed(bgm); + check(appendedLines().size()==1,"MAIN_CHARACTER4_BGM_VOL in Game phase is RecvDefaultPacket (buffer cleared)"); + ava2::CPythonChat::Instance().Destroy(); + python.execute("net.SetPhaseWindow(net.PHASE_WINDOW_GAME,0)\n"); std::cout << "PhaseGame wire packet receive & dispatch verified successfully!\n"; + { + // Pass 17: player-settings effects, GC114, emoticon gate, name colours, NPC wear, sash. + auto& actors=ava2::NetworkActorManager::Instance(); + using NAM=ava2::NetworkActorManager; + check(NAM::GetEffectCRC(17)!=0 && NAM::GetEffectCRC(NAM::EFFECT_EMOTICON)!=0,"introLoading/player settings registered effects"); + check(NAM::GetIndexedNameColor(NAM::NAMECOLOR_SHOP)!=0 && NAM::GetIndexedNameColor(NAM::NAMECOLOR_PK)!=0,"chrmgr.RegisterNameColor tables filled"); + ava2::SNetworkActorData pc;pc.m_dwVID=7001;pc.m_bType=6;pc.m_dwRace=1;pc.m_stName="Killer";pc.m_dwEmpireID=1; + pc.m_dwStateFlags=NAM::ADD_CHARACTER_STATE_KILLER;actors.AppendActor(pc); + check(actors.GetNameColorIndex(7001)==NAM::NAMECOLOR_PK,"KILLER state uses NAMECOLOR_PK"); + ava2::SNetworkActorData shop;shop.m_dwVID=7002;shop.m_bType=1;shop.m_dwRace=30001;shop.m_dwWeapon=5;actors.AppendActor(shop); + check(actors.GetNameColorIndex(7002)==NAM::NAMECOLOR_SHOP,"race 30000-30020 NPC uses NAMECOLOR_SHOP"); + check(actors.GetActorData(7002)->m_dwWeapon==0,"non-PC without npc_wear takes no weapon"); + // GC114: 6 bytes, SE_CRITICAL attaches EFFECT_CRITICAL (17) to the actor. + const size_t before=actors.GetActorData(7001)->m_attachedEffects.size(); + const uint8_t se[]={114,uint8_t(ava2::SE_CRITICAL),0x59,0x1b,0,0}; + netStream.PushRecvData(se,sizeof(se));netStream.ProcessRecvData(); + check(netStream.GetUnportedPackets().empty() && actors.GetActorData(7001)->m_attachedEffects.size()==before+1,"GC114 attaches the special effect"); + // SetEmoticon: one emoticon per 1000 ms (m_dwEmoticonTime). + static uint32_t fakeNow=5000;actors.SetTimeSourceForTest([]{return fakeNow;}); + check(actors.IsPossibleEmoticon(7002),"fresh actor may show an emoticon"); + actors.SetEmoticon(7002,0);fakeNow=5500; + check(!actors.IsPossibleEmoticon(7002),"emoticon blocked inside 1000 ms"); + actors.SetTimeSourceForTest(nullptr); + // npc_wear.txt row (ENABLE_NPC_WEAR_ITEM): race/weapon/armor/hair/acce/mount/7 shining. + auto& npd=ava2::NonPlayerData::Instance(); + npd.loadNPCWear("20016\tall\t2\t11\t12\t13\t86010\t0\t1\t2\t3\t4\t5\t6\t7\n"); + ava2::SNetworkActorData wear;wear.m_dwVID=7003;wear.m_bType=1;wear.m_dwRace=20016;actors.AppendActor(wear); + const auto* w=actors.GetActorData(7003); + check(w->m_dwRace==2 && w->m_dwWeapon==11 && w->m_dwArmor==12 && w->m_dwHair==13 && w->m_dwSash==1010 + && w->m_shining[0]==1 && w->m_shining[ava2::CHR_SHINING_NUM-1]==ava2::CHR_SHINING_NUM,"npc_wear replaces race and parts"); + check(w->m_dwSashEffect!=0,"acce > 86000 attaches EFFECT_REFINED+EFFECT_SASH"); + actors.ChangeSash(7003,0); + check(actors.GetActorData(7003)->m_dwSash==0 && actors.GetActorData(7003)->m_dwSashEffect==0,"ChangeSash clears the sash effect"); + npd.clearNPCWear(); + for(uint32_t vid:{7001u,7002u,7003u}) actors.RemoveActor(vid); + } + { + // Pass 20: 64-bit Granny (Map_Sands shadow_dragon) loads and its curve2-compressed + // animation (D4nK*/D3K* tracks) drives the bones instead of leaving them at bind. + auto resolve=[](const char* p){ + std::error_code ec; + for(const auto& c:CResourceManager::GetCandidatePaths(CResourceManager::NormalizePath(p))) + if(std::filesystem::is_regular_file(c,ec)) return c; + return std::string(); + }; + const std::string model=resolve("d:/ymir work/monster/shadow_dragon/shadow_dragon.gr2"); + const std::string run=resolve("d:/ymir work/monster/shadow_dragon/run.gr2"); + if(model.empty()||run.empty()) { + std::cout<<"pass20 shadow_dragon assets missing: 64-bit gr2 checks skipped\n"; + } else { + auto dragon=ava2::Gr2ModelInstance::Load(model); + check(dragon && dragon->GetFile().magic()==gr2::Magic::Bit64_LE && !dragon->GetInfo().meshes.empty(),"64-bit shadow_dragon.gr2 loads with meshes"); + check(dragon && dragon->LoadExternalAnimation(run),"64-bit run.gr2 loads"); + if(dragon) { + size_t compressed=0,decoded=0; + gr2::LoadError err;auto anim=gr2::File::load_path(run,&err); + if(anim) for(auto& t:anim->file_info().animations[0].tracks) + if(t.rot_type.rfind("D4n",0)==0){++compressed;decoded+=!t.orientation.empty();} + check(compressed>0 && decoded==compressed,"D4n compressed quaternion tracks decode"); + const float dur=dragon->GetAnimationDuration(); + float a[16]={},b[16]={},bind[16]={}; + const bool ok=dragon->GetBoneWorldTransform("Spine01_jnt",a,0.0f) + && dragon->GetBoneWorldTransform("Spine01_jnt",b,dur*0.5f) + && dragon->GetBoneWorldTransform("Spine01_jnt",bind,-1.0f); + float moved=0.0f,fromBind=0.0f;bool finite=ok; + for(int i=0;i<16;++i){finite&=std::isfinite(a[i])&&std::isfinite(b[i]);moved=std::max(moved,std::fabs(a[i]-b[i]));fromBind=std::max(fromBind,std::fabs(a[i]-bind[i]));} + check(finite && dur>0.0f && moved>1e-3f && fromBind>1e-3f,"curve2 animation moves Spine01_jnt away from bind"); + } + } + } + { + // Pass 18: CRaceManager .msm race/shape/hair, AttachWeapon bones and AttachSash on network actors. + auto& actors=ava2::NetworkActorManager::Instance(); + using NAM=ava2::NetworkActorManager;using RD=ava2::RaceData; + auto& races=ava2::RaceManager::Instance(); + races.LoadGameNPC("npclist.txt");races.LoadPlayerRaces(); + if(!races.GetRaceDataPointer(0)) { + std::cout<<"pass18 race assets (warrior_m.msm) missing: mount checks skipped\n"; + } else { + NAM::SetHairColorEnable(true); + ava2::SNetworkActorData hero;hero.m_dwVID=7101;hero.m_bType=6;hero.m_dwRace=0;hero.m_dwArmor=1; + hero.m_dwHair=1;hero.m_dwWeapon=10;hero.m_dwSash=1;hero.m_stName="Mounted"; + actors.AppendActor(hero); + auto inst=actors.GetActorInstance(7101); + check(inst && inst->GetRace()==0 && inst->GetShape()==1,"SetRace(0) + SetArmor(1) -> shape 1"); + check(inst->GetShapeModelFile().find("warrior_novice")!=std::string::npos,"ShapeData01 model requested"); + check(inst->GetPartModelPath(RD::PART_HAIR).find("hair_1_1")!=std::string::npos && inst->GetPartBone(RD::PART_HAIR).empty(),"HairData01 skinned on PART_HAIR"); + check(inst->GetPartItemID(RD::PART_WEAPON)==10 && inst->GetPartBone(RD::PART_WEAPON)=="equip_right_hand" + && inst->GetPartModelPath(RD::PART_WEAPON).find("00010")!=std::string::npos,"warrior weapon on equip_right_hand"); + check(inst->GetPartBone(RD::PART_SASH)=="Bip01 Spine2" && inst->GetPartModelPath(RD::PART_SASH).find("85_001")!=std::string::npos,"sash 85001 on Bip01 Spine2"); + check(actors.GetActorData(7101)->m_awPart[RD::PART_SASH]==1 && actors.GetActorData(7101)->m_awPart[RD::PART_HAIR]==1,"m_awPart tracks hair/sash"); + // The AVA2 pc/item gr2 are BitKnit2-compressed (Granny format 4): the meshes must decode and draw. + check(inst->GetModel() && !inst->GetModel()->GetInfo().meshes.empty(),"BitKnit2 warrior_novice.gr2 loads"); + { + auto draws=inst->BuildDrawCommands(); + size_t shapeMeshes=inst->GetModel()->GetInfo().meshes.size(); + bool textured=true,bodySkin=false,hairSkin=false,weapon=false,sash=false; + for(auto& dc:draws){ + std::string t=dc.texture0;for(auto& c:t) c=char(std::tolower((unsigned char)c)); + if(t.empty()) textured=false; + bodySkin|=t.find("warrior_novice_blue")!=std::string::npos; // .msm ShapeData SourceSkin->TargetSkin + hairSkin|=t.find("warrior_hair_01_white")!=std::string::npos; // .msm HairData skin + weapon|=t.find("weapon_chogeup_01")!=std::string::npos; + sash|=t.find("acce_85_001")!=std::string::npos; + } + check(draws.size()>shapeMeshes && textured,"shape + hair/weapon/sash parts draw with textures"); + check(bodySkin && hairSkin && weapon && sash,"msm skins and part textures reach the draws"); + } + // ChangeWeapon(0) detaches; ChangeArmor rebuilds the race and re-applies hair/sash/weapon. + ava2::SNetworkUpdateActorData up;up.m_dwVID=7101;up.m_dwArmor=1;up.m_dwWeapon=0;up.m_dwHair=1;up.m_dwSash=1; + actors.UpdateActor(up); + check(inst->GetPartItemID(RD::PART_WEAPON)==0 && inst->GetPartModelPath(RD::PART_WEAPON).empty(),"ChangeWeapon(0) removes the weapon"); + up.m_dwArmor=0;up.m_dwWeapon=10;actors.UpdateActor(up); + check(inst->GetShape()==0 && inst->GetPartModelPath(RD::PART_HAIR).find("hair_1_1")!=std::string::npos + && inst->GetPartItemID(RD::PART_WEAPON)==10 && inst->GetPartBone(RD::PART_SASH)=="Bip01 Spine2","ChangeArmor re-applies parts"); + // Missing sash item keeps the previous sash (GetItemDataPointer failure returns early). + actors.ChangeSash(7101,999); + check(inst->GetPartModelPath(RD::PART_SASH).find("85_001")!=std::string::npos,"unknown sash keeps the old model"); + // npc_wear: the NPC is drawn as race 0 with the listed parts (hair allowed, race <= 8). + auto& npd=ava2::NonPlayerData::Instance(); + npd.loadNPCWear("20016\tall\t0\t10\t1\t1\t85001\t0\t0\t0\t0\t0\t0\t0\t0\n"); + ava2::SNetworkActorData wear;wear.m_dwVID=7102;wear.m_bType=1;wear.m_dwRace=20016;actors.AppendActor(wear); + auto w=actors.GetActorInstance(7102); + check(w->GetRace()==0 && w->GetShape()==1 && w->GetPartItemID(RD::PART_WEAPON)==10 + && !w->GetPartModelPath(RD::PART_HAIR).empty() && w->GetPartBone(RD::PART_SASH)=="Bip01 Spine2","npc_wear mounts race/armor/weapon/hair/sash"); + npd.clearNPCWear(); + // Monster race from npclist: no hair / sash / weapon for non-PC races. + ava2::SNetworkActorData dog;dog.m_dwVID=7103;dog.m_bType=0;dog.m_dwRace=101;dog.m_dwWeapon=10;actors.AppendActor(dog); + auto d=actors.GetActorInstance(7103); + check(d->GetRace()==101 && d->GetShapeModelFile().find("stray_dog")!=std::string::npos && d->GetPartItemID(RD::PART_WEAPON)==0,"npclist stray_dog race loads without parts"); + for(uint32_t vid:{7101u,7102u,7103u}) actors.RemoveActor(vid); + } + } + + { + // Remaining GamePhase() handlers (PythonNetworkStreamPhaseGameRecv.cpp): golden wire bytes -> callbacks. + netStream.ResetConnection();netStream.SetPhase(ava2::PHASE_GAME); + python.execute("class GameRec(object):\n def __init__(self):\n self.calls=[]\n def __getattr__(self,name):\n if name.startswith('__'):\n raise AttributeError(name)\n return lambda *a: self.calls.append((name,)+a)\ngame_rec=GameRec()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,game_rec)\n"); + struct W { std::vector b; + W& u8(uint32_t v){b.push_back(uint8_t(v));return *this;} + W& u16(uint32_t v){u8(v);u8(v>>8);return *this;} + W& u32(uint32_t v){u16(v);u16(v>>16);return *this;} + W& i64(int64_t v){u32(uint32_t(v));u32(uint32_t(uint64_t(v)>>32));return *this;} + W& str(const std::string& t,size_t n){for(size_t i=0;i>8);return *this;} + W& size32(){for(int i=0;i<4;++i) b[1+i]=uint8_t(b.size()>>(8*i));return *this;} }; + auto feedG=[&](const std::vector& bytes) { netStream.PushRecvData(bytes.data(),bytes.size());netStream.ProcessRecvData(); }; + auto expect=[&](const std::string& calls,const char* what) { + python.execute("calls,game_rec.calls=game_rec.calls,[]\nassert calls=="+calls+",('"+what+"',calls)\n"); + }; + auto channel=W{}.u8(121).u8(3).u8(1).b; + // 255 Handshake: TIME_SYNC reply (sequenced) and GamePhase() returns before the next packet. + auto hs=W{}.u8(255).u32(0x11223344).u32(1000).u32(50).b;hs.insert(hs.end(),channel.begin(),channel.end()); + netStream.ClearSendQueue();feedG(hs); + auto sent=netStream.PopSendPacketsWithSequence(); + check(sent.size()==1 && sent[0].first==W{}.u8(0xfc).u32(0x11223344).u32(1100).u32(0).b && sent[0].second,"Handshake -> TIME_SYNC dwTime+2*lDelta"); + expect("[]","Handshake stops the GamePhase frame"); + netStream.ProcessRecvData(); + expect("[('SetChannelIndex',3),('SetAntiExp',1)]","packet after Handshake runs next frame"); + feedG(W{}.u8(252).b); + check(ava2::GetServerMSec()-1050<1000,"HandshakeOK sets server msec to time+delta+elapsed"); + // 205 XTrap: ACK 204 + 128 bytes without SendSequence. + feedG(W{}.u8(205).zero(128).b); + sent=netStream.PopSendPacketsWithSequence(); + check(sent.size()==1 && sent[0].first==W{}.u8(204).zero(128).b && !sent[0].second,"XTrap ACK is unsequenced"); + // 204 HS / 213 Unk213 fail -> RecvErrorPacket clears the buffer. + auto hsReq=W{}.u8(204).zero(402).b;hsReq.insert(hsReq.end(),channel.begin(),channel.end());feedG(hsReq); + auto unk=W{}.u8(213).u8(0).b;unk.insert(unk.end(),channel.begin(),channel.end());feedG(unk); + expect("[]","HS and Unk213 fail and clear the buffer"); + // 152 HybridCrypt keys: stream dropped, frame stops. + auto keys=W{}.u8(152).u16(0).u32(3).u8(1).u8(2).u8(3).size16().b;keys.insert(keys.end(),channel.begin(),channel.end()); + feedG(keys);expect("[]","HybridCrypt stops the frame"); + netStream.ProcessRecvData();expect("[('SetChannelIndex',3),('SetAntiExp',1)]","HybridCrypt key stream consumed"); + // 95/119 refine (ENABLE_MULTI_REFINE_WORLDARD). + auto refine=[&](bool isNew,uint8_t sub) { + W w;w.u8(isNew?119:95);if(isNew) w.u8(4);w.u8(7); + w.u32(11).u32(12).u8(1).u32(500).u32(90).u8(1).u32(2).u8(sub).u32(30).u32(2).zero(32);return w.b; }; + feedG(refine(false,1));feedG(refine(true,1));feedG(refine(true,5));feedG(refine(false,0)); + expect("[('OpenRefineDialog',2,7,12,500,90,1),('AppendMaterialToRefineDialog',2,30,2)," + "('BINARY_MULTI_REFINE_ADD_INFO',2,7,12,500,90,1,4),('BINARY_MULTI_REFINE_ADD_MATERIAL',2,30,2)," + "('BINARY_MULTI_REFINE_DATES_CLEAR',),('BINARY_MULTI_REFINE_CLEAR_INFO',)]","refine information"); + // 112 ChangeSkillGroup + 72 SkillLevel: refresh block order Character, Skill, Status. + std::vector grp=W{}.u8(112).u8(2).b;std::vector lv(256,0);lv[0]=72;grp.insert(grp.end(),lv.begin(),lv.end()); + feedG(grp); + check(netStream.GetMainActorSkillGroup()==2,"skill group stored"); + expect("[('RefreshCharacter',),('RefreshSkill',),('RefreshStatus',)]","refresh order"); + // 41 PVP, 215 Sash, 218 KingdomsWar, 231 Sungma, 131/132 Love, 242 67Attr, 82 guild. + feedG(W{}.u8(41).u32(5).u32(6).u8(ava2::PVP_MODE_FIGHT).b); + check(ava2::NetworkActorManager::Instance().FindPVPKey(6,5),"PVP fight key"); + feedG(W{}.u8(215).u8(ava2::SASH_SUBHEADER_GC_ADDED).u8(1).u32(0).u8(1).u8(0).u16(0).u32(0).u32(0).u32(0).b); + feedG(W{}.u8(218).u8(1).u32(1).u32(2).u32(3).u32(10).u32(4).u32(5).u32(60).b); + feedG(W{}.u8(231).u8(1).u8(2).u8(3).u8(4).b); + feedG(W{}.u8(131).str("Bob",25).u8(80).b);feedG(W{}.u8(132).u8(90).b); + feedG(W{}.u8(242).b);feedG(W{}.u8(82).b); + expect("[('RefreshTargetBoardByVID',5),('RefreshTargetBoardByVID',6),('AlertSash',1),('ActSash',3,1)," + "('ActKingdomsWar',3,1,2,3,10,4,5,60),('BINARY_SungMaAttr',1,2,3,4),('BINARY_LoverInfo','Bob',80)," + "('BINARY_UpdateLovePoint',90),('OpenAttr67AddDlg',),('AskGuildName',)]","small callbacks"); + // 235 ExchangeLog (LOAD + LOAD_ITEM), 241 CatchKing, 214/216 Calendar, 209 DS refine. + W log;log.u8(235).u32(0).u8(0).str("CODE",19).u8(1).u16(1).u32(9) + .str("Al",25).u32(1).i64(5000000000LL).str("1.2.3.4",16).str("Bo",25).u32(2).i64(7).str("5.6.7.8",16).str("2026-10-06",25).u8(0); + feedG(log.size32().b); + W item;item.u8(235).u32(0).u8(1).u16(1).u32(9).u8(2).u32(19).u16(1).u32(4);item.zero(28).u8(1).u16(15).zero(42).u8(1); + feedG(item.size32().b); + feedG(W{}.u8(241).u16(5).u8(ava2::SUBHEADER_GC_CATCH_KING_START).u32(123).b); + feedG(W{}.u8(241).u16(4).u8(ava2::SUBHEADER_GC_CATCH_KING_REWARD).b); + feedG(W{}.u8(214).u8(ava2::CALENDAR_RECEIVE_OPEN).u8(0).zero(400).u32(0).u32(777).b); + feedG(W{}.u8(216).u8(ava2::CALENDAR_RECEIVE_LOAD_EVENTS_ADM).u32(3).str("ev",100).str("desc",100).b); + feedG(W{}.u8(209).u8(ava2::DS_SUB_HEADER_REFINE_SUCCEED).u8(1).u16(12).b); + expect("[('ExchangeLogClear','CODE'),('ExchangeLogAppend',9,'Al',5000000000,'1.2.3.4','Bo',7,'5.6.7.8','2026-10-06'),('ExchangeLogRefresh',0)," + "('ExchangeLogItemAppend',9,2,19,1,[4,0,0,0,0,0,0,0],[1]+[0]*14,[15]+[0]*14,1),('ExchangeLogRefresh',9)," + "('MiniGameCatchKingEventStart',123),('BINARY_CALENDAR_OPEN',777),('BINARY_CALENDAR_LOAD_EVENTS_ADM',3,'ev','desc')," + "('BINARY_DragonSoulRefineWindow_RefineSucceed',1,12)]","exchange log / catch king / calendar / DS"); + // 130 Land, 115 NPC list, 110 Dungeon destination, 249 blacklist: consumed exactly. + feedG(W{}.u8(130).u16(0).zero(48).size16().b); + feedG(W{}.u8(115).u16(0).u16(1).zero(17).size16().b); + feedG(W{}.u8(110).u16(12).u8(ava2::DUNGEON_SUBHEADER_GC_DESTINATION_POSITION).u32(100).u32(200).b); + feedG(W{}.u8(249).zero(1024).b); + feedG(channel); + check(netStream.GetDungeonDestination()==std::make_pair(100,200),"dungeon destination stored"); + expect("[('SetChannelIndex',3),('SetAntiExp',1)]","land/npc/dungeon/blacklist consumed exactly"); + check(netStream.GetUnportedPackets().empty(),"no newly ported header is skipped"); + python.execute("net.SetPhaseWindow(net.PHASE_WINDOW_GAME,0)\n"); + std::cout << "PhaseGame remaining handlers verified successfully!\n"; + } netStream.ResetConnection(); python.execute("class SkillCallbacks:\n def __init__(self):\n self.skills=0\n self.status=0\n def RefreshSkill(self):\n self.skills+=1\n def RefreshStatus(self):\n self.status+=1\nskill_callbacks=SkillCallbacks()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,skill_callbacks)\nplayer.SetSkill(1,1)\nplayer.SetSkill(2,2)\nplayer.SetSkill(3,3)\nplayer.SetSkill(4,4)\nassert player.GetSkillLevel(1)==0\nassert player.GetSkillSlotIndex(3)==3\n"); diff --git a/tests/quest_test.cpp b/tests/quest_test.cpp new file mode 100644 index 00000000..d5f84e2b --- /dev/null +++ b/tests/quest_test.cpp @@ -0,0 +1,58 @@ +#include "quest_state.h" +#include "python_runtime.h" +#include "python_net.h" +#include "eter_net/PythonNetworkStream.h" +#include +#include +using namespace ava2; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +std::vector packet(uint16_t id,uint8_t flags,const std::vector& payload) { + auto size=uint16_t(6+payload.size()); + return {81,uint8_t(size),uint8_t(size>>8),uint8_t(id),uint8_t(id>>8),flags}; +} +void append(std::vector& p,const std::string& field,size_t size) { + auto start=p.size();p.resize(start+size,0); + std::copy_n(field.begin(),std::min(field.size(),size),p.begin()+start); +} +void u32(std::vector& p,uint32_t n) { for(unsigned i=0;i<4;++i)p.push_back(uint8_t(n>>(i*8))); } +void send(uint16_t id,uint8_t flags,const std::vector& payload) { + auto p=packet(id,flags,payload);p.insert(p.end(),payload.begin(),payload.end()); + PythonNetworkStream::Instance().PushRecvData(p);PythonNetworkStream::Instance().ProcessRecvData(); +} +int main(int argc,char** argv) { + if(argc!=3)return 2; + try { + QuestState fixture;QuestRecord q;q.index=10;q.clockValue=20;q.title="First"; + fixture.apply(1,q,127,100);q.index=20;fixture.apply(1,q,127,101); + q.index=10;q.title="Replaced";fixture.apply(1,q,127,102); + require(fixture.records[0].index==20 && fixture.records[1].title=="Replaced","wire begin did not replace/reorder"); + q.title="Duplicate";fixture.apply(1,q,127,103,true); + require(fixture.records[1].title=="Replaced","quest.Add duplicate changed state"); + q.title.clear();q.clockValue=0;q.counterValue=-3;fixture.apply(2,q,32,110); + require(fixture.find(10)->title=="Replaced" && fixture.find(10)->startTime==102 && fixture.find(10)->counterValue==-3,"partial update semantics"); + require(QuestState::remaining(*fixture.find(10),130)==-8,"expired countdown clamped"); + q.clockValue=-1;fixture.apply(2,q,8,140); + require(QuestState::remaining(*fixture.find(10),150)==0,"negative clock must return zero"); + PythonRuntime python(argv[1],argv[2]); + auto& stream=PythonNetworkStream::Instance();stream.ResetConnection();stream.SetPhase(PHASE_GAME); + python.execute("import quest, net\nassert quest.GetQuestCount()==0\nclass Callbacks:\n def __init__(self):\n self.refresh=0\n self.translations=[]\n def RefreshQuest(self):\n self.refresh+=1\n def GetQuestLetterName(self,*args):\n self.translations.append(args)\n kind,index,flags,title,clock,counter,icon,cv,nv=args\n quest.Add(kind,index,'Translated',clock,cv,counter,nv,icon,flags)\ncb=Callbacks()\nnet.SetPhaseWindow(net.PHASE_WINDOW_GAME,cb)\n"); + std::vector payload{1};append(payload,"Title",31);append(payload,"Clock",17);u32(payload,60);append(payload,"Counter",17);u32(payload,uint32_t(-9));append(payload,"icon.tga",25); + auto p=packet(65535,127,payload);p.insert(p.end(),payload.begin(),payload.end());p.push_back(44); + stream.PushRecvData(p.data(),p.size()-2);stream.ProcessRecvData(); + python.execute("assert quest.GetQuestCount()==0\nassert cb.refresh==0\n"); + stream.PushRecvData(p.data()+p.size()-2,2);stream.ProcessRecvData(); + require(stream.PopSendBytes()==std::vector{254},"quest frame lost following ping"); + python.execute("assert quest.GetQuestCount()==1\nassert quest.GetQuestIndex(0)==65535\nassert quest.GetQuestData(0)==('Title',0,'Counter',-9)\nassert quest.GetQuestLastTime(0)==('Clock',60)\nassert cb.refresh==1\n"); + require(GetQuestState().find(65535)->counterValue==-9,"signed counter"); + payload.clear();append(payload,"",31);u32(payload,0);send(65535,2|32,payload); + require(GetQuestState().find(65535)->title=="Title" && GetQuestState().find(65535)->counterValue==0,"empty title/value update"); + payload={1};append(payload,"^LOCALE_TITLE",31);send(7,1|2,payload); + python.execute("assert cb.translations==[(1,7,3,'^LOCALE_TITLE','','','',0,0)]\nassert quest.GetQuestIndex(1)==7\nquest.Add(1,7,'Ignored','',0,'',0,'',0)\nassert quest.GetQuestCount()==2\nquest.Add(2,-1,'Unsigned','',-1,'',0,'',8,123)\nassert quest.GetQuestIndex(2)==-1\nassert quest.GetQuestLastTime(2)==('',0)\nfor getter in [quest.GetQuestIndex,quest.GetQuestData,quest.GetQuestLastTime]:\n try:\n getter(-1)\n raise AssertionError('invalid quest index accepted')\n except RuntimeError:\n pass\n"); + send(65535,1,{0}); + python.execute("assert quest.GetQuestCount()==2\nassert quest.GetQuestIndex(0)==7\nassert cb.refresh==4\n"); + // Truncated flag-selected title cannot consume a coalesced next packet. + send(9,2,{}); + python.execute("assert quest.GetQuestCount()==2\nassert cb.refresh==4\nquest.Clear()\nassert quest.GetQuestCount()==0\n"); + stream.ResetConnection();std::cout<<"AVA2 quest state, wire and Python parity passed\n"; + } catch(const std::exception& e) { std::cerr< +#include +using namespace ava2; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +void put(std::vector& p,uint64_t v,unsigned n) { for(unsigned i=0;i>(8*i))); } +std::vector item() { + std::vector p;put(p,0xffffffff,4);put(p,0x80000001,4);put(p,uint64_t(-1234567890123LL),8);put(p,uint32_t(-9),4);p.push_back(255); + for(unsigned i=0;i<8;++i)put(p,uint32_t(-100-int(i)),4); + for(unsigned i=0;i<15;++i) { p.push_back(uint8_t(240+i));put(p,uint16_t(-300-int(i)),2); } + p.push_back(7);const size_t start=p.size();p.resize(start+25,0);p[start]='S';p[start+1]='e';p[start+2]='l';p[start+3]='l';p[start+4]='e';p[start+5]='r'; + put(p,0x80000002,4);return p; +} +std::vector reply(uint16_t count) { + std::vector p{156};put(p,7+128u*count,4);put(p,count,2); + for(unsigned i=0;i{254},"search frame lost following ping"); + python.execute("assert search.GetItemCount()==2\nassert w.counts==[2]\nassert search.GetSearchItemID(0)==-1\nassert search.GetSearchItemVnum(0)==-2147483647\nassert search.GetSearchItemPrice(0)==-1234567890123\nassert search.GetSearchItemCount(0)==-9\nassert search.GetSearchItemShopVID(0)==-2147483646\nassert search.GetSearchItemPos(0)==255\nassert search.GetSearchItemSeller(0)=='Seller'\nassert search.GetSearchItemMetinSocket(1,7)==-107\nassert search.GetSearchItemAttribute(1,14)==(254,-314)\nassert search.GetSearchItemNewName(0)=='^'\nfor getter in [search.GetSearchItemID,search.GetSearchItemSeller]:\n try:\n getter(-1)\n raise AssertionError('invalid index accepted')\n except RuntimeError:\n pass\n"); + auto more=reply(1),empty=reply(0);more.insert(more.end(),empty.begin(),empty.end());s.PushRecvData(more);s.ProcessRecvData(); + python.execute("assert search.GetItemCount()==3\nassert w.counts==[2,3]\n"); + // Count claims one record but the declared packet ends before it: retain prior results. + const std::vector malformed{156,7,0,0,0,1,0,44};s.PushRecvData(malformed);s.ProcessRecvData(); + require(s.PopSendBytes().empty(),"search malformed length consumed coalesced ping"); + python.execute("assert search.GetItemCount()==3\nassert w.counts==[2,3]\nsearch.ClearSearchItems()\nassert search.GetItemCount()==0\nassert w.counts==[2,3]\nargs=[-2,3,257,-1,258,259,260,261,262,263,264,265,266,267,268,269,-5,9223372036854775807,'Sword']\nassert net.SendPrivateShopSearchInfo() is None\nnet.SendPrivateShopSearchInfo(*args)\n"); + require(s.PopSendBytes().empty(),"search sent without main actor"); + SNetworkActorData actor{};actor.m_dwVID=1001;actor.m_dwRace=0;actor.m_stName="SearchFixture";NetworkActorManager::Instance().AppendActor(actor);s.SetMainActorVID(1001); + python.execute("net.SendPrivateShopSearchInfo(*args)\n"); + auto packets=s.PopSendPacketsWithSequence();require(packets.size()==1 && !packets[0].second,"search request incorrectly sequenced"); + std::vector expected{143};put(expected,uint32_t(-2),4);put(expected,3,4);expected.resize(59,0);const char input[]="Sword";std::copy_n(input,5,expected.begin()+9); + expected.insert(expected.end(),{1,255,2,3,4,5,6,7,8,9,12,10,11,13});put(expected,uint64_t(-5),8);put(expected,0x7fffffffffffffffULL,8); + require(packets[0].first==expected && expected.size()==89,"search request field layout/conversions"); + s.ClearSendQueue();auto instance=NetworkActorManager::Instance().GetActorInstance(1001);require(bool(instance),"missing actor");instance->SetSleep(true); + python.execute("net.SendPrivateShopSearchInfo(*args)\n");require(s.PopSendBytes().empty(),"controlled actor searched");instance->SetSleep(false); + python.execute("args[-1]='X'*50\ntry:\n net.SendPrivateShopSearchInfo(*args)\n raise AssertionError('oversized text accepted')\nexcept ValueError:\n pass\n");require(s.PopSendBytes().empty(),"invalid search emitted bytes"); + s.PushRecvData(reply(1));s.ProcessRecvData();s.ResetConnection();NetworkActorManager::Instance().Clear(); + } + { PythonRuntime python(argv[1],argv[2]);python.execute("import privateShopSearch as search\nassert search.GetItemCount()==0\n"); } + std::cout<<"AVA2 shop search state, wire and Python parity passed\n"; + } catch(const std::exception& e) { std::cerr< +#include +#include +#include +#include +using namespace ava2; +namespace fs = std::filesystem; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +void spit(const fs::path& p,const std::string& s) { fs::create_directories(p.parent_path());std::ofstream f(p,std::ios::binary);f<imageFile.empty(),"active skills have no pImage"); + require(active->gradeImageFiles[0]=="d:/ymir work/ui/skill/warrior/samyeon_01.sub" && + active->gradeImageFiles[2]=="d:/ymir work/ui/skill/warrior/samyeon_03.sub" && active->gradeImageFiles[3].empty(),"grade icons"); + auto* support=FindSkillDescription(2); + require(support->imageFile=="d:/ymir work/ui/skill/common/support/leadership.sub" && + support->gradeImageFiles[0]==support->imageFile && support->gradeImageFiles[2]==support->imageFile,"normal icon"); + require(FindSkillDescription(3)->gradeImageFiles[0].empty() && FindSkillDescription(3)->imageFile.empty(),"job map is case-sensitive"); + require(FindSkillDescription(130)->gradeImageFiles[1]=="d:/ymir work/ui/skill/common/support/riding_02.sub" && + FindSkillDescription(130)->imageFile.empty(),"riding grade icons"); + require(FindSkillDescription(131)->imageFile=="d:/ymir work/ui/skill/common/horse/horse_icon.sub","horse icon"); + + fs::current_path(root); + python.execute( + "import skill\n" + "def raises(f,*a):\n try:\n f(*a)\n except RuntimeError:\n return True\n return False\n" + // Requirement data is never loaded, so every query has the constructor-state answer. + "assert skill.IsSkillRequirement(1)==0 and raises(skill.IsSkillRequirement,99)\n" + "assert skill.GetSkillRequirementData(1)==(None,0)\n" + "assert skill.GetSkillRequireStatCount(1)==0 and skill.GetSkillRequireStatData(1,5)==(0,0)\n" + "assert skill.CanLevelUpSkill(1,19)==1 and skill.CanLevelUpSkill(1,20)==0\n" + "assert skill.CanLevelUpSkill(2,0)==0 and raises(skill.CanLevelUpSkill,99,0)\n" + "assert skill.IsLevelUpSkill(1)==1 and skill.CheckRequirementSueccess(1)==1 and skill.GetNeedCharacterLevel(1)==0\n" + "assert raises(skill.GetNeedCharacterLevel,99) and raises(skill.CheckRequirementSueccess,99)\n" + "assert skill.CanUseSkill(1)==1 and skill.CanUseSkill(2)==0 and raises(skill.CanUseSkill,99)\n" + // Icons: no image assets in this mount, so NULL handles; unknown skills are 0, not errors. + "assert skill.GetIconName(1)=='' and skill.GetIconName(99)==''\n" + "assert skill.GetIconImage(99)==0 and skill.GetIconImageNew(99,0)==0\n" + "assert skill.GetIconImage(2)==0 and skill.GetIconImageNew(1,-5)==0 and skill.GetIconImageNewEx('missing.sub')==0\n" + "h=skill.GetIconInstance(1)\nh2=skill.GetIconInstanceNew(1,7)\n" + "assert h and h2 and h!=h2\n" + "skill.DeleteIconInstance(h)\nskill.DeleteIconInstance(h2)\nskill.DeleteIconInstance(h)\nskill.DeleteIconInstance(12345)\n" + "assert raises(skill.GetIconInstance,99) and raises(skill.GetIconInstanceNew,99,0)\n" + // GetGradeData: the first four bytes of the MSVC std::string (inline buffer for short names). + "assert skill.GetGradeData(1,0)==0x65736142, hex(skill.GetGradeData(1,0))\n" + "assert skill.GetGradeData(1,1)==ord('M')|ord('i')<<8|ord('d')<<16\n" + "assert skill.GetGradeData(2,0)==0x6461654C\n" // 15 chars: still the inline buffer + "assert skill.GetGradeData(131,0)==0\n" // 16+ chars: heap pointer, 0 here + "try:\n skill.GetGradeData(1,3)\n raise AssertionError\nexcept RuntimeError, e:\n assert str(e)=='Strange grade index [1]', str(e)\n" + // RegisterSkill: per-skill file relative to SetPathName; 949 keys win; no overwrite. + "skill.SetPathName('skill/')\n" + "skill.RegisterSkill(200,'fire.txt')\n" + "assert skill.GetSkillName(200)=='FireKr' and skill.GetSkillDescription(200)=='burns things'\n" + "assert skill.GetIconName(200)=='d:/ymir work/ui/skill/fire.sub'\n" + "assert skill.GetSkillMaxLevel(200)==30 and skill.GetSkillLevelUpPoint(200)==2\n" + "assert skill.GetSkillAffectDescriptionCount(200)==1\n" + "assert skill.GetGradeData(200,1)==ord('G')|ord('2')<<8\n" + "skill.RegisterSkill(1,'fire.txt')\nassert skill.GetSkillName(1)=='Base'\n" + "try:\n skill.RegisterSkill(201,'broken.txt')\n raise AssertionError\nexcept RuntimeError, e:\n" + " assert str(e)=='skill.RegisterSkill - Failed to find skill data file : 201, skill/broken.txt', str(e)\n" + "assert raises(skill.RegisterSkill,202,'nothere.txt')\n" + "skill.LoadSkillData()\nskill.ClearSkillData()\n" + "skill.TEST()\n"); + auto* fire=FindSkillDescription(200); + require(fire && fire->needWeapon==(16u|32u) && fire->attributes==((1u<<15)|1u) && fire->motion==7 && fire->motionForMe==9,"RegisterSkill fields"); + require(fire->gradeImageFiles[0]=="d:/ymir work/ui/skill/fire_01.sub" && fire->gradeImageFiles[2].empty() && + fire->imageFile=="d:/ymir work/ui/skill/fire.sub","RegisterSkill icons"); + const std::string dump=slurp(root/"test.txt"); + std::istringstream lines(dump);std::string first,line,fireRow;std::getline(lines,first); + while(std::getline(lines,line))if(line.rfind("FireKr",0)==0)fireRow=line; + // ARROW shares SWORD's bit, so the map walk prints both. + if(first!="Base\t\t\tCut\tc1\t\t\t\tTOGGLE\tARROW|BOW|SWORD\t\t2\t\t\t\t") { std::cerr<<'['< canopy0[top * 3 + 1]) top = i; + } + float top_x0 = canopy0[top * 3 + 0]; + float top_x1 = draws_t1[1].positions[top * 3 + 0]; float delta_sway = std::abs(top_x0 - top_x1); assert(delta_sway > 0.5f && "Tree canopy must visibly sway with wind"); std::cout << " -> Wind displacement at canopy tip: " << delta_sway << " units (sway verified!)" << std::endl; diff --git a/tests/switchbot_test.cpp b/tests/switchbot_test.cpp new file mode 100644 index 00000000..736e63d0 --- /dev/null +++ b/tests/switchbot_test.cpp @@ -0,0 +1,91 @@ +#include "switchbot_state.h" +#include "python_runtime.h" +#include "python_gameplay_modules.h" +#include "eter_net/PythonNetworkStream.h" +#include +#include +#include +#include +using namespace ava2; +using Bytes=std::vector; +void require(bool ok,const char* why) {if(!ok)throw std::runtime_error(why);} +void u32(Bytes& b,uint32_t v) {for(unsigned i=0;i<4;++i)b.push_back(uint8_t(v>>(8*i)));} +void u16(Bytes& b,uint16_t v) {b.push_back(uint8_t(v));b.push_back(uint8_t(v>>8));} +Bytes frame(uint8_t sub,const Bytes& data) {Bytes b{171};u32(b,uint32_t(7+data.size()));b.insert(b.end(),{sub,0});b.insert(b.end(),data.begin(),data.end());return b;} +void send(uint8_t sub,const Bytes& data) {auto& s=PythonNetworkStream::Instance();s.PushRecvData(frame(sub,data));s.ProcessRecvData();} +void attr(Bytes& data,uint8_t set,int type,int value) {data.push_back(set);u32(data,uint32_t(type));u32(data,uint32_t(value));} +void proto(const std::filesystem::path& path,uint32_t id,uint8_t type,uint8_t sub) { + // Independent172-byte AVA2 r152 record and literal LZO stream, no source assets. + Bytes raw;u32(raw,id);raw.resize(172);raw[4]='F';raw[29]='F';raw[54]=type;raw[55]=sub;raw[57]=1; + Bytes compressed{189};compressed.insert(compressed.end(),raw.begin(),raw.end());compressed.insert(compressed.end(),{17,0,0}); + Bytes payload{'M','C','O','Z'};payload.insert(payload.end(),compressed.begin(),compressed.end()); + Bytes file{'M','I','P','X'};u32(file,1);u32(file,172);u32(file,1);u32(file,uint32_t(16+payload.size())); + file.insert(file.end(),{'M','C','O','Z'});u32(file,0);u32(file,uint32_t(compressed.size()));u32(file,172);file.insert(file.end(),payload.begin(),payload.end()); + std::ofstream out(path,std::ios::binary);out.write(reinterpret_cast(file.data()),file.size()); +} +int main(int argc,char** argv) { + if(argc!=3)return 2; + auto root=std::filesystem::temp_directory_path()/std::filesystem::path("ava2-switchbot-"+std::to_string(getpid()));std::filesystem::create_directories(root); + try { + { + PythonRuntime python(argv[1],root);auto& s=PythonNetworkStream::Instance();s.ResetConnection();s.SetPhase(PHASE_GAME); + python.execute(R"PY(import switchbot as sw,player,net,item +assert sw.SLOT_COUNT==5 and sw.ALTERNATIVE_COUNT==2 +assert sw.IsActive(5)==0 and sw.IsFinished(5)==0 +assert sw.GetAttribute(5,1,4)==(0,0) +assert sw.IsActive() is None and sw.SetAttribute() is None +assert sw.GetAttributesForSet(0)==[] and sw.GetAttributeMaxValue(0,1)==0 +class Game: + def __init__(self): self.events=[] + def RefreshSwitchbotWindow(self): self.events.append('window') + def RefreshInventory(self): + assert player.GetItemCount(11,5)==700 + assert player.GetItemMetinSocket(11,5,7)==0 + self.events.append('inventory') + def RefreshSwitchbotItem(self,slot): self.events.append(('item',slot)) +game=Game() +net.SetPhaseWindow(net.PHASE_WINDOW_GAME,game) +player.SetGameWindow(game) +sw.SetAttribute(256,256,256,257,65535) +assert sw.GetAttribute(0,0,0)==(1,-1) +sw.SetAttribute(5,1,4,9,40000) +assert sw.GetAttribute(5,1,4)==(9,-25536) +assert sw.GetAttribute(0,0,5)==(0,0) and sw.GetAttribute(-1,0,0)==(0,0) +sw.Start(0) +assert sw.IsActive(0)==0 +sw.Stop(0) +)PY"); + auto packets=s.PopSendPacketsWithSequence();Bytes expected{171,37,0,0,0,0,0,1,255,255};expected.resize(37); + require(packets.size()==2 && packets[0].first==expected && packets[1].first==Bytes{171,7,0,0,0,1,0} && packets[0].second && packets[1].second,"switchbot native-less send/sequence mismatch"); + Bytes table;u32(table,123);table.insert(table.end(),{0,0,0,0,0,2,0,0,0,0,0,255});for(unsigned i=0;i<6;++i)u32(table,100+i); + for(unsigned i=0;i<60;++i) {table.push_back(uint8_t(i+1));u16(table,uint16_t(-int(i+1)));} + require(table.size()==220,"literal table size");auto wire=frame(0,table);wire.push_back(44); + s.PushRecvData(wire.data(),226);s.ProcessRecvData();python.execute("assert game.events==[]\n");s.PushRecvData(wire.data()+226,2);s.ProcessRecvData();require(s.PopSendBytes()==Bytes{254},"switchbot table consumed next ping"); + python.execute("assert sw.IsActive(5)==1 and sw.IsFinished(5)==1\nassert sw.GetAttribute(5,1,4)==(60,-60) and game.events==['window']\nsw.Stop(5)\nassert sw.IsActive(5)==1\nsw.ClearSlot(5)\nassert sw.IsActive(5)==0 and sw.IsFinished(5)==1 and sw.GetAttribute(5,1,4)==(0,0)\n");s.PopSendBytes(); + require(GetSwitchbotState().table.items[5]==0 && GetSwitchbotState().table.player_id==123,"clear slot/table state mismatch"); + TItemData item{};item.vnum=555;item.count=1;item.flags=123;SetPlayerItemData(11,5,item); + Bytes update{5};u32(update,999);u16(update,700);for(unsigned i=0;i<8;++i)u32(update,uint32_t(-int(i+1)));for(unsigned i=0;i<15;++i){update.push_back(uint8_t(i+1));u16(update,uint16_t(-int(i+10)));}send(1,update); + auto got=GetPlayerItemData(11,5);require(got.vnum==555 && got.count==700 && got.flags==123 && got.alSockets[7]==-8 && got.aAttr[14].bType==15 && got.aAttr[14].sValue==-24,"switchbot item update replaced vnum or lost extended arrays"); + python.execute("assert game.events[-2:]==['inventory',('item',5)]\n"); + Bytes attributes;for(int set=0;set<15;++set)attr(attributes,uint8_t(set),1,100+set);attr(attributes,0,4,40000);attr(attributes,0,257,999);send(2,attributes); + // Load small independent prototypes to verify actual equipped-item classification. + const std::vector> types{{1,0},{1,6},{36,0},{2,0},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,8},{2,7},{28,0},{28,1},{28,2},{28,3},{0,0}}; + const int sets[]{0,-1,11,1,5,6,2,3,4,7,13,-1,1,5,6,2,-1}; + for(size_t i=0;i +#include +#include +#include +#include +#include +#include +#include +using namespace ava2; +namespace fs = std::filesystem; +void require(bool ok,const char* why) { if(!ok)throw std::runtime_error(why); } +std::string slurp(const fs::path& p) { std::ifstream f(p,std::ios::binary);std::stringstream s;s<>(i*8)); }; + put(CPythonSystem::WINDOW_CHAT,0,1);put(CPythonSystem::WINDOW_CHAT,2,-20);put(CPythonSystem::WINDOW_CHAT,4,300); + spit(dir/"interface.cfg",std::string(reinterpret_cast(raw),sizeof(raw))); + sys.Reload(); + require(sys.GetWidth()==1280 && sys.GetHeight()==720,"cfg resolution"); + require(std::fabs(sys.GetMusicVolume()-std::pow(10.0f,-0.4f))<1e-6f,"old music volume"); + require(sys.GetSoundVolume()==4 && sys.GetShadowLevel()==2 && sys.IsSaveID()==1,"cfg ints"); + require(std::string(sys.GetSaveID())=="hero","save id"); + require(sys.IsShowOutline() && !sys.IsViewChat(),"flags are ==1"); + require(sys.GetFOVLevel()==45.5f && sys.GetShopNamesRange()==3 && sys.GetObjectDistance()==25600.0f,"floats"); + require(g_iLoadingDelayTime==7,"loading delay"); + require(sys.IsShadow(),"value-less SHOW_SHADOW reuses the previous '1'"); + require(sys.isInterfaceConfig() && sys.GetWindowStatusReference(CPythonSystem::WINDOW_CHAT).ixPosition==-20,"interface.cfg"); + require(SoundManager::Instance().GetMusicVolume()==sys.GetMusicVolume(),"ChangeSystem music volume"); + + // Display list: <800x600 and 24 bpp dropped, refresh rates merged per resolution. + sys.ClearDisplaySettings(); + sys.AddDisplayMode(640,480,32,60);sys.AddDisplayMode(1024,768,24,60); + sys.AddDisplayMode(1024,768,32,60);sys.AddDisplayMode(1280,720,32,60);sys.AddDisplayMode(1280,720,32,75); + sys.AddDisplayMode(1280,720,32,60); + require(sys.GetResolutionCount()==2 && sys.GetFrequencyCount(1)==2 && sys.GetFrequencyCount(5)==0,"display list"); + require(sys.GetResolutionIndex(1280,720,32)==1 && sys.GetResolutionIndex(1,1,32)==0 && sys.GetFrequencyIndex(1,75)==1,"indexes"); + + PythonRuntime python(argv[1],argv[2]); + python.execute( + "import systemSetting as s\n" + "assert (s.WINDOW_STATUS,s.WINDOW_MINIMAP,s.WINDOW_CHAT)==(0,8,9)\n" + "for n in ('SetCollectEquipment','IsCollectEquipment','SetFastPickup','IsEnabledFastPickup'):\n assert not hasattr(s,n),n\n" + "assert (s.GetWidth(),s.GetHeight())==(1280,720)\n" + "assert s.GetCurrentResolution()==(1280,720,32)\n" + "assert s.GetResolutionCount()==2 and s.GetResolution(1)==(1280,720,32) and s.GetResolution(9)==(0,0,0)\n" + "assert s.GetFrequency(1,1)==75 and s.GetFrequency(1,2)==0\n" + "assert s.GetWindowStatus(s.WINDOW_CHAT)==(1,0,-20,0,300)\n" + "s.SaveWindowStatus(s.WINDOW_QUICK,1,1,5,6,7)\nassert s.GetWindowStatus(s.WINDOW_QUICK)==(1,1,5,6,7)\n" + "assert s.isSaveID()==1 and s.GetSaveID()=='hero'\n" + "s.SetSaveID(0,'other')\nassert s.GetSaveID()=='hero'\n" + "s.SetSaveID(1,'abcdefghijklmnopqrstuvwxyz')\nassert s.GetSaveID()=='abcdefghijklmnopqrs'\n" + "s.SetSoundVolumef(0.5)\nassert s.GetSoundVolume()==2\n" + "s.SetMusicVolume(0.25)\nassert abs(s.GetMusicVolume()-0.25)<1e-6\n" + "s.SetShadowLevel(0)\nassert s.GetShadowLevel()==2\n" + "s.SetShadowLevel(9)\nassert s.GetShadowLevel()==5\n" + "s.SetViewChatFlag(2)\nassert s.IsViewChat()==0\ns.SetViewChatFlag(1)\nassert s.IsViewChat()==1\n" + "s.SetShowOutlineFlag(0)\nassert s.IsShowOutline()==0\n" + "s.SetShadow(1)\nassert s.IsShadow()==1\n" + "s.SetFOVLevel(120.0)\nassert s.GetFOVLevel()==100.0\ns.SetFOVLevel(10)\nassert s.GetFOVLevel()==30.0\n" + "s.SetMapObjectDistance(30000.0)\nassert s.GetMapObjectDistance()==25600.0\n" + "s.SetShopNamesRange(258)\nassert s.GetShopNamesRange()==2\n" + "s.SetQuestIconMode(5)\nassert s.GetQuestIconMode()==1\n" + "s.SetPetRender(0)\nassert s.GetPetRender()==0\n" + "s.SetDungeonTrack(1)\nassert s.GetDungeonTrack()==1\n" + "s.SetShowMobLevel(0)\nassert s.IsShowMobLevel()==0\n" + "assert s.SetViewChatFlag('x') is None\n" + // SetConfig keeps the old config on a bad resolution/frequency index. + "s.SetConfig(7,0,1,3,0,1,2,1,4)\nassert s.GetCurrentResolution()==(1280,720,32)\n" + "s.SetConfig(0,0,1,3,0,1,2,1,4)\nassert s.GetCurrentResolution()==(1024,768,32)\n" + "assert s.IsSoftwareCursor()==1 and s.GetSoundVolume()==2\n" + "assert abs(s.GetMusicVolume()-1.0)<1e-6\n" + // 32-bit varargs quirk: the double music volume fills two int slots (1.0 = 0x3FF00000:0). + "assert s.GetConfig()==(0,0,1,0,0,0x3FF00000,2,1),s.GetConfig()\n" + "class H:\n def __init__(self):\n self.n=0\n def OnSaveInterfaceStatus(self):\n self.n+=1\n s.SaveWindowStatus(s.WINDOW_STATUS,1,0,11,12,13)\n" + "h=H()\ns.SetInterfaceHandler(h)\n"); + sys.ApplyConfig(); + require(sys.GetAppliedGamma()==0.7f,"gamma 1 -> 0.7"); + sys.SaveInterfaceStatus(); + python.execute("assert h.n==1\ns.DestroyInterfaceHandler()\n"); + const std::string iface=slurp(dir/"interface.cfg"); + require(iface.size()==200 && iface[0]==1 && iface[8]==11 && iface[16]==13,"interface.cfg layout"); + require(uint8_t(iface[(9*5+2)*4])==0xEC && uint8_t(iface[(9*5+2)*4+3])==0xFF,"negative int32 LE"); + sys.SaveInterfaceStatus(); + python.execute("assert h.n==1\n"); + + python.execute("assert s.SaveConfig()==1\n"); + const std::string expected= + "WIDTH\t\t\t\t\t\t1024\nHEIGHT\t\t\t\t\t\t768\nBPP\t\t\t\t\t\t32\nFREQUENCY\t\t\t\t\t60\n" + "SOFTWARE_CURSOR\t\t\t1\nOBJECT_CULLING\t\t\t\t0\nVISIBILITY\t\t\t\t\t4\nMUSIC_VOLUME\t\t\t\t1.000\n" + "VOICE_VOLUME\t\t\t\t2\nGAMMA\t\t\t\t\t\t1\nIS_SAVE_ID\t\t\t\t\t1\nSAVE_ID\t\t\t\t\tabcdefghijklmnopqrs\n" + "PRE_LOADING_DELAY_TIME\t\t7\nDECOMPRESSED_TEXTURE\t\t0\n" + "SHOW_MOBLEVEL\t\t0\n" + "SHOW_OUTLINE\t\t\t\t0\nUSE_DEFAULT_IME\t\t0\nSOFTWARE_TILING\t\t0\nSHADOW_LEVEL\t\t\t5\n" + "SNOW_TEXTURE_MODE\t\t\t0\nSHOW_SHADOW\t\t\t\t1\nshop_range\t2\n" + "QUEST_LETTER\t\t\t\t1\nCOUNTRY_FLAG\t\t\t\t1\nAFFECT_ICONS\t\t\t\t1\nperspective\t30.0\n" + "effect_level\t0\npet_status\t0\nmount_status\t1\nnpc_status\t1\nnight_mode\t0\nspecial_message\t1\n" + "DUNGEON_TRACK\t1\nBOSS_TRACK\t0\nOBJECT_DIST\t25600.00000\n\n"; + const std::string saved=slurp(dir/"metin2.cfg"); + if(saved!=expected) { std::cerr< +#include +#include +#include + +namespace ava2_test { + +// CTest SKIP_RETURN_CODE: the run directory is not available. +constexpr int kSkip = 77; + +// Enters AVA2_TEST_RUNDIR when it is set. Returns false when it is set but +// missing (the caller should exit kSkip); unset keeps the current directory. +inline bool EnterTestRunDir() { + const char* rundir = std::getenv("AVA2_TEST_RUNDIR"); + if (!rundir || !*rundir) return true; + std::error_code ec; + if (!std::filesystem::is_directory(rundir, ec)) { + std::cerr << "SKIP: AVA2_TEST_RUNDIR " << rundir + << " missing; run tools/make_test_rundir.py" << std::endl; + return false; + } + std::filesystem::current_path(rundir, ec); + return !ec; +} + +// Decoded AVA2 pack_maker tree (Maps/, property/, Sound/...). AVA2_PACK_MAKER +// overrides the original developer path. +inline std::string PackMaker() { + if (const char* env = std::getenv("AVA2_PACK_MAKER"); env && *env) return env; + return "/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker"; +} + +} // namespace ava2_test diff --git a/tests/windows_item_oracle_test.cpp b/tests/windows_item_oracle_test.cpp index 54208eec..36ec88b8 100644 --- a/tests/windows_item_oracle_test.cpp +++ b/tests/windows_item_oracle_test.cpp @@ -63,3 +63,214 @@ static_assert(ava2::skill_constants::SKILL_GRADE_COUNT == ava2_windows_skill::SK static_assert(ava2::skill_constants::SKILL_GRADE_STEP_COUNT == ava2_windows_skill::SKILL_GRADE_STEP_COUNT); static_assert(ava2::skill_constants::SKILL_GRADEGAP == ava2_windows_skill::SKILL_GRADEGAP); static_assert(ava2::skill_constants::SKILL_EFFECT_COUNT == ava2_windows_skill::SKILL_EFFECT_COUNT); + +#include "quest_state.h" +static_assert(sizeof(ava2::TPacketGCQuestInfo)==sizeof(ava2_windows_quest::TPacketGCQuestInfo)); +static_assert(offsetof(ava2::TPacketGCQuestInfo,index)==offsetof(ava2_windows_quest::TPacketGCQuestInfo,index)); +static_assert(offsetof(ava2::TPacketGCQuestInfo,flag)==offsetof(ava2_windows_quest::TPacketGCQuestInfo,flag)); +#define QUEST_FLAG_CHECK(name) static_assert(int(ava2::name)==int(ava2_windows_quest::name)) +QUEST_FLAG_CHECK(QUEST_SEND_IS_BEGIN);QUEST_FLAG_CHECK(QUEST_SEND_TITLE); +QUEST_FLAG_CHECK(QUEST_SEND_CLOCK_NAME);QUEST_FLAG_CHECK(QUEST_SEND_CLOCK_VALUE); +QUEST_FLAG_CHECK(QUEST_SEND_COUNTER_NAME);QUEST_FLAG_CHECK(QUEST_SEND_COUNTER_VALUE); +QUEST_FLAG_CHECK(QUEST_SEND_ICON_FILE); + +#define MESSENGER_TYPE_CHECK(name) static_assert(sizeof(ava2::name)==sizeof(ava2_windows_messenger::name)) +MESSENGER_TYPE_CHECK(TPacketGCMessenger);MESSENGER_TYPE_CHECK(TPacketGCMessengerListOffline); +MESSENGER_TYPE_CHECK(TPacketGCMessengerListOnline);MESSENGER_TYPE_CHECK(TPacketGCMessengerLogin); +MESSENGER_TYPE_CHECK(TPacketGCMessengerLogout); +static_assert(offsetof(ava2::TPacketGCMessenger,subheader)==offsetof(ava2_windows_messenger::TPacketGCMessenger,subheader)); +#define MESSENGER_FLAG_CHECK(name) static_assert(int(ava2::name)==int(ava2_windows_messenger::name)) +MESSENGER_FLAG_CHECK(MESSENGER_SUBHEADER_GC_LIST);MESSENGER_FLAG_CHECK(MESSENGER_SUBHEADER_GC_LOGIN); +MESSENGER_FLAG_CHECK(MESSENGER_SUBHEADER_GC_LOGOUT);MESSENGER_FLAG_CHECK(MESSENGER_SUBHEADER_GC_INVITE); +MESSENGER_FLAG_CHECK(MESSENGER_SUBHEADER_GC_MOBILE); +MESSENGER_FLAG_CHECK(MESSENGER_CONNECTED_STATE_OFFLINE);MESSENGER_FLAG_CHECK(MESSENGER_CONNECTED_STATE_ONLINE); +MESSENGER_FLAG_CHECK(MESSENGER_CONNECTED_STATE_MOBILE); + +static_assert(sizeof(ava2::TInfoDateCubeRenewal)==sizeof(ava2_windows_cube::TInfoDateCubeRenewal)); +static_assert(sizeof(ava2::TPacketGCCubeRenewalReceive)==sizeof(ava2_windows_cube::TPacketGCCubeRenewalReceive)); +static_assert(sizeof(ava2::TPacketCGCubeRenewalSend)==sizeof(ava2_windows_cube::TPacketCGCubeRenewalSend)); +#define CUBE_FIELD_CHECK(name) static_assert(offsetof(ava2::TInfoDateCubeRenewal,name)==offsetof(ava2_windows_cube::TInfoDateCubeRenewal,name)) +CUBE_FIELD_CHECK(npc_vnum);CUBE_FIELD_CHECK(index);CUBE_FIELD_CHECK(vnum_reward);CUBE_FIELD_CHECK(count_reward); +CUBE_FIELD_CHECK(item_reward_stackable);CUBE_FIELD_CHECK(vnum_material_1);CUBE_FIELD_CHECK(count_material_1); +CUBE_FIELD_CHECK(vnum_material_2);CUBE_FIELD_CHECK(count_material_2);CUBE_FIELD_CHECK(vnum_material_3);CUBE_FIELD_CHECK(count_material_3); +CUBE_FIELD_CHECK(vnum_material_4);CUBE_FIELD_CHECK(count_material_4);CUBE_FIELD_CHECK(vnum_material_5);CUBE_FIELD_CHECK(count_material_5); +CUBE_FIELD_CHECK(gold);CUBE_FIELD_CHECK(percent);CUBE_FIELD_CHECK(category); +#define CUBE_FLAG_CHECK(name) static_assert(int(ava2::name)==int(ava2_windows_cube::name)) +CUBE_FLAG_CHECK(CUBE_RENEWAL_SUB_HEADER_OPEN_RECEIVE);CUBE_FLAG_CHECK(CUBE_RENEWAL_SUB_HEADER_CLEAR_DATES_RECEIVE); +CUBE_FLAG_CHECK(CUBE_RENEWAL_SUB_HEADER_DATES_RECEIVE);CUBE_FLAG_CHECK(CUBE_RENEWAL_SUB_HEADER_DATES_LOADING); +CUBE_FLAG_CHECK(CUBE_RENEWAL_SUB_HEADER_MAKE_ITEM);CUBE_FLAG_CHECK(CUBE_RENEWAL_SUB_HEADER_CLOSE); + +#define SEARCH_TYPE_CHECK(name) static_assert(sizeof(ava2::name)==sizeof(ava2_windows_search::name)) +SEARCH_TYPE_CHECK(TOfflineShopItemData);SEARCH_TYPE_CHECK(TPacketGCShopSearchItemSet);SEARCH_TYPE_CHECK(TPacketCGShopSearch); +#define SEARCH_ITEM_CHECK(name) static_assert(offsetof(ava2::TOfflineShopItemData,name)==offsetof(ava2_windows_search::TOfflineShopItemData,name)) +SEARCH_ITEM_CHECK(id);SEARCH_ITEM_CHECK(vnum);SEARCH_ITEM_CHECK(price);SEARCH_ITEM_CHECK(count);SEARCH_ITEM_CHECK(display_pos); +SEARCH_ITEM_CHECK(alSockets);SEARCH_ITEM_CHECK(aAttr);SEARCH_ITEM_CHECK(status);SEARCH_ITEM_CHECK(szBuyerName);SEARCH_ITEM_CHECK(owner_id); +#define SEARCH_REQUEST_CHECK(name) static_assert(offsetof(ava2::TPacketCGShopSearch,name)==offsetof(ava2_windows_search::TPacketCGShopSearch,name)) +SEARCH_REQUEST_CHECK(ItemCat);SEARCH_REQUEST_CHECK(SubCat);SEARCH_REQUEST_CHECK(searchInput);SEARCH_REQUEST_CHECK(avg); +SEARCH_REQUEST_CHECK(skill);SEARCH_REQUEST_CHECK(abs);SEARCH_REQUEST_CHECK(level);SEARCH_REQUEST_CHECK(refine); +SEARCH_REQUEST_CHECK(sex);SEARCH_REQUEST_CHECK(enchant);SEARCH_REQUEST_CHECK(alchemy);SEARCH_REQUEST_CHECK(character);SEARCH_REQUEST_CHECK(price); + +#define GUILD_TYPE_CHECK(type) static_assert(sizeof(ava2::type)==sizeof(ava2_windows_guild::type)) +GUILD_TYPE_CHECK(TPacketGCGuild);GUILD_TYPE_CHECK(TPacketGCGuildSubGrade);GUILD_TYPE_CHECK(TPacketGCGuildSubMember); +GUILD_TYPE_CHECK(TPacketGCGuildInfo);GUILD_TYPE_CHECK(TPacketGCGuildWar);GUILD_TYPE_CHECK(TPacketGuildWarPoint); +#define GUILD_FIELD(type,field) static_assert(offsetof(ava2::type,field)==offsetof(ava2_windows_guild::type,field)) +GUILD_FIELD(TPacketGCGuildSubGrade,auth_flag);GUILD_FIELD(TPacketGCGuildSubMember,dwOffer);GUILD_FIELD(TPacketGCGuildSubMember,byNameFlag); +GUILD_FIELD(TPacketGCGuildInfo,guild_id);GUILD_FIELD(TPacketGCGuildInfo,name);GUILD_FIELD(TPacketGCGuildInfo,gold);GUILD_FIELD(TPacketGCGuildInfo,hasLand); +GUILD_FIELD(TPacketGCGuildWar,bWarState);GUILD_FIELD(TPacketGuildWarPoint,lPoint); +static_assert(int(ava2::GUILD_SUBHEADER_GC_LOGIN)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_LOGIN)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_LOGOUT)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_LOGOUT)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_LIST)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_LIST)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_GRADE)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_GRADE)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_ADD)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_ADD)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_REMOVE)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_REMOVE)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_GRADE_NAME)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_GRADE_NAME)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_GRADE_AUTH)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_GRADE_AUTH)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_INFO)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_INFO)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_COMMENTS)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_COMMENTS)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_CHANGE_EXP)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_CHANGE_EXP)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_CHANGE_MEMBER_GRADE)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_CHANGE_MEMBER_GRADE)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_SKILL_INFO)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_SKILL_INFO)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_CHANGE_MEMBER_GENERAL)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_CHANGE_MEMBER_GENERAL)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_GUILD_INVITE)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_GUILD_INVITE)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_WAR)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_WAR)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_GUILD_NAME)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_GUILD_NAME)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_GUILD_WAR_LIST)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_GUILD_WAR_LIST)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_GUILD_WAR_END_LIST)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_GUILD_WAR_END_LIST)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_WAR_POINT)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_WAR_POINT)); +static_assert(int(ava2::GUILD_SUBHEADER_GC_MONEY_CHANGE)==int(ava2_windows_guild::GUILD_SUBHEADER_GC_MONEY_CHANGE)); +static_assert(int(ava2::GUILD_AUTH_ADD_MEMBER)==int(ava2_windows_guild::GUILD_AUTH_ADD_MEMBER)); +static_assert(int(ava2::GUILD_AUTH_REMOVE_MEMBER)==int(ava2_windows_guild::GUILD_AUTH_REMOVE_MEMBER)); +static_assert(int(ava2::GUILD_AUTH_NOTICE)==int(ava2_windows_guild::GUILD_AUTH_NOTICE)); +static_assert(int(ava2::GUILD_AUTH_SKILL)==int(ava2_windows_guild::GUILD_AUTH_SKILL)); +static_assert(int(ava2::GUILD_WAR_NONE)==int(ava2_windows_guild::GUILD_WAR_NONE)); +static_assert(int(ava2::GUILD_WAR_SEND_DECLARE)==int(ava2_windows_guild::GUILD_WAR_SEND_DECLARE)); +static_assert(int(ava2::GUILD_WAR_REFUSE)==int(ava2_windows_guild::GUILD_WAR_REFUSE)); +static_assert(int(ava2::GUILD_WAR_RECV_DECLARE)==int(ava2_windows_guild::GUILD_WAR_RECV_DECLARE)); +static_assert(int(ava2::GUILD_WAR_WAIT_START)==int(ava2_windows_guild::GUILD_WAR_WAIT_START)); +static_assert(int(ava2::GUILD_WAR_CANCEL)==int(ava2_windows_guild::GUILD_WAR_CANCEL)); +static_assert(int(ava2::GUILD_WAR_ON_WAR)==int(ava2_windows_guild::GUILD_WAR_ON_WAR)); +static_assert(int(ava2::GUILD_WAR_END)==int(ava2_windows_guild::GUILD_WAR_END)); +static_assert(int(ava2::GUILD_WAR_DURATION)==int(ava2_windows_guild::GUILD_WAR_DURATION)); + +#define BATTLE_TYPE(type) static_assert(sizeof(ava2::type)==sizeof(ava2_windows_battlepass::type)) +BATTLE_TYPE(TInfoBattlePassItem);BATTLE_TYPE(TInfoBattlePass);BATTLE_TYPE(TPacketGCBattlePass);BATTLE_TYPE(TPacketCGBattlePass); +static_assert(offsetof(ava2::TInfoBattlePass,items)==offsetof(ava2_windows_battlepass::TInfoBattlePass,data_item)); +#define BATTLE_FIELD(type,field) static_assert(offsetof(ava2::type,field)==offsetof(ava2_windows_battlepass::type,field)) +BATTLE_FIELD(TPacketGCBattlePass,time);BATTLE_FIELD(TPacketGCBattlePass,data);BATTLE_FIELD(TPacketCGBattlePass,index); +BATTLE_FIELD(TInfoBattlePass,count);BATTLE_FIELD(TInfoBattlePass,count_actual);BATTLE_FIELD(TInfoBattlePass,reward_status); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_OPEN)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_OPEN)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_CLEAR)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_CLEAR)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_INFO)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_INFO)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_INFO_EXTRA)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_INFO_EXTRA)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_LOADING)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_LOADING)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_REWARD)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_REWARD)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_UPDATE_CLEAR)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_UPDATE_CLEAR)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_UPDATE)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_UPDATE)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_UPDATE_LOADING)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_UPDATE_LOADING)); +static_assert(int(ava2::BATTLEPASS_SUB_HEADER_MP)==int(ava2_windows_battlepass::BATTLEPASS_SUB_HEADER_MP)); + +#define DROP_TYPE(type) static_assert(sizeof(ava2::type)==sizeof(ava2_windows_drop::type)) +DROP_TYPE(TInfoDropItemSystem);DROP_TYPE(TPacketGCDropItemReceive);DROP_TYPE(TPacketCGDropItemSend); +#define DROP_FIELD(type,field) static_assert(offsetof(ava2::type,field)==offsetof(ava2_windows_drop::type,field)) +DROP_FIELD(TInfoDropItemSystem,id_mob);DROP_FIELD(TInfoDropItemSystem,prob_item);DROP_FIELD(TInfoDropItemSystem,count_item); +DROP_FIELD(TPacketGCDropItemReceive,info_drop);DROP_FIELD(TPacketCGDropItemSend,vnum_item); +static_assert(int(ava2::DROP_ITEM_SUB_HEADER_OPEN)==int(ava2_windows_drop::DROP_ITEM_SUB_HEADER_OPEN)); +static_assert(int(ava2::DROP_ITEM_SUB_HEADER_SEARCH)==int(ava2_windows_drop::DROP_ITEM_SUB_HEADER_SEARCH)); +static_assert(int(ava2::DROP_ITEM_SUB_HEADER_OPEN_RECEIVE)==int(ava2_windows_drop::DROP_ITEM_SUB_HEADER_OPEN_RECEIVE)); +static_assert(int(ava2::DROP_ITEM_SUB_HEADER_DATES_RECEIVE)==int(ava2_windows_drop::DROP_ITEM_SUB_HEADER_DATES_RECEIVE)); +static_assert(int(ava2::DROP_ITEM_SUB_HEADER_DATES_CLEAR_RECEIVE)==int(ava2_windows_drop::DROP_ITEM_SUB_HEADER_DATES_CLEAR_RECEIVE)); +static_assert(int(ava2::DROP_ITEM_SUB_HEADER_DATES_LOADING)==int(ava2_windows_drop::DROP_ITEM_SUB_HEADER_DATES_LOADING)); + +#define DUNGEON_TYPE(type) static_assert(sizeof(ava2::type)==sizeof(ava2_windows_dungeon::type)) +DUNGEON_TYPE(TFDateInfoPacket);DUNGEON_TYPE(TFDateInfoRanking);DUNGEON_TYPE(TFDateMision);DUNGEON_TYPE(TPacketGCDungeonInfoReceive); +static_assert(sizeof(ava2::TPacketCGDungeonInfo)==sizeof(ava2_windows_dungeon::TPacketCGDungeonInfoSend)); +static_assert(offsetof(ava2::TFDateInfoPacket,id)==offsetof(ava2_windows_dungeon::TFDateInfoPacket,id_dungeon)); +#define DUNGEON_FIELD(type,field) static_assert(offsetof(ava2::type,field)==offsetof(ava2_windows_dungeon::type,field)) +DUNGEON_FIELD(TFDateInfoPacket,name);DUNGEON_FIELD(TFDateInfoPacket,respawn);DUNGEON_FIELD(TFDateInfoPacket,entrance);DUNGEON_FIELD(TFDateInfoPacket,id_boss); +DUNGEON_FIELD(TFDateInfoRanking,name_r);DUNGEON_FIELD(TFDateInfoRanking,extra_r);DUNGEON_FIELD(TFDateMision,status_mision); +DUNGEON_FIELD(TPacketGCDungeonInfoReceive,dateinfo);DUNGEON_FIELD(TPacketGCDungeonInfoReceive,dateinfo_ranking);DUNGEON_FIELD(TPacketGCDungeonInfoReceive,dateinfom); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_OPEN)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_OPEN)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_TELEPORT)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_TELEPORT)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_MISION)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_MISION)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_OPEN_SEND)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_OPEN_SEND)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_DATES_SEND)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_DATES_SEND)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_DATES_CLEAR)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_DATES_CLEAR)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_DATES_RANKING_CLEAR)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_DATES_RANKING_CLEAR)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_DATES_RANKING_SEND)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_DATES_RANKING_SEND)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_DATES_RANKING_LOAD)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_DATES_RANKING_LOAD)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_RANKING)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_RANKING)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_DATES_MISION_CLEAR)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_DATES_MISION_CLEAR)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_DATES_MISION_SEND)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_DATES_MISION_SEND)); +static_assert(int(ava2::DUNGEON_INFO_SUB_HEADER_DATES_MISION_LOAD)==int(ava2_windows_dungeon::DUNGEON_INFO_SUB_HEADER_DATES_MISION_LOAD)); + +#define SWITCH_TYPE(type) static_assert(sizeof(ava2::type)==sizeof(ava2_windows_switchbot::type)) +SWITCH_TYPE(TPacketCGSwitchbot);SWITCH_TYPE(TPacketGCSwitchbot);SWITCH_TYPE(TSwitchbotUpdateItem);SWITCH_TYPE(TSwitchbotTable);SWITCH_TYPE(TSwitchbotAttributeAlternativeTable); +static_assert(sizeof(ava2::TSwitchbotAttributeTable)==sizeof(ava2_windows_switchbot::TSwitchbottAttributeTable)); +#define SWITCH_FIELD(type,field) static_assert(offsetof(ava2::type,field)==offsetof(ava2_windows_switchbot::type,field)) +SWITCH_FIELD(TSwitchbotTable,active);SWITCH_FIELD(TSwitchbotTable,finished);SWITCH_FIELD(TSwitchbotTable,items);SWITCH_FIELD(TSwitchbotTable,alternatives); +SWITCH_FIELD(TSwitchbotUpdateItem,alSockets);SWITCH_FIELD(TSwitchbotUpdateItem,aAttr);SWITCH_FIELD(TPacketGCSwitchbot,size);SWITCH_FIELD(TPacketGCSwitchbot,slot); +static_assert(int(ava2::SWITCHBOT_SLOT_COUNT)==int(ava2_windows_switchbot::SWITCHBOT_SLOT_COUNT)); +static_assert(int(ava2::SWITCHBOT_SLOT_COUNT_REAL)==int(ava2_windows_switchbot::SWITCHBOT_SLOT_COUNT_REAL)); +static_assert(int(ava2::SWITCHBOT_ALTERNATIVE_COUNT)==int(ava2_windows_switchbot::SWITCHBOT_ALTERNATIVE_COUNT)); +static_assert(int(ava2::MAX_NORM_ATTR_NUM)==int(ava2_windows_switchbot::MAX_NORM_ATTR_NUM)); +static_assert(int(ava2::SUBHEADER_CG_SWITCHBOT_START)==int(ava2_windows_switchbot::SUBHEADER_CG_SWITCHBOT_START)); +static_assert(int(ava2::SUBHEADER_CG_SWITCHBOT_STOP)==int(ava2_windows_switchbot::SUBHEADER_CG_SWITCHBOT_STOP)); +static_assert(int(ava2::SUBHEADER_GC_SWITCHBOT_UPDATE)==int(ava2_windows_switchbot::SUBHEADER_GC_SWITCHBOT_UPDATE)); +static_assert(int(ava2::SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM)==int(ava2_windows_switchbot::SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM)); +static_assert(int(ava2::SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION)==int(ava2_windows_switchbot::SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION)); +static_assert(int(ava2::ATTRIBUTE_SET_WEAPON)==int(ava2_windows_switchbot::ATTRIBUTE_SET_WEAPON)); +static_assert(int(ava2::ATTRIBUTE_SET_BODY)==int(ava2_windows_switchbot::ATTRIBUTE_SET_BODY)); +static_assert(int(ava2::ATTRIBUTE_SET_WRIST)==int(ava2_windows_switchbot::ATTRIBUTE_SET_WRIST)); +static_assert(int(ava2::ATTRIBUTE_SET_FOOTS)==int(ava2_windows_switchbot::ATTRIBUTE_SET_FOOTS)); +static_assert(int(ava2::ATTRIBUTE_SET_NECK)==int(ava2_windows_switchbot::ATTRIBUTE_SET_NECK)); +static_assert(int(ava2::ATTRIBUTE_SET_HEAD)==int(ava2_windows_switchbot::ATTRIBUTE_SET_HEAD)); +static_assert(int(ava2::ATTRIBUTE_SET_SHIELD)==int(ava2_windows_switchbot::ATTRIBUTE_SET_SHIELD)); +static_assert(int(ava2::ATTRIBUTE_SET_EAR)==int(ava2_windows_switchbot::ATTRIBUTE_SET_EAR)); +static_assert(int(ava2::ATTRIBUTE_SET_COSTUME_BODY)==int(ava2_windows_switchbot::ATTRIBUTE_SET_COSTUME_BODY)); +static_assert(int(ava2::ATTRIBUTE_SET_COSTUME_HEAD)==int(ava2_windows_switchbot::ATTRIBUTE_SET_COSTUME_HEAD)); +static_assert(int(ava2::ATTRIBUTE_SET_COSTUME_WEAPON)==int(ava2_windows_switchbot::ATTRIBUTE_SET_COSTUME_WEAPON)); +static_assert(int(ava2::ATTRIBUTE_SET_NEW_RINGS)==int(ava2_windows_switchbot::ATTRIBUTE_SET_NEW_RINGS)); +static_assert(int(ava2::ATTRIBUTE_SET_GLOVE)==int(ava2_windows_switchbot::ATTRIBUTE_SET_GLOVE)); +static_assert(int(ava2::ATTRIBUTE_SET_PENDANT)==int(ava2_windows_switchbot::ATTRIBUTE_SET_PENDANT)); +static_assert(int(ava2::ATTRIBUTE_SET_MAX_NUM)==int(ava2_windows_switchbot::ATTRIBUTE_SET_MAX_NUM)); + +#define ISHOP_TYPE(type) static_assert(sizeof(ava2::type)==sizeof(ava2_windows_itemshop::type)) +ISHOP_TYPE(TIShopData);ISHOP_TYPE(TIShopLogData);ISHOP_TYPE(TPacketGCItemShop); +#define ISHOP_FIELD(type,field) static_assert(offsetof(ava2::type,field)==offsetof(ava2_windows_itemshop::type,field)) +ISHOP_FIELD(TIShopData,itemPrice);ISHOP_FIELD(TIShopData,discount);ISHOP_FIELD(TIShopData,offerTime);ISHOP_FIELD(TIShopData,sellCount);ISHOP_FIELD(TIShopData,maxSellCount); +ISHOP_FIELD(TIShopLogData,playerName);ISHOP_FIELD(TIShopLogData,buyDate);ISHOP_FIELD(TIShopLogData,buyTime);ISHOP_FIELD(TIShopLogData,ipAdress);ISHOP_FIELD(TIShopLogData,itemPrice); +static_assert(int(ava2::ITEMSHOP_LOAD)==int(ava2_windows_itemshop::ITEMSHOP_LOAD)); +static_assert(int(ava2::ITEMSHOP_LOG)==int(ava2_windows_itemshop::ITEMSHOP_LOG)); +static_assert(int(ava2::ITEMSHOP_BUY)==int(ava2_windows_itemshop::ITEMSHOP_BUY)); +static_assert(int(ava2::ITEMSHOP_DRAGONCOIN)==int(ava2_windows_itemshop::ITEMSHOP_DRAGONCOIN)); +static_assert(int(ava2::ITEMSHOP_RELOAD)==int(ava2_windows_itemshop::ITEMSHOP_RELOAD)); +static_assert(int(ava2::ITEMSHOP_LOG_ADD)==int(ava2_windows_itemshop::ITEMSHOP_LOG_ADD)); +static_assert(int(ava2::ITEMSHOP_UPDATE_ITEM)==int(ava2_windows_itemshop::ITEMSHOP_UPDATE_ITEM)); + +#define OFFLINE_TYPE_CHECK(name) static_assert(sizeof(ava2::name)==sizeof(ava2_windows_offline_shop::name)) +OFFLINE_TYPE_CHECK(TPacketGCShop);OFFLINE_TYPE_CHECK(TShopLog);OFFLINE_TYPE_CHECK(TShopDecoration); +OFFLINE_TYPE_CHECK(TOfflineShopItemTable);OFFLINE_TYPE_CHECK(TPacketCGMyOfflineShop); +OFFLINE_TYPE_CHECK(TPacketGCOfflineShopStart);OFFLINE_TYPE_CHECK(TPacketGCOfflineShopUpdateItem); +#define OFFLINE_ENUM_CHECK(name) static_assert(int(ava2::name)==int(ava2_windows_offline_shop::name)) +OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_START);OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_END); +OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_UPDATE_ITEM);OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY); +OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_SOLD_OUT);OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_INVENTORY_FULL); +OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_INVALID_POS);OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_REFRESH_MONEY); +OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_CHECK_RESULT);OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_REFRESH_DISPLAY_COUNT); +OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_REALWATCHER_COUNT);OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_REFRESH_COUNT); +OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_CHANGE_TITLE);OFFLINE_ENUM_CHECK(SHOP_SUBHEADER_GC_NOT_ENOUGH_LUCKY); +#define OFFLINE_OFFSET_CHECK(type,field) static_assert(offsetof(ava2::type,field)==offsetof(ava2_windows_offline_shop::type,field)) +OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopStart,items);OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopStart,title); +OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopStart,log);OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopStart,flag); +OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopStart,IsOwner);OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopUpdateItem,item); +OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopUpdateItem,title);OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopUpdateItem,price); +OFFLINE_OFFSET_CHECK(TPacketGCOfflineShopUpdateItem,log);OFFLINE_OFFSET_CHECK(TOfflineShopItemTable,price); +OFFLINE_OFFSET_CHECK(TPacketCGMyOfflineShop,shopVnum);OFFLINE_OFFSET_CHECK(TShopDecoration,vnum); + +#include "item_sound.h" +#define ITEM_SOUND_ENUM_CHECK(name) static_assert(int(ava2::name)==int(ava2_windows_item_sound::name)) +ITEM_SOUND_ENUM_CHECK(USESOUND_NONE);ITEM_SOUND_ENUM_CHECK(USESOUND_DEFAULT);ITEM_SOUND_ENUM_CHECK(USESOUND_ARMOR); +ITEM_SOUND_ENUM_CHECK(USESOUND_WEAPON);ITEM_SOUND_ENUM_CHECK(USESOUND_BOW);ITEM_SOUND_ENUM_CHECK(USESOUND_ACCESSORY); +ITEM_SOUND_ENUM_CHECK(USESOUND_POTION);ITEM_SOUND_ENUM_CHECK(USESOUND_PORTAL);ITEM_SOUND_ENUM_CHECK(USESOUND_NUM); +ITEM_SOUND_ENUM_CHECK(DROPSOUND_DEFAULT);ITEM_SOUND_ENUM_CHECK(DROPSOUND_ARMOR);ITEM_SOUND_ENUM_CHECK(DROPSOUND_WEAPON); +ITEM_SOUND_ENUM_CHECK(DROPSOUND_BOW);ITEM_SOUND_ENUM_CHECK(DROPSOUND_ACCESSORY);ITEM_SOUND_ENUM_CHECK(DROPSOUND_NUM); diff --git a/tools/audit_ava2_packet_constants.py b/tools/audit_ava2_packet_constants.py index c133f70c..61645897 100644 --- a/tools/audit_ava2_packet_constants.py +++ b/tools/audit_ava2_packet_constants.py @@ -21,7 +21,7 @@ for body in re.findall(r'\benum\s*\w*\s*\{(.*?)\}',processed,re.S): aliases={'HEADER_CG_CHARACTER_CREATE':'HEADER_CG_PLAYER_CREATE','HEADER_CG_CHARACTER_DELETE':'HEADER_CG_PLAYER_DESTROY','HEADER_CG_MOVE':'HEADER_CG_CHARACTER_MOVE','HEADER_CG_CHARACTER_SELECT':'HEADER_CG_PLAYER_SELECT','HEADER_GC_CHARACTER_CREATE_SUCCESS':'HEADER_GC_PLAYER_CREATE_SUCCESS','HEADER_GC_CHARACTER_CREATE_FAILURE':'HEADER_GC_PLAYER_CREATE_FAILURE','HEADER_GC_CHARACTER_DELETE_SUCCESS':'HEADER_GC_PLAYER_DELETE_SUCCESS','PHASE_OFFLINE':'PHASE_CLOSE'} port=(root/'src/eter_net/Packet.h').read_text() checked=[];mismatches=[];unmatched=[] -for name,value in re.findall(r'\b((?:HEADER_[CG][GC]_|PHASE_|EXCHANGE_SUBHEADER_)[A-Z0-9_]+)\s*=\s*(0x[0-9a-fA-F]+|\d+)',port): +for name,value in re.findall(r'\b((?:HEADER_[CG][GC]_|PHASE_|EXCHANGE_SUBHEADER_|MESSENGER_SUBHEADER_CG_|GUILD_SUBHEADER_CG_)[A-Z0-9_]+)\s*=\s*(0x[0-9a-fA-F]+|\d+)',port): reference=aliases.get(name,name) if reference not in values: unmatched.append(name);continue row={'name':name,'windows_name':reference,'windows':values[reference],'port':int(value,0)} diff --git a/tools/audit_ava2_python_interfaces.py b/tools/audit_ava2_python_interfaces.py index 944488b7..912ce165 100644 --- a/tools/audit_ava2_python_interfaces.py +++ b/tools/audit_ava2_python_interfaces.py @@ -19,16 +19,29 @@ def modules(paths,preprocess=False): for call in re.finditer(r'Py_InitModule\s*\(\s*"([^"\n]+)"\s*,\s*(\w+)',source): candidates=[t for t in tables if t[1]==call[2] and t.start(){}]*>)?)\s*,',candidates[-1][2])} + if call[1] in result: + result[call[1]]['methods'].update(methods) + else: + result[call[1]]={'path':str(path.relative_to(root)),'methods':methods} return result -windows=modules(sorted((root/'upstream/ava2-client').rglob('*Module.cpp')),True) +# Only translation units listed in AVA2's Windows build are reference modules. +# Orphan .cpp files (e.g. guild_ranking) do not define the shipped client API. +import xml.etree.ElementTree as ET +compiled=set() +for project in (root/'upstream/ava2-client').rglob('*.vcxproj'): + for node in ET.parse(project).getroot().iter(): + if node.tag.rsplit('}',1)[-1]=='ClCompile' and 'Include' in node.attrib: + compiled.add((project.parent/node.attrib['Include'].replace('\\','/')).resolve()) +reference_paths=[p for p in sorted(compiled) if p.is_file() and + re.search(r'\bPy_InitModule\s*\(',p.read_text(errors='replace'))] +windows=modules(reference_paths,True) port=modules(sorted((root/'src').glob('python_*.cpp'))) rows=[] for name,reference in sorted(windows.items()): target=port.get(name,{'methods':{}});original=set(reference['methods']);current=set(target['methods']) rows.append({'module':name,'windows_file':reference['path'],'port_file':target.get('path'),'windows_methods':len(original),'missing':sorted(original-current),'extra':sorted(current-original),'placeholder':sorted(method for method in original¤t if 'dummy' in target['methods'][method])}) -report={'basis':'AVA2 Windows active method tables; module constants/signatures/behavior require further audit','modules':rows,'missing_method_count':sum(len(r['missing']) for r in rows),'placeholder_method_count':sum(len(r['placeholder']) for r in rows)} +report={'basis':'AVA2 Windows project-compiled active method tables; module constants/signatures/behavior require further audit','modules':rows,'missing_method_count':sum(len(r['missing']) for r in rows),'placeholder_method_count':sum(len(r['placeholder']) for r in rows)} (root/'docs/AVA2-PYTHON-INTERFACES.json').write_text(json.dumps(report,indent=2)+'\n') print(f"{len(rows)} Windows modules compared; {report['missing_method_count']} missing methods; {report['placeholder_method_count']} overlapping placeholder methods") for row in rows: diff --git a/tools/generate_ava2_gc_packet_table.py b/tools/generate_ava2_gc_packet_table.py new file mode 100644 index 00000000..f046fd5c --- /dev/null +++ b/tools/generate_ava2_gc_packet_table.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Generate src/eter_net/Ava2GcPacketTable.inc from the AVA2 Windows reference. + +Source of truth: + * UserInterface/PythonNetworkStream.cpp CMainPacketHeaderMap (header -> size, static/dynamic) + * UserInterface/PythonNetworkStreamPhaseGame.cpp GamePhase() switch (headers with a handler) + * UserInterface/Packet.h + Locale_inc.h struct layouts and feature defines + +sizeof() is evaluated by clang for i686-pc-windows-msvc (the Win32 client ABI) with +_USE_32BIT_TIME_T semantics (StdAfx.h), so the table is the Win32 wire size, not a +guess. Only constants used by Packet.h are stubbed; they are copied from the reference. +""" +import json +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +root = Path(__file__).resolve().parents[1] +ui = root / "upstream/ava2-client/UserInterface" +out = root / "src/eter_net/Ava2GcPacketTable.inc" + + +def ascii_text(path): + return re.sub(r"[^\t\n\r\x20-\x7e]", "", path.read_bytes().decode("latin1")) + + +PRELUDE = """ +#include +typedef uint8_t BYTE; typedef uint16_t WORD; typedef uint32_t DWORD; typedef int32_t LONG; +typedef int BOOL; typedef uint32_t UINT; typedef int INT; typedef int64_t LONGLONG; +typedef uint64_t ULONGLONG; typedef int16_t SHORT; typedef char CHAR; typedef float FLOAT; +#define NULL 0 +typedef int time_t; /* StdAfx.h: _USE_32BIT_TIME_T */ +typedef unsigned int size_t; +extern "C" void* memset(void*, int, size_t); extern "C" float sqrtf(float); +class CResource {}; struct TPixelPosition { float x, y, z; }; +namespace std { template struct vector { T* a; T* b; T* c; }; struct string { char b[24]; }; + template struct map {}; template struct pair { A first; B second; }; } +/* UserInterface/StdAfx.h */ +enum { POINT_MAX_NUM = 255, CHARACTER_NAME_MAX_LEN = 24, PLAYER_NAME_MAX_LEN = 12 }; +""" + +# GameLib/ItemData.h CItemData enum values referenced by Packet.h / GameType.h +ITEMDATA = """#pragma once +class CItemData { public: enum { ITEM_NAME_MAX_LEN = 24, ITEM_LIMIT_MAX_NUM = 2, ITEM_VALUES_MAX_NUM = 6, + ITEM_APPLY_MAX_NUM = 3, ITEM_SOCKET_MAX_NUM = 8, WEAR_MAX_NUM = 32, DS_SLOT_NUM_TYPES = 6 }; }; +""" + + +def header_map_body(): + text = ascii_text(ui / "PythonNetworkStream.cpp") + start = text.index("CMainPacketHeaderMap()") + body_start = text.index("{", start) + 1 + end = text.index("\n};", body_start) + body = text[body_start:end].rstrip() + assert body.endswith("}") + return body[:-1] + + +def game_switch_body(): + text = ascii_text(ui / "PythonNetworkStreamPhaseGame.cpp") + start = text.index("void CPythonNetworkStream::GamePhase()") + end = text.index("RecvDefaultPacket(header)", start) + lines = [] + body = re.sub(r"/\*.*?\*/", "", text[start:end], flags=re.S) + for line in body.splitlines(): + s = line.split("//", 1)[0].strip() + if re.match(r"#\s*(if|ifdef|ifndef|else|elif|endif)\b", s): + lines.append(s) + else: + for m in re.finditer(r"case\s+(HEADER_GC_\w+)\s*:", s): + lines.append(f"handled[{m.group(1)}] = 1;") + return "\n".join(lines) + + +GEN = """#include "Locale_inc.h" +#include "GameType.h" +#include "Packet.h" +struct CNetworkPacketHeaderMap { struct TPacketType { int s, d; constexpr TPacketType(int a = 0, int b = 0) : s(a), d(b) {} }; }; +struct Table { + enum { STATIC_SIZE_PACKET = 0, DYNAMIC_SIZE_PACKET = 1 }; + int size[256] = {}; int dyn[256] = {}; int set[256] = {}; int handled[256] = {}; + constexpr void Set(int h, CNetworkPacketHeaderMap::TPacketType t) { size[h] = t.s; dyn[h] = t.d; set[h] = 1; } + constexpr Table() { +#include "map.inc" +#include "switch.inc" + } +}; +extern "C" const Table exported_table = Table(); +""" + + +def main(): + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / "x").mkdir() + (tmp / "GameLib").mkdir() + for name in ("Packet.h", "GameType.h", "Locale_inc.h"): + (tmp / "x" / name).write_bytes((ui / name).read_bytes()) + (tmp / "x" / "Locale.h").write_text("") + (tmp / "GameLib" / "ItemData.h").write_text(ITEMDATA) + (tmp / "GameLib" / "RaceData.h").write_text("") + (tmp / "prelude.h").write_text(PRELUDE) + (tmp / "map.inc").write_text(header_map_body()) + (tmp / "switch.inc").write_text(game_switch_body()) + (tmp / "gen.cpp").write_text(GEN) + cmd = ["clang++", "-target", "i686-pc-windows-msvc", "-fms-extensions", "-fms-compatibility", + "-std=c++17", "-S", "-emit-llvm", "-o", str(tmp / "gen.ll"), "-I", str(tmp / "x"), + "-I", str(tmp), "-include", str(tmp / "prelude.h"), str(tmp / "gen.cpp")] + subprocess.run(cmd, check=True) + ir = (tmp / "gen.ll").read_text() + line = next(l for l in ir.splitlines() if l.startswith("@exported_table")) + values = [] + for m in re.finditer(r"\[(\d+) x i32\] zeroinitializer|(? {out.relative_to(root)}") + + +if __name__ == "__main__": + main() diff --git a/tools/generate_ava2_item_oracle.py b/tools/generate_ava2_item_oracle.py index dd61a38c..1281d24f 100644 --- a/tools/generate_ava2_item_oracle.py +++ b/tools/generate_ava2_item_oracle.py @@ -6,9 +6,9 @@ root=Path(__file__).resolve().parents[1] packet=(root/'upstream/ava2-client/UserInterface/Packet.h').read_text(errors='replace') game=(root/'upstream/ava2-client/UserInterface/GameType.h').read_text(errors='replace') def decl(source,name): - matches=re.findall(r'typedef struct '+name+r'\s*\{.*?\}\s*\w+\s*;',source,re.S) + matches=re.findall(r'typedef\s+struct\s+'+name+r'\s*\{.*?\}\s*\w+\s*;',source,re.S) assert matches,name - return matches[-1].replace('long long','std::int64_t').replace('long','std::int32_t').replace('CItemData::ITEM_NAME_MAX_LEN','24') + return matches[-1].replace('unsigned long long','std::uint64_t').replace('long long','std::int64_t').replace('long','std::int32_t').replace('CItemData::ITEM_NAME_MAX_LEN','24') constants=game[game.index('enum\n{\n\tITEM_SOCKET_SLOT_MAX_NUM'):] constants=constants[:constants.index('\n};')+3] stdafx=(root/'upstream/ava2-client/UserInterface/StdAfx.h').read_text(errors='replace') @@ -42,4 +42,58 @@ for name in ('ITEM_NAME_MAX_LEN','ITEM_LIMIT_MAX_NUM','ITEM_APPLY_MAX_NUM','ITEM assert value,name item_constants+='constexpr int '+name+'='+value.group(1)+';\n' text+='namespace ava2_windows_proto {using BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;\n'+item_constants+'#pragma pack(push,1)\n'+item_decls+'\n#pragma pack(pop)\n}\n' +quest_flags=re.search(r'enum\s*\{\s*QUEST_SEND_IS_BEGIN.*?\};',packet,re.S) +assert quest_flags +text+='namespace ava2_windows_quest { using BYTE=std::uint8_t;using WORD=std::uint16_t;\n'+quest_flags.group()+'\n#pragma pack(push,1)\n'+decl(packet,'packet_quest_info')+'\n#pragma pack(pop)\n}\n' +messenger_decls='\n'.join(decl(packet,name) for name in ('packet_messenger','packet_messenger_list_offline','packet_messenger_list_online','packet_messenger_login','packet_messenger_logout')) +messenger_enums=[] +for start in ('MESSENGER_SUBHEADER_GC_LIST','MESSENGER_CONNECTED_STATE_OFFLINE'): + match=re.search(r'enum\s*\{\s*'+start+r'.*?\};',packet,re.S) + assert match,start + messenger_enums.append(match.group()) +text+='namespace ava2_windows_messenger {using BYTE=std::uint8_t;using WORD=std::uint16_t;\n'+'\n'.join(messenger_enums)+'\n#pragma pack(push,1)\n'+messenger_decls+'\n#pragma pack(pop)\n}\n' +cube_enum=re.search(r'enum\s*\{\s*CUBE_RENEWAL_SUB_HEADER_OPEN_RECEIVE.*?\};',packet,re.S) +assert cube_enum +cube_decls='\n'.join(decl(packet,name) for name in ('packet_send_cube_renewal','dates_cube_renewal','packet_receive_cube_renewal')) +text+='namespace ava2_windows_cube {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr BYTE HEADER_GC_CUBE_RENEWAL=221;\n'+cube_enum.group()+'\n#pragma pack(push,1)\n'+cube_decls+'\n#pragma pack(pop)\n}\n' +search_decls='\n'.join(decl(packet,name) for name in ('packet_offline_shop_item','packet_priv_shop_item_set','command_shop_search')) +text+='namespace ava2_windows_search {using BYTE=std::uint8_t;using DWORD=std::uint32_t;using TPlayerItemAttribute=ava2_windows_item::TPlayerItemAttribute;constexpr int ITEM_SOCKET_SLOT_MAX_NUM=ava2_windows_item::ITEM_SOCKET_SLOT_MAX_NUM,ITEM_ATTRIBUTE_SLOT_MAX_NUM=ava2_windows_item::ITEM_ATTRIBUTE_SLOT_MAX_NUM,CHARACTER_NAME_MAX_LEN=24;\n#pragma pack(push,1)\n'+search_decls+'\n#pragma pack(pop)\n}\n' +guild_decls='\n'.join(decl(packet,name) for name in ('packet_guild','packet_guild_sub_grade','packet_guild_sub_member','packet_guild_sub_info','packet_guild_war','SPacketGuildWarPoint')) +guild_enums='\n'.join(re.search(r'enum(?: EGuildWarState)?\s*\{\s*'+start+r'.*?\};',packet,re.S).group() for start in ('GUILD_SUBHEADER_GC_LOGIN','GUILD_AUTH_ADD_MEMBER','GUILD_WAR_NONE')) +text+='namespace ava2_windows_guild {using BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;constexpr int GUILD_NAME_MAX_LEN=12,GUILD_GRADE_NAME_MAX_LEN=8;\n'+guild_enums+'\n#pragma pack(push,1)\n'+guild_decls+'\n#pragma pack(pop)\n}\n' +battle_enum=re.search(r'enum\s*\{\s*BATTLEPASS_SUB_HEADER_OPEN.*?\};',packet,re.S) +assert battle_enum +battle_decls='\n'.join(decl(packet,name) for name in ('info_item_battlepass','info_battlepass','packet_cg_battlepass','packet_gc_battlepass')) +text+='namespace ava2_windows_battlepass {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr BYTE HEADER_GC_BATTLEPASS=230;\n'+battle_enum.group()+'\n#pragma pack(push,1)\n'+battle_decls+'\n#pragma pack(pop)\n}\n' +drop_enum=re.search(r'enum\s*\{\s*DROP_ITEM_SUB_HEADER_OPEN.*?\};',packet,re.S) +assert drop_enum +drop_decls='\n'.join(decl(packet,name) for name in ('packet_send_drop_item_system','info_drop_item_system','packet_receive_drop_item_system')) +text+='namespace ava2_windows_drop {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr BYTE HEADER_GC_DROP_ITEM_SYSTEM=220;\n'+drop_enum.group()+'\n#pragma pack(push,1)\n'+drop_decls+'\n#pragma pack(pop)\n}\n' +dungeon_enum=re.search(r'enum\s*\{\s*DUNGEON_INFO_SUB_HEADER_OPEN.*?\};',packet,re.S) +assert dungeon_enum +dungeon_decls='\n'.join(decl(packet,name) for name in ('packet_send_dungeon_info_system','SFDateInfoPacket','SFDateRanking','SFDateMision','SPacketGCDungeonInfoReceive')) +text+='namespace ava2_windows_dungeon {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr BYTE HEADER_GC_DUNGEON_INFO_SYSTEM=217;\n'+dungeon_enum.group()+'\n#pragma pack(push,1)\n'+dungeon_decls+'\n#pragma pack(pop)\n}\n' +switch=(root/'upstream/ava2-client/UserInterface/PythonSwitchbot.h').read_text(errors='replace') +switch_decls=[] +for name in ('TSwitchbotAttributeAlternativeTable','TSwitchbotTable','TSwitchbottAttributeTable'): + found=re.search(r'struct '+name+r'\s*\{.*?\};',switch,re.S) + assert found,name + switch_decls.append(found.group().replace('long','std::int32_t')) +for name in ('TPacketCGSwitchbot','TPacketGCSwitchbot','TSwitchbotUpdateItem'): + found=re.search(r'struct '+name+r'\s*\{.*?\};',packet,re.S) + assert found,name + switch_decls.append(found.group().replace('long','std::int32_t')) +switch_enums='\n'.join(re.search(r'enum '+name+r'\s*\{.*?\};',source,re.S).group() for source,name in ((game,'ESwitchbotValues'),(game,'EAttributeSet'),(packet,'ECGSwitchbotSubheader'),(packet,'EGCSwitchbotSubheader'))) +text+='namespace ava2_windows_switchbot {using BYTE=std::uint8_t;using DWORD=std::uint32_t;using WORD=std::uint16_t;using TPlayerItemAttribute=ava2_windows_item::TPlayerItemAttribute;constexpr int ITEM_SOCKET_SLOT_MAX_NUM=8,ITEM_ATTRIBUTE_SLOT_MAX_NUM=15;\n'+switch_enums+'\n#pragma pack(push,1)\n'+'\n'.join(switch_decls)+'\n#pragma pack(pop)\n}\n' +ishop_enum=re.search(r'enum\s*\{\s*ITEMSHOP_LOAD.*?\};',packet,re.S) +assert ishop_enum +ishop_decls='\n'.join(decl(packet,name) for name in ('SIShopData','SIShopLogData','SPacketGCItemShop')) +text+='namespace ava2_windows_itemshop {using BYTE=std::uint8_t;using DWORD=std::uint32_t;constexpr int CHARACTER_NAME_MAX_LEN=24;\n'+ishop_enum.group()+'\n#pragma pack(push,1)\n'+ishop_decls+'\n#pragma pack(pop)\n}\n' +offline_enum=re.search(r'enum EPacketShopSubHeaders\s*\{.*?\};',packet,re.S) +assert offline_enum +offline_decls='\n'.join(decl(packet,name) for name in ('packet_shop','ShopLog','SShopDecoration','SOfflineShopItemTable','SPacketCGMyOfflineShop','packet_offline_shop_start','packet_offline_shop_update_item')) +text+='namespace ava2_windows_offline_shop {using BYTE=std::uint8_t;using WORD=std::uint16_t;using DWORD=std::uint32_t;using TItemPos=ava2_windows_item::TItemPos;using TOfflineShopItemData=ava2_windows_search::TOfflineShopItemData;constexpr int CHARACTER_NAME_MAX_LEN=24,SHOP_SIGN_MAX_LEN=45,OFFLINE_SHOP_HOST_ITEM_MAX_NUM=80;\n'+offline_enum.group()+'\n#pragma pack(push,1)\n'+offline_decls+'\n#pragma pack(pop)\n}\n' +python_item=(root/'upstream/ava2-client/UserInterface/PythonItem.h').read_text(errors='replace') +sound_enums='\n'.join(re.search(r'enum\s*\{\s*'+start+r'.*?\};',python_item,re.S).group() for start in ('USESOUND_NONE','DROPSOUND_DEFAULT')) +text+='namespace ava2_windows_item_sound {\n'+sound_enums+'\n}\n' out=Path(sys.argv[1]);out.parent.mkdir(parents=True,exist_ok=True);out.write_text(text) diff --git a/tools/make_test_rundir.py b/tools/make_test_rundir.py new file mode 100644 index 00000000..4036b0ce --- /dev/null +++ b/tools/make_test_rundir.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Build a client-root style run directory for asset-backed tests. + +The decoded AVA2 pack_maker tree keeps each pack in its own folder, and each +pack's _create.xml lists the root-relative path ("ArchivedPath") the +Windows pack manager serves for every file (d:/ymir work/pc/..., icon/item/..., +locale/es/ui/...). This rebuilds that single root out of per-file symlinks, +without copying any asset: + + 1. every upstream/python-root file (the repository's scripts win) + 2. every *_create.xml entry, "d:/" stripped; packs PC, ETC, root first, then + the rest alphabetically; first file wins, names compared case-insensitively + 3. map -> pack_maker/Maps (tests read map/metin2_map_a1/...) + mark, svside -> pack_maker/../ (loose client-root folders, not in any pack) + +The output is generated data: keep it out of the repository (default +build/dev/test-rundir, which CMake passes to the tests as AVA2_TEST_RUNDIR). + +usage: tools/make_test_rundir.py [--pack-maker DIR] [--python-root DIR] [--out DIR] +""" + +import argparse +import os +import re +import shutil +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +MARKER = ".ava2_test_rundir" +FIRST_PACKS = ["PC", "ETC", "root"] +DIR_LINKS = { + "map": "Maps", + "mark": "../mark", + "svside": "../svside", +} +MANIFEST_ENTRY = re.compile(r'ArchivedPath="([^"]*)">') + + +def pack_manifests(pack_maker): + packs = sorted(p.name[: -len("_create.xml")] for p in pack_maker.glob("*_create.xml")) + first = [p for p in FIRST_PACKS if p in packs] + for pack in first + [p for p in packs if p not in first]: + yield pack_maker / f"{pack}_create.xml" + + +class RunDir: + """Per-file symlink tree; the first file for a case-insensitive path wins.""" + + def __init__(self, out): + self.out = out + self.dirs = {"": out} # lower-case relative dir -> real directory + self.files = set() + + def _dir(self, parts): + key = "" + for part in parts: + parent = self.dirs[key] + key = f"{key}/{part.lower()}" if key else part.lower() + if key not in self.dirs: + self.dirs[key] = parent / part + self.dirs[key].mkdir() + return self.dirs[key] + + def add(self, rel, source): + parts = [p for p in rel.replace("\\", "/").split("/") if p] + key = "/".join(parts).lower() + if not parts or key in self.files or key in self.dirs: + return False + self.files.add(key) + os.symlink(source, self._dir(parts[:-1]) / parts[-1]) + return True + + +def archived_root_path(archived): + archived = archived.replace("\\", "/") + return archived[3:] if archived.lower().startswith("d:/") else archived + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--pack-maker", type=Path, + default=ROOT.parent / "AVA2" / "TEST" / "1. Client DEV" / "pack_maker") + ap.add_argument("--python-root", type=Path, default=ROOT / "upstream" / "python-root") + ap.add_argument("--out", type=Path, default=ROOT / "build" / "dev" / "test-rundir") + args = ap.parse_args() + + pack_maker = args.pack_maker.resolve() + out = args.out.resolve() + if not pack_maker.is_dir(): + sys.exit(f"pack_maker not found: {pack_maker}") + + # Only ever replace a directory this script made. + if out.exists(): + if not (out / MARKER).exists(): + sys.exit(f"refusing to replace {out}: not made by this script (no {MARKER})") + shutil.rmtree(out) + out.mkdir(parents=True) + (out / MARKER).write_text(f"pack_maker={pack_maker}\n") + + tree = RunDir(out) + linked = 0 + python_root = args.python_root.resolve() + if python_root.is_dir(): + for dirpath, _dirnames, filenames in os.walk(python_root): + for name in sorted(filenames): + source = Path(dirpath) / name + linked += tree.add(source.relative_to(python_root).as_posix(), source) + else: + print(f"warning: missing {python_root}", file=sys.stderr) + + for manifest in pack_manifests(pack_maker): + text = manifest.read_text(encoding="latin-1") + for archived, source in MANIFEST_ENTRY.findall(text): + # CDATA sources are relative to the directory holding pack_maker. + source = pack_maker.parent / source + if source.is_file(): + linked += tree.add(archived_root_path(archived), source) + + for name, rel in DIR_LINKS.items(): + target = (pack_maker / rel).resolve() + if target.is_dir() and name not in tree.dirs: + os.symlink(target, out / name) + else: + print(f"warning: not linking {name} -> {target}", file=sys.stderr) + + print(f"{out}: {linked} files linked") + + +if __name__ == "__main__": + main()