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 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-08 10:43:01 +09:00
co-authored by Claude Opus 5.5
parent 9f748eb05a
commit 9077aa389a
145 changed files with 22692 additions and 6584 deletions
+3
View File
@@ -4,3 +4,6 @@ build/
__pycache__/ __pycache__/
*.pyc *.pyc
*.pyo *.pyo
# CPythonSystem runtime option files (Windows writes them next to the client)
metin2.cfg
interface.cfg
+116 -5
View File
@@ -21,7 +21,7 @@ find_package(SDL3 CONFIG REQUIRED)
add_library(ava2_transport src/login_client.cpp) add_library(ava2_transport src/login_client.cpp)
target_include_directories(ava2_transport PUBLIC src) target_include_directories(ava2_transport PUBLIC src)
target_link_libraries(ava2_transport PUBLIC ava2_protocol Threads::Threads) 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_include_directories(ava2_render PUBLIC src ${CMAKE_CURRENT_SOURCE_DIR} third_party/extern_include)
target_link_libraries(ava2_render PUBLIC libgr2 SDL3::SDL3) target_link_libraries(ava2_render PUBLIC libgr2 SDL3::SDL3)
option(AVA2_EMBED_PYTHON "Build embedded Python 2.7 runtime" ON) 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) add_library(ava2_lzo STATIC third_party/ava2-lzo/lzo1x_d2.c)
target_include_directories(ava2_lzo PUBLIC third_party/ava2-lzo) target_include_directories(ava2_lzo PUBLIC third_party/ava2-lzo)
set_target_properties(ava2_lzo PROPERTIES POSITION_INDEPENDENT_CODE ON) 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_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() endif()
if(NOT WIN32 AND NOT ANDROID) if(NOT WIN32 AND NOT ANDROID)
add_executable(ava2_login src/login_cli.cpp) add_executable(ava2_login src/login_cli.cpp)
target_link_libraries(ava2_login PRIVATE ava2_protocol) target_link_libraries(ava2_login PRIVATE ava2_protocol)
endif() endif()
if(BUILD_TESTING AND NOT ANDROID) 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) if(AVA2_EMBED_PYTHON)
find_package(Python3 COMPONENTS Interpreter REQUIRED)
add_executable(python_test tests/python_test.cpp) add_executable(python_test tests/python_test.cpp)
target_link_libraries(python_test PRIVATE ava2_python ava2_lzo ava2_protocol) target_link_libraries(python_test PRIVATE ava2_python ava2_lzo ava2_protocol)
add_dependencies(python_test mtpython_stdlib) 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" "$<TARGET_FILE:item_data_test>" "${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" "$<TARGET_FILE:item_sound_test>" "${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" "$<TARGET_FILE:offline_shop_test>" "${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" "$<TARGET_FILE:itemshop_test>" "${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" "$<TARGET_FILE:switchbot_test>" "${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" "$<TARGET_FILE:dungeon_info_test>" "${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" "$<TARGET_FILE:drop_item_test>" "${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" "$<TARGET_FILE:battlepass_test>" "${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" "$<TARGET_FILE:guild_test>" "${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" "$<TARGET_FILE:shop_search_test>" "${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" "$<TARGET_FILE:cube_renewal_test>" "${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" "$<TARGET_FILE:messenger_test>" "${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" "$<TARGET_FILE:quest_test>" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root")
add_executable(python_view_test tests/python_view_test.cpp) add_executable(python_view_test tests/python_view_test.cpp)
target_link_libraries(python_view_test PRIVATE ava2_python) target_link_libraries(python_view_test PRIVATE ava2_python)
add_dependencies(python_view_test mtpython_stdlib) 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" add_test(NAME ava2.python_view COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/view_fixture.py"
"$<TARGET_FILE:python_view_test>" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root" "${CMAKE_SOURCE_DIR}/runtime/login_view.py") "$<TARGET_FILE:python_view_test>" "${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) 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" "$<TARGET_FILE:python_test>" "${MT_PYTHON_STDLIB_ZIP}" "${CMAKE_SOURCE_DIR}/upstream/python-root")
add_executable(ava2_window_tree_test tests/ava2_window_tree_test.cpp) add_executable(ava2_window_tree_test tests/ava2_window_tree_test.cpp)
target_link_libraries(ava2_window_tree_test PRIVATE ava2_python mtpython) target_link_libraries(ava2_window_tree_test PRIVATE ava2_python mtpython)
add_dependencies(ava2_window_tree_test mtpython_stdlib) 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_test(NAME ava2.protocol COMMAND protocol_test)
add_executable(ava2_render_3d_test tests/ava2_render_3d_test.cpp) add_executable(ava2_render_3d_test tests/ava2_render_3d_test.cpp)
target_link_libraries(ava2_render_3d_test PRIVATE ava2_render) 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) add_executable(environment_skybox_test tests/environment_skybox_test.cpp)
target_link_libraries(environment_skybox_test PRIVATE ava2_render) target_link_libraries(environment_skybox_test PRIVATE ava2_render)
add_test(NAME ava2.environment_skybox COMMAND environment_skybox_test) 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_include_directories(nonplayer_oracle_test PRIVATE "${CMAKE_BINARY_DIR}/generated")
target_link_libraries(nonplayer_oracle_test PRIVATE ava2_python) target_link_libraries(nonplayer_oracle_test PRIVATE ava2_python)
add_test(NAME ava2.nonplayer_oracle COMMAND nonplayer_oracle_test) 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" "$<TARGET_FILE:event_test>" "${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" "$<TARGET_FILE:chat_test>" "${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" "$<TARGET_FILE:skill_test>" "${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" "$<TARGET_FILE:system_setting_test>" "${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" "$<TARGET_FILE:minimap_test>" "${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" "$<TARGET_FILE:chr_test>" "${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}") 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_include_directories(item_proto_oracle_test PRIVATE src "${CMAKE_BINARY_DIR}/generated")
target_link_libraries(item_proto_oracle_test PRIVATE ava2_protocol ava2_lzo) 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_include_directories(login_oracle_test PRIVATE "${CMAKE_BINARY_DIR}/generated")
target_link_libraries(login_oracle_test PRIVATE ava2_protocol) target_link_libraries(login_oracle_test PRIVATE ava2_protocol)
add_test(NAME ava2.login_oracle COMMAND login_oracle_test) 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) if(TARGET ava2_login)
find_package(Python3 COMPONENTS Interpreter REQUIRED) find_package(Python3 COMPONENTS Interpreter REQUIRED)
add_test(NAME ava2.login_loopback COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/login_fixture.py" "$<TARGET_FILE:ava2_login>") add_test(NAME ava2.login_loopback COMMAND "${Python3_EXECUTABLE}" "${CMAKE_SOURCE_DIR}/tests/login_fixture.py" "$<TARGET_FILE:ava2_login>")
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"reference": "upstream/ava2-client/UserInterface/Packet.h preprocessed with AVA2 Windows feature headers", "reference": "upstream/ava2-client/UserInterface/Packet.h preprocessed with AVA2 Windows feature headers",
"checked": 125, "checked": 229,
"mismatches": [], "mismatches": [],
"unmatched": [] "unmatched": []
} }
+189 -423
View File
@@ -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": [ "modules": [
{ {
"module": "ServerStateChecker", "module": "ServerStateChecker",
@@ -24,7 +24,6 @@
"missing": [], "missing": [],
"extra": [], "extra": [],
"placeholder": [ "placeholder": [
"CloseTextFile",
"EnablePerformanceTime", "EnablePerformanceTime",
"EnableSpecialCameraMode", "EnableSpecialCameraMode",
"FlashApplication", "FlashApplication",
@@ -43,12 +42,9 @@
"GetImageInfo", "GetImageInfo",
"GetInfo", "GetInfo",
"GetLoad", "GetLoad",
"GetRandom",
"GetRenderFPS", "GetRenderFPS",
"GetRenderTime", "GetRenderTime",
"GetRotatingDirection", "GetRotatingDirection",
"GetTextFileLine",
"GetTextFileLineCount",
"GetUpdateFPS", "GetUpdateFPS",
"GetUpdateTime", "GetUpdateTime",
"HideCursor", "HideCursor",
@@ -67,7 +63,6 @@
"IsWebPageMode", "IsWebPageMode",
"LoadCameraSetting", "LoadCameraSetting",
"LoadLocaleAddr", "LoadLocaleAddr",
"LoadLocaleData",
"MoveWebPage", "MoveWebPage",
"MoviePitchCamera", "MoviePitchCamera",
"MovieResetCamera", "MovieResetCamera",
@@ -77,7 +72,6 @@
"OnLogoOpen", "OnLogoOpen",
"OnLogoRender", "OnLogoRender",
"OnLogoUpdate", "OnLogoUpdate",
"OpenTextFile",
"PitchCamera", "PitchCamera",
"Process", "Process",
"RenderGame", "RenderGame",
@@ -109,7 +103,6 @@
"SetSpecularSpeed", "SetSpecularSpeed",
"SetTextTailLivingTime", "SetTextTailLivingTime",
"SetTitle", "SetTitle",
"SetTwoHandedWeaponAttSpeedDecreaseValue",
"SetVisibleNotice", "SetVisibleNotice",
"ShowCursor", "ShowCursor",
"ShowWebPage", "ShowWebPage",
@@ -146,8 +139,6 @@
"GetRenderedGraphicThingInstanceNum", "GetRenderedGraphicThingInstanceNum",
"GetRenderedSplatNum", "GetRenderedSplatNum",
"GetShadowMapColor", "GetShadowMapColor",
"GlobalPositionToLocalPosition",
"GlobalPositionToMapInfo",
"IsSoftwareTiling", "IsSoftwareTiling",
"IsVisiblePart", "IsVisiblePart",
"RegisterDungeonMapName", "RegisterDungeonMapName",
@@ -177,171 +168,53 @@
"SetXMasTree", "SetXMasTree",
"TextureChange", "TextureChange",
"Update", "Update",
"VisibleGuildArea", "VisibleGuildArea"
"WarpTest"
] ]
}, },
{
"module": "battlepass",
"windows_file": "upstream/ava2-client/UserInterface/PythonBattlePass.cpp",
"port_file": "src/python_battlepass.cpp",
"windows_methods": 8,
"missing": [],
"extra": [],
"placeholder": []
},
{ {
"module": "chat", "module": "chat",
"windows_file": "upstream/ava2-client/UserInterface/PythonChatModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonChatModule.cpp",
"port_file": "src/python_gameplay_modules.cpp", "port_file": "src/python_chat.cpp",
"windows_methods": 33, "windows_methods": 33,
"missing": [], "missing": [],
"extra": [], "extra": [],
"placeholder": [ "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"
]
}, },
{ {
"module": "chr", "module": "chr",
"windows_file": "upstream/ava2-client/UserInterface/PythonCharacterModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonCharacterModule.cpp",
"port_file": "src/python_gameplay_modules.cpp", "port_file": "src/python_chr.cpp",
"windows_methods": 80, "windows_methods": 80,
"missing": [], "missing": [],
"extra": [ "extra": [],
"RequestPetName" "placeholder": []
],
"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"
]
}, },
{ {
"module": "chrmgr", "module": "chrmgr",
"windows_file": "upstream/ava2-client/UserInterface/PythonCharacterManagerModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonCharacterManagerModule.cpp",
"port_file": "src/python_gameplay_modules.cpp", "port_file": "src/python_chr.cpp",
"windows_methods": 37, "windows_methods": 37,
"missing": [], "missing": [],
"extra": [ "extra": [],
"RegisterMotion" "placeholder": []
], },
"placeholder": [ {
"AppendShapeSkin", "module": "cube_renewal",
"CreateRace", "windows_file": "upstream/ava2-client/UserInterface/PythonCubeRenewal.cpp",
"GetPickedVID", "port_file": "src/python_cube_renewal.cpp",
"GetVIDInfo", "windows_methods": 5,
"IsPossibleEmoticon", "missing": [],
"LoadLocalRaceData", "extra": [],
"LoadRaceData", "placeholder": []
"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"
]
}, },
{ {
"module": "dbg", "module": "dbg",
@@ -352,6 +225,24 @@
"extra": [], "extra": [],
"placeholder": [] "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", "module": "effect",
"windows_file": "upstream/ava2-client/UserInterface/PythonEffectModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonEffectModule.cpp",
@@ -361,6 +252,15 @@
"extra": [], "extra": [],
"placeholder": [] "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", "module": "eventMgr",
"windows_file": "upstream/ava2-client/UserInterface/PythonGameEventManagerModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonGameEventManagerModule.cpp",
@@ -525,6 +425,15 @@
"Update" "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", "module": "ime",
"windows_file": "upstream/ava2-client/UserInterface/PythonIMEModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonIMEModule.cpp",
@@ -547,77 +456,50 @@
"IsSealScroll" "IsSealScroll"
], ],
"placeholder": [ "placeholder": [
"CanAddToQuickSlotItem",
"CreateItem", "CreateItem",
"DeleteIconInstance", "DeleteIconInstance",
"DeleteItem", "DeleteItem",
"GetApplyPoint",
"GetDropClear", "GetDropClear",
"GetDropInfo", "GetDropInfo",
"GetIBuyItemPrice",
"GetISellItemPrice",
"GetIconInstance", "GetIconInstance",
"GetItemsByName", "GetItemsByName",
"GetRarityMaxValue", "GetRarityMaxValue",
"GetRarityPoint", "GetRarityPoint",
"GetRefineSet",
"GetSocket",
"GetUseType",
"HasDropInfo", "HasDropInfo",
"Is1GoldItem",
"IsAntiFlag",
"IsDetachScroll",
"IsEquipmentVID",
"IsFlag",
"IsKey",
"IsMetin",
"IsRarityItem", "IsRarityItem",
"IsRefineScroll",
"IsWearableFlag",
"LoadItemTable",
"Pick", "Pick",
"Render", "Render",
"SelectItemWiki",
"SetDropSoundFileName",
"SetUseSoundFileName",
"Update" "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", "module": "miniMap",
"windows_file": "upstream/ava2-client/UserInterface/PythonMiniMapModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonMiniMapModule.cpp",
"port_file": "src/python_native_modules.cpp", "port_file": "src/python_minimap.cpp",
"windows_methods": 27, "windows_methods": 27,
"missing": [], "missing": [],
"extra": [ "extra": [],
"RegisterColor" "placeholder": []
],
"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"
]
}, },
{ {
"module": "net", "module": "net",
@@ -648,62 +530,22 @@
"ConnectTCP", "ConnectTCP",
"ConnectUDP", "ConnectUDP",
"DisconnectUploader", "DisconnectUploader",
"EnableChatInsultFilter",
"ExitApplication", "ExitApplication",
"ExitGame", "ExitGame",
"GetBettingGuildWarValue", "GetBettingGuildWarValue",
"GetGuildID",
"GetPreservedServerCommand",
"GetServerInfo", "GetServerInfo",
"IsChatInsultIn",
"IsInsultIn",
"IsTest", "IsTest",
"LoadInsultList",
"LogOutGame", "LogOutGame",
"OpenCatchKing", "OpenCatchKing",
"PreserveServerCommand",
"RecvGuildSymbol", "RecvGuildSymbol",
"RegisterEmoticonString",
"RegisterErrorLog", "RegisterErrorLog",
"Send67AttrClosePacket", "Send67AttrClosePacket",
"Send67AttrPacket", "Send67AttrPacket",
"SendAddOfflineShopItem", "SendAddOfflineShopItem",
"SendAddTime",
"SendAnswerMakeGuildPacket",
"SendChangeNamePacket", "SendChangeNamePacket",
"SendChinaMatrixCardPacket", "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", "SendGuildSymbol",
"SendGuildUseSkillPacket",
"SendGuildWithdrawMoneyPacket",
"SendLoginPacket", "SendLoginPacket",
"SendMallCheckoutPacket",
"SendMessengerAddByNamePacket",
"SendMessengerAddByVIDPacket",
"SendMessengerRemovePacket",
"SendMiniGameCatchKingDeckCardClick", "SendMiniGameCatchKingDeckCardClick",
"SendMiniGameCatchKingFieldCardClick", "SendMiniGameCatchKingFieldCardClick",
"SendMiniGameCatchKingReward", "SendMiniGameCatchKingReward",
@@ -711,46 +553,13 @@
"SendMobileMessagePacket", "SendMobileMessagePacket",
"SendNEWCIBNPasspodAnswerPacket", "SendNEWCIBNPasspodAnswerPacket",
"SendOfflineShopButton", "SendOfflineShopButton",
"SendOfflineShopBuyPacket",
"SendOfflineShopChangeTitle", "SendOfflineShopChangeTitle",
"SendOfflineShopCheck", "SendOfflineShopCheck",
"SendOfflineShopEndPacket",
"SendOfflineShopRemoveLogs",
"SendOpenShopSlot",
"SendOpenWithVID",
"SendPartyExitPacket",
"SendPartyInviteAnswerPacket",
"SendPartyInvitePacket",
"SendPartyParameterPacket",
"SendPartyRemovePacket",
"SendPartyRemovePacketPID",
"SendPartyRemovePacketVID",
"SendPartySetStatePacket",
"SendPartyUseSkillPacket",
"SendPrivateShopSearchInfo",
"SendQuestConfirmPacket",
"SendQuestInputLongStringPacket",
"SendQuestInputStringPacket",
"SendRemoveOfflineShopItem",
"SendRequestRefineInfoPacket",
"SendRunupMatrixCardPacket", "SendRunupMatrixCardPacket",
"SendSafeboxCheckinPacket",
"SendSafeboxCheckoutPacket",
"SendSafeboxItemMovePacket",
"SendSafeboxSaveMoneyPacket",
"SendSafeboxWithdrawMoneyPacket",
"SendSelectEmpirePacket", "SendSelectEmpirePacket",
"SendSelectItemPacket",
"SendShopBuyPacket",
"SendShopEndPacket",
"SendShopSellPacket",
"SendShopSellPacketNew",
"SendTakeOfflineMoney", "SendTakeOfflineMoney",
"SendTargetInfoLoad",
"SetEmpireLanguageMode",
"SetMarkServer", "SetMarkServer",
"SetOfflinePhase", "SetOfflinePhase",
"SetServerCommandParserWindow",
"SetServerInfo", "SetServerInfo",
"SetSkillGroupFake", "SetSkillGroupFake",
"SetTCPRecvBufferSize", "SetTCPRecvBufferSize",
@@ -768,32 +577,7 @@
"windows_methods": 24, "windows_methods": 24,
"missing": [], "missing": [],
"extra": [], "extra": [],
"placeholder": [ "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"
]
}, },
{ {
"module": "pack", "module": "pack",
@@ -804,6 +588,15 @@
"extra": [], "extra": [],
"placeholder": [] "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", "module": "player",
"windows_file": "upstream/ava2-client/UserInterface/PythonPlayerModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonPlayerModule.cpp",
@@ -819,7 +612,6 @@
"GetItemElementGrade", "GetItemElementGrade",
"GetItemElementType", "GetItemElementType",
"GetItemElementValue", "GetItemElementValue",
"GetItemRefineInformation",
"GetItemSealDate", "GetItemSealDate",
"GetItemUnSealLeftTime", "GetItemUnSealLeftTime",
"GetItemUnbindTime", "GetItemUnbindTime",
@@ -828,12 +620,7 @@
], ],
"placeholder": [ "placeholder": [
"ActEmotion", "ActEmotion",
"AffectIndexToSkillIndex",
"CanAttachMetin",
"CanAttackInstance", "CanAttackInstance",
"CanDetach",
"CanRefine",
"CanUnlock",
"ChangeCurrentSkillNumberOnly", "ChangeCurrentSkillNumberOnly",
"Clear", "Clear",
"ClearSkillDict", "ClearSkillDict",
@@ -841,66 +628,30 @@
"ComboAttack", "ComboAttack",
"EndKeyWalkingImmediately", "EndKeyWalkingImmediately",
"EndMouseWalking", "EndMouseWalking",
"ExitParty",
"GetAlignmentData", "GetAlignmentData",
"GetAutoPotionInfo", "GetAutoPotionInfo",
"GetCharacterDistance", "GetCharacterDistance",
"GetConquerorEXP",
"GetEXP",
"GetEmotionIconImage", "GetEmotionIconImage",
"GetEventGame", "GetEventGame",
"GetGem", "GetGem",
"GetGuildID",
"GetGuildName",
"GetISellItemPrice",
"GetItemFlags",
"GetItemLink", "GetItemLink",
"GetItemNewName",
"GetItemRandomAttribute", "GetItemRandomAttribute",
"GetItemSubTypeBySlot",
"GetItemTypeBySlot",
"GetJob",
"GetKillLOG",
"GetMainCharacterPart", "GetMainCharacterPart",
"GetMainCharacterShiningPart", "GetMainCharacterShiningPart",
"GetMouseFunc", "GetMouseFunc",
"GetPKMode",
"GetPartyMemberAffects",
"GetPartyMemberHPPercentage",
"GetPartyMemberState",
"GetPlayTime",
"GetQuickPage",
"GetRace",
"GetSkillCurrentEfficientPercentage",
"GetSkillNextEfficientPercentage",
"GetSkillSlotIndex",
"GetTargetVID", "GetTargetVID",
"HasMobilePhoneNumber",
"HidePlayer", "HidePlayer",
"IsActingEmotion", "IsActingEmotion",
"IsAntiFlagBySlot",
"IsAvailableBeltInventoryCell", "IsAvailableBeltInventoryCell",
"IsCantFightInstance",
"IsChallengeInstance",
"IsDSEquipmentSlot",
"IsEquippingBelt", "IsEquippingBelt",
"IsGameMaster",
"IsInSafeArea", "IsInSafeArea",
"IsMountingHorse", "IsMountingHorse",
"IsObserverMode",
"IsOpenPrivateShop", "IsOpenPrivateShop",
"IsPVPInstance", "IsPVPInstance",
"IsPartyLeader",
"IsPartyLeaderByPID",
"IsPartyMember",
"IsRevengeInstance",
"IsSameEmpire", "IsSameEmpire",
"IsSameItemVnum",
"IsShiningSlot", "IsShiningSlot",
"IsSkillActive", "IsSkillActive",
"IsValuableItem",
"LoadNewRegen", "LoadNewRegen",
"LocalQuickSlotIndexToGlobalQuickSlotIndex",
"MoveItem", "MoveItem",
"OpenCharacterMenu", "OpenCharacterMenu",
"PickCloseItem", "PickCloseItem",
@@ -908,13 +659,8 @@
"RegisterCacheEffect", "RegisterCacheEffect",
"RegisterEffect", "RegisterEffect",
"RegisterEmotionIcon", "RegisterEmotionIcon",
"RemovePartyMember",
"RemoveQuickSlotByValue",
"Render", "Render",
"RequestAddToEmptyLocalQuickSlot",
"RequestDeleteGlobalQuickSlot",
"RequestFlag", "RequestFlag",
"RequestMoveGlobalQuickSlotToLocalQuickSlot",
"ResetCameraRotation", "ResetCameraRotation",
"SendClickItemPacket", "SendClickItemPacket",
"SendDragonSoulRefine", "SendDragonSoulRefine",
@@ -922,7 +668,6 @@
"SetAutoCameraRotationSpeed", "SetAutoCameraRotationSpeed",
"SetAutoPotionInfo", "SetAutoPotionInfo",
"SetEventGame", "SetEventGame",
"SetGameWindow",
"SetItemAttribute", "SetItemAttribute",
"SetItemCount", "SetItemCount",
"SetItemData", "SetItemData",
@@ -931,16 +676,12 @@
"SetMouseFunc", "SetMouseFunc",
"SetMouseMiddleButtonState", "SetMouseMiddleButtonState",
"SetMouseState", "SetMouseState",
"SetPlayTime",
"SetQuickCameraMode", "SetQuickCameraMode",
"SetQuickPage",
"SetSingleDIKKeyState", "SetSingleDIKKeyState",
"SetTarget", "SetTarget",
"SetWeaponAttackBonusFlag", "SetWeaponAttackBonusFlag",
"ShowPlayer", "ShowPlayer",
"SlotTypeToInvenType",
"StartMouseWalking", "StartMouseWalking",
"ToggleCoolTime",
"ToggleLevelLimit", "ToggleLevelLimit",
"Update", "Update",
"UseGuildSkill", "UseGuildSkill",
@@ -958,6 +699,15 @@
"RegisterSkill" "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", "module": "profiler",
"windows_file": "upstream/ava2-client/UserInterface/PythonProfilerModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonProfilerModule.cpp",
@@ -970,6 +720,15 @@
"Push" "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", "module": "renderTarget",
"windows_file": "upstream/ava2-client/UserInterface/CPythonRenderTargetModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/CPythonRenderTargetModule.cpp",
@@ -988,6 +747,59 @@
"SetShining" "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", "module": "snd",
"windows_file": "upstream/ava2-client/UserInterface/PythonSoundManagerModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonSoundManagerModule.cpp",
@@ -997,78 +809,23 @@
"extra": [], "extra": [],
"placeholder": [] "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", "module": "systemSetting",
"windows_file": "upstream/ava2-client/UserInterface/PythonSystemModule.cpp", "windows_file": "upstream/ava2-client/UserInterface/PythonSystemModule.cpp",
"port_file": "src/python_system.cpp", "port_file": "src/python_system.cpp",
"windows_methods": 73, "windows_methods": 73,
"missing": [], "missing": [],
"extra": [ "extra": [],
"IsCollectEquipment", "placeholder": []
"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"
]
}, },
{ {
"module": "textTail", "module": "textTail",
@@ -1084,6 +841,15 @@
], ],
"placeholder": [] "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", "module": "wndMgr",
"windows_file": "upstream/ava2-client/EterPythonLib/PythonWindowManagerModule.cpp", "windows_file": "upstream/ava2-client/EterPythonLib/PythonWindowManagerModule.cpp",
@@ -1097,5 +863,5 @@
} }
], ],
"missing_method_count": 0, "missing_method_count": 0,
"placeholder_method_count": 749 "placeholder_method_count": 370
} }
+415
View File
@@ -308,3 +308,418 @@ Implemented SendOpenShopSlot(sub13)+BYTE position, SendGetBackItems(sub14), Send
### 2026-10-05: offline open by VID ### 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. 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/<lang>/...`, `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:<hex>:…|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 `<map>_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.
File diff suppressed because it is too large Load Diff
+337 -1
View File
@@ -18,7 +18,7 @@ Full 1:1 behavior is NOT implemented. The original AVA2 C++/Python snapshot is t
## Remaining substantial differences ## 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. - 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. - 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. - 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 ### 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. 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. 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).
+10 -1
View File
@@ -18,8 +18,17 @@ bool PyTuple_GetPointer(PyObject* args, int position, T** out)
PyObject* value = PyTuple_GetItem(args, position); PyObject* value = PyTuple_GetItem(args, position);
if (!value) if (!value)
return false; 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); 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; return false;
*out = static_cast<T*>(pointer); *out = static_cast<T*>(pointer);
return true; return true;
+1
View File
@@ -3,6 +3,7 @@ add_library(libgr2 STATIC
src/gr2_file.cpp # T1 header + section table + fixup src/gr2_file.cpp # T1 header + section table + fixup
src/gr2_decompress.cpp # T2 section 解压分派 src/gr2_decompress.cpp # T2 section 解压分派
src/oodle1.c # T2 Granny Oodle1 解码(端口自泄露 SDK) src/oodle1.c # T2 Granny Oodle1 解码(端口自泄露 SDK)
src/bitknit2.cpp # T2 Granny BitKnit2 解码(MIT,BG3ModStudio)
src/gr2_typetree.cpp # T3 自描述类型树遍历 src/gr2_typetree.cpp # T3 自描述类型树遍历
src/gr2_fileinfo.cpp # T4 FileInfo 汇总 src/gr2_fileinfo.cpp # T4 FileInfo 汇总
src/gr2_skeleton.cpp # T5 骨架 + bind pose 自洽检查 src/gr2_skeleton.cpp # T5 骨架 + bind pose 自洽检查
+8 -4
View File
@@ -5,7 +5,9 @@
## 能做什么 ## 能做什么
- 容器:magic / header / section / pointer-fixup(懒解引用,不物化 32 位指针) - 容器: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 布局) - 自描述类型树遍历(不硬编码 struct 布局)
- `FileInfo`:skeletons / meshes / materials / textures / models / animations - `FileInfo`:skeletons / meshes / materials / textures / models / animations
- 骨架 + `granny_transform` → 4x4 组合(`BuildCompositeTransform4x4` 语义) - 骨架 + `granny_transform` → 4x4 组合(`BuildCompositeTransform4x4` 语义)
@@ -26,14 +28,16 @@
|---|---|---| |---|---|---|
| **writer** | 无(设计上只读)| 大,PoC 不需要 | | **writer** | 无(设计上只读)| 大,PoC 不需要 |
| Oodle0 解压(`Format==1`)| `decompress_status=1`,不崩 | 中,同族算法变体 | | Oodle0 解压(`Format==1`)| `decompress_status=1`,不崩 | 中,同族算法变体 |
| BitKnit 解压(`Format==4`)| `decompress_status=4`,不崩 | 大,无公开实现;退路:Windows 侧离线转未压缩 | | BitKnit v1 解压(`Format==3`)| `decompress_status=3`,不崩(AVA2 语料 0 个;`Format==4` 是 BitKnit2,已支持)| 中,与 BitKnit2 同族 |
| 压缩曲线(`curve2` / `CurveData*` 变体)| `classify_curve` 标 `Identity`/`Unknown`,`read_old_curve` 跳过 | 中,`granny_curve.cpp` 各 `Da*` 分支 |
| B 样条 degree ≥ 3 | `eval` 退化到 degree 2 | 小,加 `CubicCoefficients` | | 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 索引 | | 多 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 行)。 `src/oodle1.c` 是从泄露的 Granny SDK **直接端口**的解码路径(约 450 行)。
- **内部研究 / 不发布 / 非商用**:可用(和「拿泄露 SDK 当字节级规格」同一风险类别,全项目都这么做)。 - **内部研究 / 不发布 / 非商用**:可用(和「拿泄露 SDK 当字节级规格」同一风险类别,全项目都这么做)。
+3 -2
View File
@@ -94,7 +94,8 @@ struct Mesh {
// ── 动画 ────────────────────────────────────────────────────────────── // ── 动画 ──────────────────────────────────────────────────────────────
// 曲线子类型:T7a 分类。Metin2 = Granny 2.4,全是 OldCurveType(granny_curve.cpp): // 曲线子类型:T7a 分类。Metin2 = Granny 2.4,全是 OldCurveType(granny_curve.cpp):
// {Int32 Degree; RefToArray Knots(Real32[]); RefToArray Controls(Real32[])} // {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 }; enum class CurveFormat { Keyframes32f, /* T7a 跑 fuzz 后补齐 */ Unknown };
// T7b:解出的曲线(B 样条:knots 时间轴 + controls 控制点,行优先 [knot][dim]) // T7b:解出的曲线(B 样条:knots 时间轴 + controls 控制点,行优先 [knot][dim])
@@ -192,7 +193,7 @@ struct FileInfo {
// ── section 表(T1,gr2dump --sections 用)──────────────────────────── // ── section 表(T1,gr2dump --sections 用)────────────────────────────
struct SectionInfo { 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 data_size; // 压缩后
uint32_t expanded_size; // 展开后 uint32_t expanded_size; // 展开后
uint32_t pointer_fixup_count; uint32_t pointer_fixup_count;
+256
View File
@@ -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 <cstring>
#include <memory>
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 <unsigned N, unsigned SHIFT, unsigned BOOST>
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<Decoder>();
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
+37
View File
@@ -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 <cstddef>
#include <cstdint>
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
+245 -3
View File
@@ -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; } 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; // animation: {String Name; Real32 Duration; Real32 TimeStep; Real32 Oversampling;
// ArrayOfRefs TrackGroups; ...} // ArrayOfRefs TrackGroups; ...}
// track_group: {String Name; RefToArray VectorTracks; RefToArray TransformTracks; ...} // 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) { if (mPos) {
bt.pos_type = classify_curve_obj(member_slot(t, *mPos), mPos->ref_type); 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_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) { if (mOri) {
bt.rot_type = classify_curve_obj(member_slot(t, *mOri), mOri->ref_type); 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_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) { if (mScl) {
bt.scale_type = classify_curve_obj(member_slot(t, *mScl), mScl->ref_type); 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_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) 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; } 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:曲线解码 ───────────────────────────────────────────────────── // ── 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 // 求值照 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。 // KnotIndex = "第一个 > t 的 knot"(granny CurveFindKnot),窗口越界按端点 clamp。
// //
// dim==4(四元数):blend 之前对本 span 参与的 degree+1 个控制点做 // dim==4(四元数):blend 之前对本 span 参与的 degree+1 个控制点做
@@ -223,10 +454,21 @@ void Curve::eval(float t, float* out) const {
return knots[(uint32_t)i]; 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]; for (uint32_t d = 0; d < dim; ++d) out[d] = controls[d];
return; 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[0]) t = knots[0];
if (t >= knots[n - 1]) t = knots[n - 1]; if (t >= knots[n - 1]) t = knots[n - 1];
// 第一个 > t 的 knot(找不到 → n-1);升序时二分 // 第一个 > t 的 knot(找不到 → n-1);升序时二分
+13 -3
View File
@@ -1,6 +1,7 @@
// M0 T2 —— section 解压分派。见 docs/reference/steps/M0-gr2-reader.md // M0 T2 —— section 解压分派。见 docs/reference/steps/M0-gr2-reader.md
#include "internal.h" #include "internal.h"
#include "oodle1.h" #include "oodle1.h"
#include "bitknit2.h"
#include <cstring> #include <cstring>
namespace gr2 { namespace gr2 {
@@ -44,10 +45,19 @@ bool File::Impl::decompress_section(const detail::GrnSection& s, const uint8_t*
} }
return true; return true;
} }
case 4: // BitKnit —— 无公开实现(全样本 0 个) case 3: // BitKnit(v1)—— Granny 2.11 之前的旧格式,AVA2 语料未出现
out.info.decompress_status = 4; out.info.decompress_status = 3;
if (err) *err = {"section", "BitKnit unsupported (M0 T2)"}; if (err) *err = {"section", "BitKnit (v1) not implemented"};
return false; 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: default:
out.info.decompress_status = -1; out.info.decompress_status = -1;
if (err) *err = {"section", "unknown compression format"}; if (err) *err = {"section", "unknown compression format"};
+7 -3
View File
@@ -75,8 +75,10 @@ std::optional<File> File::load(const uint8_t* bytes, size_t len, LoadError* err)
} }
if (magic == Magic::Unknown) if (magic == Magic::Unknown)
return fail("header", "not a Granny file (unknown magic)"); return fail("header", "not a Granny file (unknown magic)");
if (magic != Magic::Bit32_LE) // 64 位 LE(Granny 64 位导出器,如 AVA2 plechi_* 资源):头 / section 表 / fixup 与
return fail("header", "only 32-bit little-endian supported (M0 range)"); // 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; uint32_t header_size = 0, header_format = 0;
rd32(bytes, len, 16, header_size); rd32(bytes, len, 16, header_size);
@@ -120,6 +122,7 @@ std::optional<File> File::load(const uint8_t* bytes, size_t len, LoadError* err)
out.version_ = version; out.version_ = version;
out.total_size_ = total_size; out.total_size_ = total_size;
out.impl_ = std::make_shared<Impl>(); out.impl_ = std::make_shared<Impl>();
out.impl_->ptr = (magic == Magic::Bit64_LE) ? 8 : 4;
out.impl_->sections.resize(sec_count); out.impl_->sections.resize(sec_count);
out.impl_->raw.resize(sec_count); out.impl_->raw.resize(sec_count);
out.sections_.reserve(sec_count); out.sections_.reserve(sec_count);
@@ -161,7 +164,8 @@ std::optional<File> File::load(const uint8_t* bytes, size_t len, LoadError* err)
} }
// ── T1:fixup 索引(需要展开后的 section 数据 + 原始 section 头)────── // ── 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_type = { int32_t(rt_sec), rt_off };
out.impl_->root_obj = { int32_t(ro_sec), ro_off }; out.impl_->root_obj = { int32_t(ro_sec), ro_off };
+6 -6
View File
@@ -88,12 +88,12 @@ bool File::Impl::extract_mesh(Ref mesh_obj, Ref mesh_type,
const auto& vdms = parse_type(mVD->ref_type); const auto& vdms = parse_type(mVD->ref_type);
const TypeMember* mVerts = find_member(vdms, "Vertices"); const TypeMember* mVerts = find_member(vdms, "Vertices");
if (!mVerts) { MDBG("no Vertices member (vdms=%zu)\n", vdms.size()); return false; } if (!mVerts) { MDBG("no Vertices member (vdms=%zu)\n", vdms.size()); return false; }
// ReferenceToVariantArray on-disk (32-bit): {def* Type; int32 Count; void* Ptr} // ReferenceToVariantArray on-disk: {def* Type; int32 Count; void* Ptr}, packed
// (granny_data_type_definition.cpp: Ptr32 + int32 + Ptr32) // (granny_data_type_definition.cpp: Ptr + int32 + Ptr; ptr = 4 or 8 bytes)
Ref vslot = member_slot(vd, *mVerts); Ref vslot = member_slot(vd, *mVerts);
Ref vtype = follow({vslot.section, vslot.offset + 0}); Ref vtype = follow({vslot.section, vslot.offset + 0});
int32_t vcount = rd_i32({vslot.section, vslot.offset + 4}); int32_t vcount = rd_i32({vslot.section, vslot.offset + ptr});
Ref vdata = follow({vslot.section, vslot.offset + 8}); Ref vdata = follow({vslot.section, vslot.offset + ptr + 4});
MDBG("Vertices count=%d vtype=(%d,%u) vdata=(%d,%u)\n", MDBG("Vertices count=%d vtype=(%d,%u) vdata=(%d,%u)\n",
vcount, vtype.section, vtype.offset, vdata.section, vdata.offset); vcount, vtype.section, vtype.offset, vdata.section, vdata.offset);
if (vcount <= 0 || vcount > (1 << 24) || !vtype.valid() || !vdata.valid()) return false; 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; 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) { bool File::Impl::extended_i32(Ref slot, const char* name, int32_t& out) {
Ref type = follow(slot); 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; if (!type.valid() || !obj.valid()) return false;
const TypeMember* m = find_member(parse_type(type), name); const TypeMember* m = find_member(parse_type(type), name);
if (!m || (m->type != detail::MT_Int32 && m->type != detail::MT_UInt32)) return false; if (!m || (m->type != detail::MT_Int32 && m->type != detail::MT_UInt32)) return false;
+57 -19
View File
@@ -1,16 +1,20 @@
// M0 T1(fixup 索引)+ T3(自描述类型树遍历)。见 docs/reference/steps/M0-gr2-reader.md // M0 T1(fixup 索引)+ T3(自描述类型树遍历)。见 docs/reference/steps/M0-gr2-reader.md
// 规格:granny_file_format.h(fixup)+ granny_data_type_definition.h/.cpp(成员类型 + stride) // 规格:granny_file_format.h(fixup)+ granny_data_type_definition.h/.cpp(成员类型 + stride)
#include "internal.h" #include "internal.h"
#include "bitknit2.h"
#include <algorithm>
#include <cstdint>
#include <cstring> #include <cstring>
#include <string>
namespace gr2 { namespace gr2 {
using detail::Ref; using detail::Ref;
using detail::TypeMember; using detail::TypeMember;
using detail::kTypeDefEntrySize;
// ── member_type → 文件里的单元字节数(32 位指针)────────────────────── // ── member_type → 文件里的单元字节数 ──────────────────────────────────
// 序数见 internal.h MemberType。InlineMember 需递归(这里在 member_unit_size 处理)。 // 序数见 internal.h MemberType。InlineMember 需递归(这里在 member_unit_size 处理)。
// 表里是 32 位文件的值;含指针的类型按 kPtrSlots 个指针加宽(64 位文件每个指针 +4)。
static const int8_t kUnit32[detail::MT_OnePastLast] = { static const int8_t kUnit32[detail::MT_OnePastLast] = {
/* End */ 0, /* End */ 0,
/* Inline */ 0, /* 特判 */ /* Inline */ 0, /* 特判 */
@@ -19,7 +23,7 @@ static const int8_t kUnit32[detail::MT_OnePastLast] = {
/* ArrayOfRefs */ 8, /* ArrayOfRefs */ 8,
/* VariantRef */ 8, /* ptr + ptr */ /* VariantRef */ 8, /* ptr + ptr */
/* Removed */ 0, /* Removed */ 0,
/* RefToVariantArr*/ 12, /* RefToVariantArr*/ 12, /* ptr + int32 + ptr */
/* String */ 4, /* String */ 4,
/* Transform */ 68, /* u32 flags + f32[3] + f32[4] + f32[3][3] */ /* Transform */ 68, /* u32 flags + f32[3] + f32[4] + f32[3][3] */
/* Real32 */ 4, /* Real32 */ 4,
@@ -36,6 +40,11 @@ static const int8_t kUnit32[detail::MT_OnePastLast] = {
/* Real16 */ 2, /* Real16 */ 2,
/* EmptyRef */ 4, /* 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 内指针 + 边界检查 ──────────────────────────────────────── // ── section 内指针 + 边界检查 ────────────────────────────────────────
const uint8_t* File::Impl::at(Ref r, size_t need) const { 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 索引 ──────────────────────────────────────────────── // ── T1:建 fixup 索引 ────────────────────────────────────────────────
// grn_pointer_fixup 数组在文件里(PointerFixupArrayOffset 从文件起点算,Count 项,每 12B)。 // grn_pointer_fixup 数组在文件里(PointerFixupArrayOffset 从文件起点算,Count 项,每 12B)。
// 每项 { u32 FromOffset(本 section 展开数据内偏移); u32 DestSection; u32 DestOffset }。 // 每项 { u32 FromOffset(本 section 展开数据内偏移); u32 DestSection; u32 DestOffset }。
void File::Impl::build_fixups(const uint8_t* file, size_t file_len) { // BitKnit2 section(Format==4)的 fixup 表也被压缩:偏移处是 u32 压缩长度 + BitKnit2 流,
auto le32 = [&](size_t off) -> uint32_t { // 解出 Count*12 字节(Granny 2.11 changelog「fixup metadata is compressed」;
if (off + 4 > file_len) return 0; // BG3ModStudio GR2Reader 同样处理)。MixedMarshalling fixup 本读取器不用,不展开。
return uint32_t(file[off]) | (uint32_t(file[off + 1]) << 8) | bool File::Impl::build_fixups(const uint8_t* file, size_t file_len, LoadError* err) {
(uint32_t(file[off + 2]) << 16) | (uint32_t(file[off + 3]) << 24); 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(); fixups.clear();
std::vector<uint8_t> unpacked;
for (size_t si = 0; si < raw.size(); ++si) { for (size_t si = 0; si < raw.size(); ++si) {
const GrnSection& gs = raw[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; size_t base = gs.pointer_fixup_off;
for (uint32_t k = 0; k < gs.pointer_fixup_count; ++k) { if (gs.compression == 4) {
size_t p = base + size_t(k) * 12; if (base > file_len || file_len - base < 4) {
if (p + 12 > file_len) break; 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<size_t>(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 from = le32(p + 0);
uint32_t dsec = le32(p + 4); uint32_t dsec = le32(p + 4);
uint32_t doff = le32(p + 8); 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}; Ref{int32_t(dsec), doff};
} }
} }
return true;
} }
// ── T3:走 data_type_definition 数组 ───────────────────────────────── // ── T3:走 data_type_definition 数组 ─────────────────────────────────
uint32_t File::Impl::member_unit_size(const TypeMember& m) { 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 == detail::MT_Inline) return object_size(m.ref_type);
if (m.type <= 0 || m.type >= detail::MT_OnePastLast) return 0; 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) { uint32_t File::Impl::object_size(Ref type_ref) {
@@ -127,8 +164,9 @@ const std::vector<TypeMember>& File::Impl::parse_type(Ref type_ref) {
Ref cur = type_ref; Ref cur = type_ref;
uint32_t inst_off = 0; uint32_t inst_off = 0;
const uint32_t entry = detail::type_def_entry_size(ptr);
for (int guard = 0; guard < 4096; ++guard) { for (int guard = 0; guard < 4096; ++guard) {
const uint8_t* e = at(cur, kTypeDefEntrySize); const uint8_t* e = at(cur, entry);
if (!e) break; if (!e) break;
int32_t type = (int32_t)rd_u32(cur); int32_t type = (int32_t)rd_u32(cur);
if (type == detail::MT_End) break; if (type == detail::MT_End) break;
@@ -137,10 +175,10 @@ const std::vector<TypeMember>& File::Impl::parse_type(Ref type_ref) {
m.type = type; m.type = type;
// Name @ +4(指针槽) // Name @ +4(指针槽)
m.name = rd_str({cur.section, cur.offset + 4}); m.name = rd_str({cur.section, cur.offset + 4});
// ReferenceType @ +8(指针槽 → data_type_definition 数组) // ReferenceType @ +4+ptr(指针槽 → data_type_definition 数组)
m.ref_type = follow({cur.section, cur.offset + 8}); m.ref_type = follow({cur.section, cur.offset + 4 + ptr});
// ArrayWidth @ +12 // ArrayWidth @ +4+2*ptr
m.array_width = (int32_t)rd_u32({cur.section, cur.offset + 12}); 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; uint32_t width = (m.array_width <= 0) ? 1u : (uint32_t)m.array_width;
m.offset = inst_off; m.offset = inst_off;
@@ -148,7 +186,7 @@ const std::vector<TypeMember>& File::Impl::parse_type(Ref type_ref) {
inst_off += m.size; inst_off += m.size;
out.push_back(std::move(m)); out.push_back(std::move(m));
cur.offset += kTypeDefEntrySize; cur.offset += entry;
} }
slot = std::move(out); slot = std::move(out);
return slot; return slot;
@@ -169,7 +207,7 @@ std::vector<Ref> File::Impl::read_array_of_refs(Ref obj, const TypeMember& m) co
if (!arr.valid()) return out; if (!arr.valid()) return out;
out.reserve(count); out.reserve(count);
for (int32_t i = 0; i < count; ++i) { 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 项) out.push_back(elem); // 可能 invalid(NULL 项)
} }
return out; return out;
+13 -6
View File
@@ -36,7 +36,7 @@ struct Section {
SectionInfo info; SectionInfo info;
}; };
// section 内的位置。不物化指针(文件是 32 位指针,本进程 64 位), // section 内的位置。不物化指针(文件是 32 或 64 位指针),
// 全程用 (section, offset) + fixup 表按需解引用。 // 全程用 (section, offset) + fixup 表按需解引用。
struct Ref { struct Ref {
int32_t section = -1; int32_t section = -1;
@@ -53,9 +53,10 @@ enum MemberType {
MT_Int32, MT_UInt32, MT_Real16, MT_EmptyRef, MT_OnePastLast MT_Int32, MT_UInt32, MT_Real16, MT_EmptyRef, MT_OnePastLast
}; };
// data_type_definition 在文件里的字节数(32 位指针): // data_type_definition 在文件里的字节数(结构紧排,指针宽度随文件 magic):
// Type(4) Name(ptr4) ReferenceType(ptr4) ArrayWidth(4) Extra[3](12) Ignored(ptr4) // Type(4) Name(ptr) ReferenceType(ptr) ArrayWidth(4) Extra[3](12) Ignored(ptr)
constexpr uint32_t kTypeDefEntrySize = 32; // 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 { struct TypeMember {
std::string name; std::string name;
@@ -81,13 +82,16 @@ struct File::Impl {
Ref root_obj; // grn_file_header.RootObject Ref root_obj; // grn_file_header.RootObject
Ref root_type; // grn_file_header.RootObjectTypeDefinition Ref root_type; // grn_file_header.RootObjectTypeDefinition
bool typetree_ready = false; bool typetree_ready = false;
// 文件指针宽度:32 位 magic = 4,64 位 magic = 8。指针槽都靠 fixup 表解引用,
// 只有成员大小 / 复合成员内部偏移随它变化。
uint32_t ptr = 4;
// 类型解析缓存:typedef 的 Ref -> 成员列表 // 类型解析缓存:typedef 的 Ref -> 成员列表
std::unordered_map<uint64_t, std::vector<TypeMember>> type_cache; std::unordered_map<uint64_t, std::vector<TypeMember>> type_cache;
// ── T2 / T1 ── // ── T2 / T1 ──
bool decompress_section(const GrnSection&, const uint8_t* src, detail::Section& out, LoadError*); 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 ── // ── T3 ──
const uint8_t* at(Ref r, size_t need = 0) const; // section 内指针 + 边界检查 const uint8_t* at(Ref r, size_t need = 0) const; // section 内指针 + 边界检查
@@ -106,7 +110,7 @@ struct File::Impl {
// 成员访问(obj = 对象实例的 Ref,m = 其类型的某个成员) // 成员访问(obj = 对象实例的 Ref,m = 其类型的某个成员)
Ref member_slot(Ref obj, const TypeMember& m) const { return {obj.section, obj.offset + m.offset}; } 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)); } 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<Ref> read_array_of_refs(Ref obj, const TypeMember& m) const; std::vector<Ref> read_array_of_refs(Ref obj, const TypeMember& m) const;
// ReferenceToArray: {int32 count; ptr → [count] 个连续对象(elem_type)} // 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); 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 是它的类型。 // 曲线子类型分类(T7a)。curve_obj 指向 inline 曲线对象本体,curve_type 是它的类型。
std::string classify_curve_obj(Ref curve_obj, Ref 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 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; double skeleton_self_check(int skeleton) const;
// granny_transform (68B) → 行主序 4x4(BuildCompositeTransform4x4 语义) // granny_transform (68B) → 行主序 4x4(BuildCompositeTransform4x4 语义)
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace ava2 {
// CMemoryTextFileLoader::Bind and SplitLine/SplitLineByTab (AVA2 EterBase/FileLoader.cpp).
inline std::vector<std::string> ava2TextLines(const std::string& input) {
std::vector<std::string> lines;std::string line;
for(size_t i=0;i<input.size();++i) {
char c=input[i];
if(c=='\r'||c=='\n') {if(i+1<input.size()&&(input[i+1]=='\r'||input[i+1]=='\n'))++i;lines.push_back(line);line.clear();}
else {line+=c;if(int8_t(c)<0&&i+1<input.size())line+=input[++i];}
}
lines.push_back(line);return lines;
}
inline std::vector<std::string> ava2TabTokens(const std::string& line,bool preserveEmpty) {
std::vector<std::string> fields;if(line.empty())return fields;size_t pos=0;
while(pos<line.size()) {
if(!preserveEmpty) {pos=line.find_first_not_of('\t',pos);if(pos==std::string::npos)break;}
size_t end;
if(!preserveEmpty&&line[pos]=='"') {++pos;end=line.find('"',pos);if(end==std::string::npos)return {};fields.push_back(line.substr(pos,end-pos));pos=end+1;}
else {end=line.find('\t',pos);fields.push_back(line.substr(pos,end==std::string::npos?end:end-pos));if(end==std::string::npos)break;pos=end+1;}
}
return fields;
}
}
+127
View File
@@ -0,0 +1,127 @@
#pragma once
// Minimal CTextFileLoader (AVA2 EterLib/TextFileLoader.cpp) + CMemoryTextFileLoader::SplitLine/SplitLine2
// (EterBase/FileLoader.cpp): "Group name { key values... List name { ... } }" trees.
// Keys are lower-cased and the first insert wins, like the original std::map insert.
// Not ported: CRC32 name keys (a CRC collision would alias two keys on Windows) and the Cache() pool.
#include "ava2_text_file.h"
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace ava2 {
// Returns 0 = tokens, -1 = no token, -2 = unmatched '"' (SplitLine2). SplitLine == (result==0).
inline int ava2SplitLine2(const std::string& line,std::vector<std::string>* 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<line.size());
return 0;
}
inline void ava2Lowers(std::string& s) { for(auto& c:s)c=char(std::tolower(static_cast<unsigned char>(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<std::string,std::vector<std::string>>& map) {
const std::vector<std::string> lines=ava2TextLines(text);
std::vector<std::string> tok,sub;
for(size_t i=0;i<lines.size();++i) {
if(ava2SplitLine2(lines[i],&tok)!=0)continue;
ava2Lowers(tok[0]);
if(tok[0]=="start") {
if(tok.size()<2)continue; // Windows reads stTokenVector[1] unchecked.
ava2Lowers(tok[1]);std::string key=tok[1];tok.clear();
for(i=i+1;i<lines.size();++i) {
if(ava2SplitLine2(lines[i],&sub)!=0)continue;
ava2Lowers(sub[0]);
if(sub[0]=="end")break;
tok.insert(tok.end(),sub.begin(),sub.end());
}
map.insert({key,tok});
} else {
std::string key=tok[0];tok.erase(tok.begin());map.insert({key,tok});
}
}
}
class TextFileLoader {
public:
struct Node {
std::string name;Node* parent=nullptr;
std::vector<std::unique_ptr<Node>> children;
std::map<std::string,std::vector<std::string>> tokens;
};
bool load(const std::string& text,std::vector<std::string>* 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<std::string>* 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<std::string> tok;int depth=0;
for(;m_line<m_lines.size();++m_line) {
int ret=ava2SplitLine2(m_lines[m_line],&tok);
if(ret!=0) {if(ret==-2)error("cannot find \" in line "+std::to_string(m_line));continue;}
ava2Lowers(tok[0]);
if(tok[0][0]=='{') {++depth;continue;}
if(tok[0][0]=='}') {--depth;break;}
if(tok[0]=="group") {
if(tok.size()!=2)continue; // assert() is compiled out in the release client.
auto child=std::make_unique<Node>();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<std::string> values,sub;
for(++m_line;m_line<m_lines.size();++m_line) {
if(ava2SplitLine2(m_lines[m_line],&sub)!=0)continue;
if(sub[0][0]=='{')continue;
if(sub[0][0]=='}')break;
values.insert(values.end(),sub.begin(),sub.end());
}
node->tokens.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<std::string> m_lines;size_t m_line=0;
Node m_global;Node* m_cur=&m_global;std::vector<std::string>* m_errors=nullptr;
};
}
+18
View File
@@ -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 <Python.h>
#include <vector>
namespace ava2 {
struct BattlePassState {
int32_t time=0;
std::vector<TInfoBattlePass> info,progress;
PyObject* handler=nullptr;
void SetHandler(PyObject* value);
void Clear(uint8_t subheader);
void Loading(uint8_t subheader);
void Reset();
};
BattlePassState& GetBattlePassState();
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include "eter_net/Packet.h"
#include <Python.h>
#include <vector>
namespace ava2 {
// AVA2 PythonCubeRenewal.cpp: a vector, not a map keyed by recipe index.
struct CubeRenewalState {
std::vector<TInfoDateCubeRenewal> records;
PyObject* handler=nullptr;
void SetHandler(PyObject* value);
void LoadingList();
void Reset();
};
CubeRenewalState& GetCubeRenewalState();
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
// AVA2 PythonDropItem.cpp: ordered results and unconstrained page selection.
#include "eter_net/Packet.h"
#include <Python.h>
#include <vector>
namespace ava2 {
struct DropItemState {
int32_t page=1;
std::vector<TInfoDropItemSystem> records;
PyObject* handler=nullptr;
void SetHandler(PyObject* value);
void Clear();
void Loading();
void Reset();
};
DropItemState& GetDropItemState();
}
+14
View File
@@ -0,0 +1,14 @@
#pragma once
// AVA2 PythonDungeonInfo.cpp. Clear resets info/missions/page but retains ranking.
#include "eter_net/Packet.h"
#include <vector>
namespace ava2 {
struct DungeonInfoState {
int32_t page=1;
std::vector<TFDateInfoPacket> info;
std::vector<TFDateMision> missions;
std::vector<TFDateInfoRanking> ranking;
void Clear() {page=1;info.clear();missions.clear();}
};
DungeonInfoState& GetDungeonInfoState();
}
+52
View File
@@ -0,0 +1,52 @@
// Provenance: AVA2 EterBase/Random.cpp.
#include "Random.h"
#include <cassert>
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
+13
View File
@@ -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 <cstdint>
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
+45 -33
View File
@@ -1,3 +1,4 @@
#include <cstdlib>
#include "EffectData.h" #include "EffectData.h"
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
@@ -7,6 +8,13 @@
namespace ava2 { 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<TimeEvent>& events, float time, float defaultValue) { float InterpolateTimeEvent(const std::vector<TimeEvent>& events, float time, float defaultValue) {
if (events.empty()) return defaultValue; if (events.empty()) return defaultValue;
if (events.size() == 1 || time <= events.front().time) return events.front().value; 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] == "{") { if (idx < numTokens && tokens[idx] == "{") {
idx++; idx++;
while (idx < numTokens && tokens[idx] != "}") { while (idx < numTokens && tokens[idx] != "}") {
float t = std::stof(tokens[idx++]); float t = ScriptFloat(tokens[idx++]);
if (idx < numTokens && tokens[idx] != "}") { if (idx < numTokens && tokens[idx] != "}") {
float v = std::stof(tokens[idx++]); float v = ScriptFloat(tokens[idx++]);
outEvents.push_back({t, v}); outEvents.push_back({t, v});
} }
} }
@@ -138,12 +146,12 @@ bool EffectData::LoadScript(const std::string& filepath) {
if (tokenLower == "boundingsphereradius" && idx + 1 < numTokens) { if (tokenLower == "boundingsphereradius" && idx + 1 < numTokens) {
idx++; idx++;
m_bounding_sphere_radius = std::stof(tokens[idx++]); m_bounding_sphere_radius = ScriptFloat(tokens[idx++]);
} else if (tokenLower == "boundingsphereposition" && idx + 3 < numTokens) { } else if (tokenLower == "boundingsphereposition" && idx + 3 < numTokens) {
idx++; idx++;
m_bounding_sphere_position[0] = std::stof(tokens[idx++]); m_bounding_sphere_position[0] = ScriptFloat(tokens[idx++]);
m_bounding_sphere_position[1] = std::stof(tokens[idx++]); m_bounding_sphere_position[1] = ScriptFloat(tokens[idx++]);
m_bounding_sphere_position[2] = std::stof(tokens[idx++]); m_bounding_sphere_position[2] = ScriptFloat(tokens[idx++]);
} else if (tokenLower == "group" && idx + 1 < numTokens && ToLower(tokens[idx + 1]) == "particle") { } else if (tokenLower == "group" && idx + 1 < numTokens && ToLower(tokens[idx + 1]) == "particle") {
idx += 2; idx += 2;
if (idx < numTokens && tokens[idx] == "{") idx++; if (idx < numTokens && tokens[idx] == "{") idx++;
@@ -166,23 +174,27 @@ bool EffectData::LoadScript(const std::string& filepath) {
std::string pKey = ToLower(tokens[idx++]); std::string pKey = ToLower(tokens[idx++]);
if (pKey == "starttime" && idx < numTokens) { 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") { } else if (pKey == "list" && idx + 1 < numTokens && ToLower(tokens[idx]) == "timeeventposition") {
idx++; // skip timeeventposition idx++; // skip timeeventposition
if (idx < numTokens && tokens[idx] == "{") { if (idx < numTokens && tokens[idx] == "{") {
idx++; idx++;
while (idx < numTokens && tokens[idx] != "}") { while (idx < numTokens && tokens[idx] != "}") {
// format: time "MOVING_TYPE_DIRECT" x y z // 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 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] != "}") { if (idx + 2 < numTokens && tokens[idx] != "}") {
float mx = std::stof(tokens[idx++]); float mx = ScriptFloat(tokens[idx++]);
float my = std::stof(tokens[idx++]); float my = ScriptFloat(tokens[idx++]);
float mz = std::stof(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) // 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[0] = mx;
pe.position[1] = mz; pe.position[1] = mz;
pe.position[2] = my; pe.position[2] = my;
if (bezier) idx = std::min(idx + 3, numTokens); // control point
} }
} }
if (idx < numTokens && tokens[idx] == "}") idx++; if (idx < numTokens && tokens[idx] == "}") idx++;
@@ -198,21 +210,21 @@ bool EffectData::LoadScript(const std::string& filepath) {
std::string eKey = ToLower(tokens[idx++]); std::string eKey = ToLower(tokens[idx++]);
if (eKey == "maxemissioncount" && idx < numTokens) { 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) { } 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) { } 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) { } 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) { } else if (eKey == "emittershape" && idx < numTokens) {
pe.emitter.emitter_shape = static_cast<uint8_t>(std::stoi(tokens[idx++])); pe.emitter.emitter_shape = static_cast<uint8_t>(ScriptInt(tokens[idx++]));
} else if (eKey == "emittingradius" && idx < numTokens) { } 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) { } else if (eKey == "emittingdirection" && idx + 2 < numTokens) {
float ex = std::stof(tokens[idx++]); float ex = ScriptFloat(tokens[idx++]);
float ey = std::stof(tokens[idx++]); float ey = ScriptFloat(tokens[idx++]);
float ez = std::stof(tokens[idx++]); float ez = ScriptFloat(tokens[idx++]);
pe.emitter.emitting_direction[0] = ex; pe.emitter.emitting_direction[0] = ex;
pe.emitter.emitting_direction[1] = ez; pe.emitter.emitting_direction[1] = ez;
pe.emitter.emitting_direction[2] = ey; pe.emitter.emitting_direction[2] = ey;
@@ -251,31 +263,31 @@ bool EffectData::LoadScript(const std::string& filepath) {
std::string prKey = ToLower(tokens[idx++]); std::string prKey = ToLower(tokens[idx++]);
if (prKey == "srcblendtype" && idx < numTokens) { if (prKey == "srcblendtype" && idx < numTokens) {
pe.particle.src_blend_type = static_cast<uint8_t>(std::stoi(tokens[idx++])); pe.particle.src_blend_type = static_cast<uint8_t>(ScriptInt(tokens[idx++]));
} else if (prKey == "destblendtype" && idx < numTokens) { } else if (prKey == "destblendtype" && idx < numTokens) {
pe.particle.dest_blend_type = static_cast<uint8_t>(std::stoi(tokens[idx++])); pe.particle.dest_blend_type = static_cast<uint8_t>(ScriptInt(tokens[idx++]));
} else if (prKey == "coloroperationtype" && idx < numTokens) { } else if (prKey == "coloroperationtype" && idx < numTokens) {
pe.particle.color_op_type = static_cast<uint8_t>(std::stoi(tokens[idx++])); pe.particle.color_op_type = static_cast<uint8_t>(ScriptInt(tokens[idx++]));
} else if (prKey == "billboardtype" && idx < numTokens) { } else if (prKey == "billboardtype" && idx < numTokens) {
pe.particle.billboard_type = static_cast<uint8_t>(std::stoi(tokens[idx++])); pe.particle.billboard_type = static_cast<uint8_t>(ScriptInt(tokens[idx++]));
} else if (prKey == "rotationtype" && idx < numTokens) { } else if (prKey == "rotationtype" && idx < numTokens) {
pe.particle.rotation_type = static_cast<uint8_t>(std::stoi(tokens[idx++])); pe.particle.rotation_type = static_cast<uint8_t>(ScriptInt(tokens[idx++]));
} else if (prKey == "rotationspeed" && idx < numTokens) { } 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) { } 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) { } 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) { } 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) { } 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) { } else if (prKey == "texanitype" && idx < numTokens) {
pe.particle.tex_ani_type = static_cast<uint8_t>(std::stoi(tokens[idx++])); pe.particle.tex_ani_type = static_cast<uint8_t>(ScriptInt(tokens[idx++]));
} else if (prKey == "texanidelay" && idx < numTokens) { } 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) { } 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) { } else if (prKey == "list" && idx < numTokens) {
std::string listName = ToLower(tokens[idx++]); std::string listName = ToLower(tokens[idx++]);
if (listName == "timeeventscalex") ReadTimeEvents(pe.particle.time_scale_x); if (listName == "timeeventscalex") ReadTimeEvents(pe.particle.time_scale_x);
+2 -2
View File
@@ -38,12 +38,12 @@ public:
const CGraphicTexture& GetTextureReference() const { return m_imageTexture; } const CGraphicTexture& GetTextureReference() const { return m_imageTexture; }
CGraphicTexture* GetTexturePointer() { 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) if (!c_szFileName || !*c_szFileName)
return false; return false;
SetFileName(c_szFileName); SetFileName(logicalName?logicalName:c_szFileName);
std::ifstream file(c_szFileName, std::ios::binary | std::ios::ate); std::ifstream file(c_szFileName, std::ios::binary | std::ios::ate);
if (!file.is_open()) if (!file.is_open())
+31
View File
@@ -37,6 +37,37 @@ CGraphicImage* GrpGetImagePointer(uint32_t handle)
return nullptr; return nullptr;
} }
static uint32_t s_nextInstanceHandle = 1;
static std::unordered_map<uint32_t, CGraphicImageInstance*> s_handleToInstance;
uint32_t GrpRegisterImageInstanceHandle(CGraphicImageInstance* pInstance)
{
if (!pInstance)
return 0;
std::lock_guard<std::mutex> lock(s_imageHandleMutex);
const uint32_t handle = s_nextInstanceHandle++;
s_handleToInstance[handle] = pInstance;
return handle;
}
CGraphicImageInstance* GrpGetImageInstancePointer(uint32_t handle)
{
std::lock_guard<std::mutex> 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<std::mutex> 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> CGraphicImageInstance::ms_kPool; CDynamicPool<CGraphicImageInstance> CGraphicImageInstance::ms_kPool;
CDynamicPool<CGraphicExpandedImageInstance> CGraphicExpandedImageInstance::ms_kExpandedPool; CDynamicPool<CGraphicExpandedImageInstance> CGraphicExpandedImageInstance::ms_kExpandedPool;
CDynamicPool<CGraphicMarkInstance> CGraphicMarkInstance::ms_kPool; CDynamicPool<CGraphicMarkInstance> CGraphicMarkInstance::ms_kPool;
+6
View File
@@ -162,3 +162,9 @@ public:
uint32_t GrpRegisterImageHandle(CGraphicImage* pImage); uint32_t GrpRegisterImageHandle(CGraphicImage* pImage);
CGraphicImage* GrpGetImagePointer(uint32_t handle); 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);
+342
View File
@@ -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 <cctype>
#include <cstring>
#include <SDL3/SDL_log.h>
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<unsigned char>(*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<char*>(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<unsigned char>(*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<unsigned char>(*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<unsigned char>(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;
}
+43
View File
@@ -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 <list>
#include <string>
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<TArg> 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<TCmd> m_cmdList;
};
}
+144
View File
@@ -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},
+622 -93
View File
@@ -1,5 +1,12 @@
#include "NetworkActorManager.h" #include "NetworkActorManager.h"
#include "eter_render/TextTailManager.h" #include "eter_render/TextTailManager.h"
#include "eter_effect/EffectManager.h"
#include "nonplayer_data.h"
#include "eter_render/RaceData.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <map>
#include <cmath> #include <cmath>
#include <filesystem> #include <filesystem>
#include <iostream> #include <iostream>
@@ -8,61 +15,391 @@ namespace ava2 {
namespace { namespace {
std::string ResolveModelPath(const std::string& rel) { // InstanceBaseEffect.cpp g_akD3DXClrName / g_akD3DXClrTitle / g_TitleNameMap: zero (transparent
if (std::filesystem::exists(rel)) return rel; // black) until introLoading.__main__ registers them through chrmgr.
if (std::filesystem::exists("build/dev/" + rel)) return "build/dev/" + rel; std::array<uint32_t, NetworkActorManager::NAMECOLOR_NUM>& NameColors() { static std::array<uint32_t, NetworkActorManager::NAMECOLOR_NUM> s{}; return s; }
if (std::filesystem::exists("../" + rel)) return "../" + rel; std::array<uint32_t, NetworkActorManager::TITLE_NUM>& TitleColors() { static std::array<uint32_t, NetworkActorManager::TITLE_NUM> s{}; return s; }
return rel; std::map<int, std::string>& TitleNames() { static std::map<int, std::string> 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) { // InstanceBase.cpp __ArmorVnumToShape.
switch (race) { bool ArmorVnumToShape(uint32_t vnum, uint32_t* shape) {
case 0: return ResolveModelPath("ymir work/pc/warrior/warrior_assasin1.gr2"); *shape = vnum;
case 1: return ResolveModelPath("ymir work/pc/assassin/assassin_halloween1_lod_01.gr2"); if (vnum == 0 || vnum == 1) return false;
case 2: return ResolveModelPath("ymir work/pc/sura/sura_soccer1_germany_lod_02.gr2"); if (!s_armorSpecular) return false;
case 3: return ResolveModelPath("ymir work/pc/shaman/shaman_fencing1_germany_lod_02.gr2"); SItemModelData item;
case 4: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/warrior_w.gr2"); if (!GetItemData(vnum, &item)) return false;
case 5: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/assassin_m.gr2"); *shape = uint32_t(item.values[3]);
case 6: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/sura_w.gr2"); return true;
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");
}
} }
std::string GetWeaponModelPath(uint32_t weapon) { constexpr uint8_t kTypePC = 6; // CActorInstance::TYPE_PC
if (weapon > 0) { bool IsPC(const SNetworkActorData& actor) { return actor.m_bType == kTypePC; }
return ResolveModelPath("ymir work/item/weapon/set_11_sword.gr2");
} // InstanceBase.h RaceToJob / RaceToSex (ENABLE_WOLFMAN_CHARACTER off).
return ""; 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) { uint32_t RGBToColor(unsigned r, unsigned g, unsigned b) {
if (hair > 0) { // __RGBToD3DXColoru: 0xff alpha, components shifted in without masking.
return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/hair/warrior_m.gr2"); uint32_t c = 0xff; c <<= 8; c |= r; c <<= 8; c |= g; c <<= 8; c |= b;
} return c;
return "";
} }
std::string GetAlignmentTitle(int16_t alignment, uint32_t& titleColor) { // CInstanceBase::ms_astAffectEffectAttachBone / ms_adwCRCAffectEffect.
if (alignment >= 12000) { titleColor = 0xFF00BFFF; return "Chivalric"; } std::unordered_map<unsigned, std::string>& EffectAttachBones() { static std::unordered_map<unsigned, std::string> s; return s; }
if (alignment >= 8000) { titleColor = 0xFF1E90FF; return "Noble"; } std::unordered_map<unsigned, uint32_t>& EffectCRCs() { static std::unordered_map<unsigned, uint32_t> s; return s; }
if (alignment >= 4000) { titleColor = 0xFF6495ED; return "Good"; }
if (alignment >= 1000) { titleColor = 0xFF87CEEB; return "Friendly"; } bool IsAffect(const SNetworkActorData& actor, unsigned affect) {
if (alignment > -1000) { titleColor = 0xFFFFFFFF; return ""; } return affect < 64 && (actor.m_affectFlags[affect / 32] & (1u << (affect % 32))) != 0;
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";
} }
} // namespace } // 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<uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(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<float>(actor.m_lCurX), y = static_cast<float>(actor.m_lCurZ), z = static_cast<float>(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<float>(actor->m_lCurX), y = static_cast<float>(actor->m_lCurZ), z = static_cast<float>(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 << "<EMOTICON_NUM:" << EMOTICON_NUM << ", isVisible=0)" << std::endl;
return;
}
if (!IsPossibleEmoticon(vid)) return;
// AttachEffectByID(0, NULL, crc, &(0,0,GetHeight())): root attach raised by the actor height.
const float height = actor->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() { NetworkActorManager& NetworkActorManager::Instance() {
static NetworkActorManager s_instance; static NetworkActorManager s_instance;
return s_instance; return s_instance;
@@ -77,6 +414,31 @@ void NetworkActorManager::SetMainActorVID(uint32_t vid) {
void NetworkActorManager::AppendActor(const SNetworkActorData& data) { void NetworkActorManager::AppendActor(const SNetworkActorData& data) {
auto& actorData = m_actors[data.m_dwVID]; auto& actorData = m_actors[data.m_dwVID];
actorData = data; 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 // Instantiate 3D ActorInstance
auto actor = std::make_shared<ActorInstance>(); auto actor = std::make_shared<ActorInstance>();
@@ -92,33 +454,34 @@ void NetworkActorManager::AppendActor(const SNetworkActorData& data) {
float worldZ = static_cast<float>(data.m_lCurY); float worldZ = static_cast<float>(data.m_lCurY);
actor->SetPosition(worldX, worldY, worldZ); actor->SetPosition(worldX, worldY, worldZ);
std::string modelPath = GetRaceModelPath(data.m_dwRace); actorData.m_pActorInstance = actor;
if (!modelPath.empty()) { std::fill(std::begin(actorData.m_awPart), std::end(actorData.m_awPart), 0u);
actor->SetModel(modelPath); // 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))
if (data.m_dwWeapon > 0) { std::cerr << "[AVA2 TraceError] CInstanceBase::Create - SetRace(" << actorData.m_dwRace << ") failed" << std::endl;
std::string weaponPath = GetWeaponModelPath(data.m_dwWeapon); if (npcRace != -1) {
if (!weaponPath.empty()) { SetArmor(actorData, actorData.m_dwArmor);
actor->SetWeapon(weaponPath, "equip_right_hand"); SetWeapon(actorData, actorData.m_dwWeapon);
} SetHair(actorData, actorData.m_dwHair);
} SetSash(data.m_dwVID, sash);
} else {
if (data.m_dwHair > 0) { SetArmor(actorData, actorData.m_dwArmor);
std::string hairPath = GetHairModelPath(data.m_dwHair); if (IsPC(actorData)) {
if (!hairPath.empty()) { SetHair(actorData, actorData.m_dwHair);
actor->AttachPart(hairPath); 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. // AVA2 InstanceBase::SetAffect(AFFECT_STUN=5) controls the sleep action flag.
actor->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0); actor->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0);
actorData.m_pActorInstance = actor;
// Register TextTail overhead display // Register TextTail overhead display
auto& tt = TextTailManager::Instance(); auto& tt = TextTailManager::Instance();
uint32_t nameColor = (data.m_bType == 0) ? 0xFFFF4444 : 0xFFFFFFFF; // Red for mobs, white for players // AttachTextTail registers white; RefreshTextTail below applies GetNameColor/title.
tt.RegisterCharacterTextTail(data.m_dwGuildID, data.m_dwVID, nameColor); tt.RegisterCharacterTextTail(data.m_dwGuildID, data.m_dwVID, 0xFFFFFFFF);
tt.SetCharacterName(data.m_dwVID, data.m_stName); tt.SetCharacterName(data.m_dwVID, data.m_stName);
tt.SetCharacterPosition(data.m_dwVID, worldX, worldY, worldZ); 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); tt.SetGuildName(data.m_dwVID, data.m_stGuildName);
} }
if (data.m_sAlignment != 0) { RefreshTextTail(data.m_dwVID);
uint32_t titleColor = 0xFFFFFFFF;
std::string title = GetAlignmentTitle(data.m_sAlignment, titleColor);
if (!title.empty()) {
tt.AttachTitle(data.m_dwVID, title, titleColor);
}
}
if (IsMainActorVID(data.m_dwVID)) { if (IsMainActorVID(data.m_dwVID)) {
m_mainPosX = data.m_lCurX; m_mainPosX = data.m_lCurX;
@@ -147,7 +504,12 @@ void NetworkActorManager::AppendActor(const SNetworkActorData& data) {
void NetworkActorManager::RemoveActor(uint32_t vid) { void NetworkActorManager::RemoveActor(uint32_t vid) {
auto it = m_actors.find(vid); auto it = m_actors.find(vid);
if (it != m_actors.end()) { if (it != m_actors.end()) {
DestroyAttachedEffects(it->second);
m_actors.erase(it); 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); TextTailManager::Instance().DeleteCharacterTextTail(vid);
} }
@@ -157,7 +519,6 @@ void NetworkActorManager::UpdateActor(const SNetworkUpdateActorData& data) {
if (it == m_actors.end()) return; if (it == m_actors.end()) return;
auto& actorData = it->second; auto& actorData = it->second;
actorData.m_dwSash = data.m_dwSash;
actorData.m_dwArrowType = data.m_dwArrowType; actorData.m_dwArrowType = data.m_dwArrowType;
actorData.m_dwConquerorLevel = data.m_dwConquerorLevel; actorData.m_dwConquerorLevel = data.m_dwConquerorLevel;
actorData.m_dwStateFlags = data.m_dwStateFlags; 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); std::copy_n(data.m_shining, CHR_SHINING_NUM, actorData.m_shining);
actorData.m_dwArmor = data.m_dwArmor; actorData.m_dwArmor = data.m_dwArmor;
actorData.m_dwWeapon = data.m_dwWeapon; 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_dwGuildID = data.m_dwGuildID;
actorData.m_sAlignment = data.m_sAlignment; actorData.m_sAlignment = data.m_sAlignment;
actorData.m_byPKMode = data.m_byPKMode; actorData.m_byPKMode = data.m_byPKMode;
@@ -173,33 +534,20 @@ void NetworkActorManager::UpdateActor(const SNetworkUpdateActorData& data) {
actorData.m_dwMovSpd = data.m_dwMovSpd; actorData.m_dwMovSpd = data.m_dwMovSpd;
actorData.m_dwAtkSpd = data.m_dwAtkSpd; 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) { if (actorData.m_pActorInstance) {
actorData.m_pActorInstance->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0); 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) { if (data.m_dwMovSpd > 0) {
actorData.m_pActorInstance->SetSpeed(static_cast<float>(data.m_dwMovSpd)); actorData.m_pActorInstance->SetSpeed(static_cast<float>(data.m_dwMovSpd));
} }
} }
auto& tt = TextTailManager::Instance(); ChangeSash(data.m_dwVID, data.m_dwSash);
if (data.m_sAlignment != 0) { // ChangeGuild / SetAlignment / SetStateFlags(KILLER) each end in RefreshTextTail.
uint32_t titleColor = 0xFFFFFFFF; RefreshTextTail(data.m_dwVID);
std::string title = GetAlignmentTitle(data.m_sAlignment, titleColor);
if (!title.empty()) {
tt.AttachTitle(data.m_dwVID, title, titleColor);
}
}
} }
void NetworkActorManager::MoveActor(const SNetworkMoveActorData& data) { 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) { for (auto& [vid, actorData] : m_actors) {
if (!actorData.m_pActorInstance) continue; if (!actorData.m_pActorInstance) continue;
@@ -305,16 +653,145 @@ void NetworkActorManager::Update(float dt, const TerrainHeightmap* terrain) {
} }
actorData.m_pActorInstance->Update(dt, 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() { 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_actors.clear();
m_hasSelected = false;
m_hasPicked = false;
ClearPVPKeySystem();
m_mainVID = 0; m_mainVID = 0;
m_mainPosX = 0; m_mainPosX = 0;
m_mainPosY = 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<ActorInstance>();
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
<< "<AFFECT_NUM:" << isVisible << ", isVisible=0)" << std::endl;
return;
}
uint32_t& eft = actor->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) { SNetworkActorData* NetworkActorManager::GetActorData(uint32_t vid) {
auto it = m_actors.find(vid); auto it = m_actors.find(vid);
return (it != m_actors.end()) ? &it->second : nullptr; return (it != m_actors.end()) ? &it->second : nullptr;
@@ -334,7 +811,7 @@ std::vector<Render3DDraw> NetworkActorManager::BuildDrawCommands(float animTime)
(void)animTime; (void)animTime;
std::vector<Render3DDraw> allDraws; std::vector<Render3DDraw> allDraws;
for (auto& [vid, actorData] : m_actors) { 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(); auto actorDraws = actorData.m_pActorInstance->BuildDrawCommands();
for (auto& d : actorDraws) { for (auto& d : actorDraws) {
allDraws.push_back(std::move(d)); allDraws.push_back(std::move(d));
@@ -343,4 +820,56 @@ std::vector<Render3DDraw> NetworkActorManager::BuildDrawCommands(float animTime)
return allDraws; 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 } // namespace ava2
+166 -2
View File
@@ -6,14 +6,28 @@
#include <unordered_map> #include <unordered_map>
#include <memory> #include <memory>
#include <vector> #include <vector>
#include <set>
#include <utility>
namespace ava2 { 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 { struct SNetworkActorData {
uint32_t m_dwVID = 0; uint32_t m_dwVID = 0;
std::string m_stName; std::string m_stName;
uint8_t m_bType = 0; // 0=Mob, 1=NPC, 6=PC uint8_t m_bType = 0; // 0=Mob, 1=NPC, 6=PC
uint32_t m_dwRace = 0; 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_dwLevel = 0;
uint32_t m_dwGuildID = 0; uint32_t m_dwGuildID = 0;
std::string m_stGuildName; std::string m_stGuildName;
@@ -49,13 +63,33 @@ struct SNetworkActorData {
uint32_t m_dwMountVnum = 0; uint32_t m_dwMountVnum = 0;
uint32_t m_dwOwnerVID = 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; bool m_isMoving = false;
float m_moveElapsed = 0.0f; 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<SAttachedEffect> 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<ActorInstance> m_pActorInstance; std::shared_ptr<ActorInstance> m_pActorInstance;
}; };
// CInstanceBase::IsGameMaster: a "[" in the name or AFFECT_YMIR.
bool IsGameMaster(const SNetworkActorData& actor);
struct SNetworkMoveActorData { struct SNetworkMoveActorData {
uint32_t m_dwVID = 0; uint32_t m_dwVID = 0;
uint32_t m_dwTime = 0; uint32_t m_dwTime = 0;
@@ -67,6 +101,16 @@ struct SNetworkMoveActorData {
uint32_t m_dwDuration = 0; 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 { struct SNetworkUpdateActorData {
uint32_t m_dwVID = 0; uint32_t m_dwVID = 0;
uint32_t m_dwArmor = 0; uint32_t m_dwArmor = 0;
@@ -110,8 +154,117 @@ public:
void SyncActor(uint32_t vid, int32_t lPosX, int32_t lPosY); void SyncActor(uint32_t vid, int32_t lPosX, int32_t lPosY);
void SetActorOwner(uint32_t ownerVID, uint32_t victimVID); 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(); 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); SNetworkActorData* GetActorData(uint32_t vid);
const SNetworkActorData* GetActorData(uint32_t vid) const; const SNetworkActorData* GetActorData(uint32_t vid) const;
@@ -127,6 +280,17 @@ private:
int32_t m_mainPosY = 0; int32_t m_mainPosY = 0;
std::unordered_map<uint32_t, SNetworkActorData> m_actors; std::unordered_map<uint32_t, SNetworkActorData> 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<uint32_t,uint32_t> PVPKey(uint32_t src, uint32_t dst) { return src>dst?std::make_pair(dst,src):std::make_pair(src,dst); }
std::set<std::pair<uint32_t,uint32_t>> m_pvpKeys, m_duelKeys, m_gvgKeys;
}; };
} // namespace ava2 } // namespace ava2
+549 -7
View File
@@ -53,6 +53,7 @@ enum EPacketCG {
HEADER_CG_HANDSHAKE = 0xff, HEADER_CG_HANDSHAKE = 0xff,
HEADER_CG_PONG = 0xfe, HEADER_CG_PONG = 0xfe,
HEADER_CG_TIME_SYNC = 0xfc, HEADER_CG_TIME_SYNC = 0xfc,
HEADER_CG_XTRAP_ACK = 204,
HEADER_CG_LOGIN = 1, HEADER_CG_LOGIN = 1,
HEADER_CG_ATTACK = 225, HEADER_CG_ATTACK = 225,
HEADER_CG_CHAT = 231, HEADER_CG_CHAT = 231,
@@ -91,6 +92,53 @@ enum EPacketCG {
HEADER_CG_GIVE_ITEM = 83, HEADER_CG_GIVE_ITEM = 83,
HEADER_CG_REFINE = 96, HEADER_CG_REFINE = 96,
HEADER_CG_CLIENT_VERSION2 = 241, 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 { enum EPacketGC {
@@ -151,6 +199,61 @@ enum EPacketGC {
HEADER_GC_SKILL_LEVEL=72, HEADER_GC_SKILL_LEVEL=72,
HEADER_GC_SKILL_LEVEL_NEW=76, HEADER_GC_SKILL_LEVEL_NEW=76,
HEADER_GC_TIME = 106, 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_PHASE = 0xfd,
HEADER_GC_HANDSHAKE = 0xff, HEADER_GC_HANDSHAKE = 0xff,
}; };
@@ -200,6 +303,24 @@ enum EChatType {
CHAT_TYPE_SHOUT = 6, CHAT_TYPE_SHOUT = 6,
CHAT_TYPE_WHISPER = 7, CHAT_TYPE_WHISPER = 7,
CHAT_TYPE_BIG_NOTICE = 8, 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) #pragma pack(push, 1)
@@ -509,6 +630,8 @@ struct TPacketGCWhisper {
uint16_t wSize; uint16_t wSize;
uint8_t bType; uint8_t bType;
char szNameFrom[CHARACTER_NAME_MAX_LEN + 1]; char szNameFrom[CHARACTER_NAME_MAX_LEN + 1];
uint8_t bLanguage; // ENABLE_MULTILANGUAGE_SYSTEM
uint8_t bEmpire;
}; };
struct TPacketGCDamageInfo { struct TPacketGCDamageInfo {
@@ -667,13 +790,6 @@ struct TPacketCGSafeboxCheckout {
TItemPos ItemPos; TItemPos ItemPos;
}; };
struct TPacketCGSafeboxItemMove {
uint8_t header;
uint8_t bSourcePos;
uint8_t bTargetPos;
uint8_t bCount;
};
struct TPacketCGSafeboxMoney { struct TPacketCGSafeboxMoney {
uint8_t header; uint8_t header;
uint8_t bState; uint8_t bState;
@@ -694,13 +810,439 @@ struct TPacketGCSafeboxWrongPassword {
uint8_t bHeader; 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) #pragma pack(pop)
static_assert(sizeof(TPacketCGExchange) == 14, "TPacketCGExchange must match upstream");
static_assert(sizeof(TPacketCGRefine) == 5, "TPacketCGRefine must match upstream"); static_assert(sizeof(TPacketCGRefine) == 5, "TPacketCGRefine must match upstream");
static_assert(sizeof(TPacketCGItemUseToItem) == 7, "TPacketCGItemUseToItem must match upstream"); static_assert(sizeof(TPacketCGItemUseToItem) == 7, "TPacketCGItemUseToItem must match upstream");
static_assert(sizeof(TPacketCGGiveItem) == 12, "TPacketCGGiveItem must match upstream"); static_assert(sizeof(TPacketCGGiveItem) == 12, "TPacketCGGiveItem must match upstream");
static_assert(sizeof(TPacketCGScriptAnswer) == 2, "TPacketCGScriptAnswer 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"); 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 } // namespace ava2
+568 -79
View File
@@ -1,8 +1,14 @@
#include "item_sound.h"
#include "PythonNetworkStream.h" #include "PythonNetworkStream.h"
#include "python_net.h"
#include "guild_state.h"
#include "switchbot_state.h"
#include "protocol.h" #include "protocol.h"
#include "shared/common/PythonUtils.h"
#include "nonplayer_data.h" #include "nonplayer_data.h"
#include "python_app.h" #include "python_app.h"
#include "python_gameplay_modules.h" #include "python_gameplay_modules.h"
#include "python_chat.h"
#include "python_native_modules.h" #include "python_native_modules.h"
#include "PythonExchange.h" #include "PythonExchange.h"
#include "PythonSafeBox.h" #include "PythonSafeBox.h"
@@ -11,6 +17,7 @@
#include "eter_sound/SoundManager.h" #include "eter_sound/SoundManager.h"
#include "eter_effect/EffectManager.h" #include "eter_effect/EffectManager.h"
#include "eter_effect/FlyingManager.h" #include "eter_effect/FlyingManager.h"
#include <algorithm>
#include <iostream> #include <iostream>
#include <bit> #include <bit>
#include <stdexcept> #include <stdexcept>
@@ -79,14 +86,30 @@ void PythonNetworkStream::StartGame() {
} }
void PythonNetworkStream::ResetConnection() { 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(); ResetPlayerState();NetworkActorManager::Instance().Clear();
m_pendingActorData={};m_strFieldMusicFileName.clear();m_fFieldMusicVolume=0.02f; m_pendingActorData={};m_strFieldMusicFileName.clear();m_fFieldMusicVolume=0.02f;
m_phase=PHASE_OFFLINE;m_dwMainActorVID=0;m_wMainActorRace=0; m_phase=PHASE_OFFLINE;m_dwMainActorVID=0;m_wMainActorRace=0;
m_byMainActorEmpire=m_byMainActorSkillGroup=0;m_strMainActorName.clear(); m_byMainActorEmpire=m_byMainActorSkillGroup=0;m_strMainActorName.clear();
} }
std::vector<std::vector<uint8_t>> PythonNetworkStream::PopSendPackets() { std::vector<std::vector<uint8_t>> 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<std::pair<std::vector<uint8_t>,bool>> PythonNetworkStream::PopSendPacketsWithSequence() {
std::vector<std::pair<std::vector<uint8_t>,bool>> packets;
for(size_t i=0;i<m_sendPackets.size();++i) packets.emplace_back(std::move(m_sendPackets[i]),m_sendSequence[i]);
m_sendPackets.clear();m_sendSequence.clear();m_sendBuffer.clear();
return packets;
}
void PythonNetworkStream::SetGuildID(uint32_t id) {
if(m_guildID==id)return;
m_guildID=id;
auto it=GetGuildState().names.find(id);
update_player_guild(id,it==GetGuildState().names.end()?"":it->second);
} }
void PythonNetworkStream::SetMainActorVID(uint32_t vid) { 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<const uint8_t*>(data); const uint8_t* bytes = static_cast<const uint8_t*>(data);
m_sendBuffer.insert(m_sendBuffer.end(), bytes, bytes + size); m_sendBuffer.insert(m_sendBuffer.end(), bytes, bytes + size);
m_sendPackets.emplace_back(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<uint8_t> PythonNetworkStream::PopSendBytes() { std::vector<uint8_t> PythonNetworkStream::PopSendBytes() {
std::vector<uint8_t> result = std::move(m_sendBuffer); std::vector<uint8_t> result = std::move(m_sendBuffer);
m_sendBuffer.clear();m_sendPackets.clear(); m_sendBuffer.clear();m_sendPackets.clear();m_sendSequence.clear();
return result; 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] "<<text<<std::endl; }
}
// CPythonNetworkStream::CheckPacket: skip padding, reject unmapped headers and wait
// until the whole static/dynamic packet is buffered.
bool PythonNetworkStream::CheckPacket(uint8_t* retHeader) {
*retHeader=0;
while(!m_recvBuffer.empty() && m_recvBuffer.front()==0) m_recvBuffer.erase(m_recvBuffer.begin());
if(m_recvBuffer.empty()) return false;
const uint8_t header=m_recvBuffer.front();
const auto* type=gc_packet_type(header);
if(!type || !type->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()<need) return false;
*retHeader=header;
m_lastPacket[0]=m_lastPacket[1];m_lastPacket[1]=header;
return true;
}
bool PythonNetworkStream::ProcessRecvData() { bool PythonNetworkStream::ProcessRecvData() {
if(m_startGameRequested) { m_startGameRequested=false;inventory_callback(m_poHandler,"SetGamePhase",nullptr); } if(m_startGameRequested) { m_startGameRequested=false;inventory_callback(m_poHandler,"SetGamePhase",nullptr); }
bool progress = false; bool progress = false;
while (!m_recvBuffer.empty()) { uint8_t header = 0;
uint8_t header = 0; while (CheckPacket(&header)) {
if (!Peek(sizeof(header), &header)) break; const auto* type=gc_packet_type(header);
bool ret;
bool handled = DispatchGamePhasePacket(header); // LoadingPhase() handles MAIN_CHARACTER* itself and falls back to GamePhase();
if (!handled) { // GamePhase() has no case for them, so in Game they hit RecvDefaultPacket.
// Unhandled or incomplete packet: wait for more data or stop const bool loadingOnly=header==HEADER_GC_MAIN_CHARACTER || header==HEADER_GC_MAIN_CHARACTER2_EMPIRE ||
break; header==HEADER_GC_MAIN_CHARACTER3_BGM || header==HEADER_GC_MAIN_CHARACTER4_BGM_VOL;
if(loadingOnly && m_phase==PHASE_GAME) {
trace_error("Unprocessed packet header "+std::to_string(header)+", state Game");
m_recvBuffer.clear();
} else if(DispatchGamePhasePacket(header,ret)) {
// RecvErrorPacket
if(!ret) { trace_error("Phase Game does not handle this header (header: "+std::to_string(header)+")");m_recvBuffer.clear(); }
} else if(type->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; 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_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_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; 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) { 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 44: { uint8_t ping;if(!Read(1,&ping)) return false;const uint8_t pong=254;Send(&pong,1);return true; }
case HEADER_GC_PHASE: case HEADER_GC_PHASE:
return RecvPhasePacket(); return RecvPhasePacket();
case HEADER_GC_SHOP: return RecvShopPacket(); case HEADER_GC_SHOP: return RecvShopPacket();
case HEADER_GC_OFFLINE_SHOP: return RecvOfflineShopPacket();
case HEADER_GC_MAIN_CHARACTER: case HEADER_GC_MAIN_CHARACTER:
return RecvMainCharacter(); return RecvMainCharacter();
case HEADER_GC_MAIN_CHARACTER2_EMPIRE: case HEADER_GC_MAIN_CHARACTER2_EMPIRE:
@@ -250,8 +353,81 @@ bool PythonNetworkStream::DispatchGamePhasePacket(uint8_t header) {
return RecvMallSetPacket(); return RecvMallSetPacket();
case HEADER_GC_MALL_DEL: case HEADER_GC_MALL_DEL:
return RecvMallDelPacket(); 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: default:
// Unknown packet header m_dispatchUnported=true;
return false; return false;
} }
} }
@@ -407,6 +583,7 @@ bool PythonNetworkStream::RecvCharacterAppendPacketNew() {
data.m_dwEmpireID=p.bEmpire; data.m_dwGuildID=p.dwGuild; 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; data.m_sAlignment=p.sAlignment; data.m_byPKMode=p.bPKMode; data.m_dwMountVnum=p.dwMountVnum;
NetworkActorManager::Instance().AppendActor(data); NetworkActorManager::Instance().AppendActor(data);
if(data.m_dwVID==m_dwMainActorVID)SetGuildID(data.m_dwGuildID);
return true; return true;
} }
@@ -437,6 +614,7 @@ bool PythonNetworkStream::RecvCharacterAdditionalInfo() {
actorData.m_dwMountVnum = p.dwMountVnum; actorData.m_dwMountVnum = p.dwMountVnum;
NetworkActorManager::Instance().AppendActor(actorData); NetworkActorManager::Instance().AppendActor(actorData);
if(actorData.m_dwVID==m_dwMainActorVID)SetGuildID(actorData.m_dwGuildID);
return true; return true;
} }
@@ -463,6 +641,7 @@ bool PythonNetworkStream::RecvCharacterUpdatePacket() {
upd.m_dwAtkSpd = p.bAttackSpeed; upd.m_dwAtkSpd = p.bAttackSpeed;
NetworkActorManager::Instance().UpdateActor(upd); NetworkActorManager::Instance().UpdateActor(upd);
if(upd.m_dwVID==m_dwMainActorVID)SetGuildID(upd.m_dwGuildID);
return true; return true;
} }
@@ -492,6 +671,7 @@ bool PythonNetworkStream::RecvCharacterUpdatePacketNew() {
upd.m_dwAtkSpd = p.bAttackSpeed; upd.m_dwAtkSpd = p.bAttackSpeed;
NetworkActorManager::Instance().UpdateActor(upd); NetworkActorManager::Instance().UpdateActor(upd);
if(upd.m_dwVID==m_dwMainActorVID)SetGuildID(upd.m_dwGuildID);
return true; return true;
} }
@@ -540,48 +720,104 @@ bool PythonNetworkStream::RecvSyncPositionPacket() {
return true; return true;
} }
// CPythonNetworkStream::RecvChatPacket (ENABLE_MULTILANGUAGE_SYSTEM branch).
bool PythonNetworkStream::RecvChatPacket() { bool PythonNetworkStream::RecvChatPacket() {
TPacketGCChat p; TPacketGCChat kChat;
if (!Peek(sizeof(p), &p)) return false; if (!Peek(sizeof(kChat), &kChat)) return false;
if(p.size<sizeof(p)) throw std::runtime_error("invalid AVA2 chat packet length"); if (kChat.size < sizeof(kChat)) throw std::runtime_error("invalid AVA2 chat packet length");
if (m_recvBuffer.size() < p.size) return false; if (m_recvBuffer.size() < kChat.size) return false;
Read(sizeof(p), &p); Read(sizeof(kChat), &kChat);
size_t textLen = p.size - sizeof(p); std::string text(kChat.size - sizeof(kChat), '\0');
std::string text(textLen, '\0'); if (!text.empty()) Read(text.size(), text.data());
if (textLen > 0) { text.resize(strnlen(text.c_str(), text.size())); // buf[uChatSize]='\0' + C-string use
Read(textLen, text.data());
if (kChat.type >= CHAT_TYPE_MAX_NUM)
return true;
if (CHAT_TYPE_COMMAND == kChat.type) {
ServerCommand(text);
return true;
} }
// Strip trailing null characters if (kChat.dwVID != 0) {
while (!text.empty() && text.back() == '\0') text.pop_back(); auto& actors = NetworkActorManager::Instance();
const SNetworkActorData* chatter = actors.GetActorData(kChat.dwVID);
if (!chatter)
return true;
if (m_chatCallback) { std::string line;
m_chatCallback(p.type, text, p.dwVID); 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) { if (CHAT_TYPE_SHOUT != kChat.type)
TextTailManager::Instance().RegisterChatTail(p.dwVID, text); 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; return true;
} }
// CPythonNetworkStream::RecvWhisperPacket (ENABLE_MULTILANGUAGE_SYSTEM).
bool PythonNetworkStream::RecvWhisperPacket() { bool PythonNetworkStream::RecvWhisperPacket() {
TPacketGCWhisper p; TPacketGCWhisper whisperPacket;
if (!Peek(sizeof(p), &p)) return false; if (!Peek(sizeof(whisperPacket), &whisperPacket)) return false;
if(p.wSize<sizeof(p)) throw std::runtime_error("invalid AVA2 dynamic packet length"); if (whisperPacket.wSize < sizeof(whisperPacket)) throw std::runtime_error("invalid AVA2 dynamic packet length");
if (m_recvBuffer.size() < p.wSize) return false; if (m_recvBuffer.size() < whisperPacket.wSize) return false;
Read(sizeof(p), &p); Read(sizeof(whisperPacket), &whisperPacket);
size_t textLen = p.wSize - sizeof(p); std::string buf(whisperPacket.wSize - sizeof(whisperPacket), '\0');
std::string text(textLen, '\0'); if (!buf.empty()) Read(buf.size(), buf.data());
if (textLen > 0) { buf.resize(strnlen(buf.c_str(), buf.size()));
Read(textLen, text.data()); char name[sizeof(whisperPacket.szNameFrom) + 1] {};
} std::memcpy(name, whisperPacket.szNameFrom, sizeof(whisperPacket.szNameFrom));
while (!text.empty() && text.back() == '\0') text.pop_back();
if (m_whisperCallback) { if (m_whisperCallback)
m_whisperCallback(p.bType, p.szNameFrom, text); 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; return true;
} }
@@ -662,12 +898,7 @@ template<class Packet> TItemData item_data(const Packet& p) {
return data; return data;
} }
void inventory_callback(PyObject* target,const char* name,PyObject* args) { void inventory_callback(PyObject* target,const char* name,PyObject* args) {
if(!target) { Py_XDECREF(args);return; } PyCallClassMemberFunc(target,name,args); // ScriptLib semantics: skip missing, PyErr_Print on error
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);
} }
} }
bool PythonNetworkStream::RecvItemSetPacket() { bool PythonNetworkStream::RecvItemSetPacket() {
@@ -811,6 +1042,66 @@ bool main_actor_can_act(uint32_t vid) {
return actor && actor->CanAct(); return actor && actor->CanAct();
} }
} }
bool PythonNetworkStream::SendPrivateShopSearchInfo(const TPacketCGShopSearch& p) {
if(!main_actor_can_act(m_dwMainActorVID))return true;
std::vector<uint8_t> bytes{HEADER_CG_SHOP_SEARCH};
auto put=[&](uint64_t value,unsigned width) { for(unsigned i=0;i<width;++i)bytes.push_back(uint8_t(value>>(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<uint8_t> 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<uint8_t,10> 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) { bool PythonNetworkStream::SendQuickSlotAddPacket(uint8_t index,uint8_t type,uint8_t pos) {
if(!main_actor_can_act(m_dwMainActorVID)) return true; 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; 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; 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(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; auto bytes=wire::chat(text,type);Send(bytes.data(),bytes.size());return true;
} }
bool PythonNetworkStream::SendWhisperPacket(const std::string& name,const std::string& text) { 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) { bool PythonNetworkStream::SendItemUsePacket(uint8_t window, uint16_t cell) {
if(!main_actor_can_act(m_dwMainActorVID)) return true; 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; TPacketCGItemUse p;
p.header = HEADER_CG_ITEM_USE; p.header = HEADER_CG_ITEM_USE;
p.Cell.window_type = window; 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) { 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(!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; TPacketCGItemMove p;
p.header = HEADER_CG_ITEM_MOVE; p.header = HEADER_CG_ITEM_MOVE;
p.Cell.window_type = srcWindow; p.Cell.window_type = srcWindow;
@@ -1092,19 +1404,31 @@ bool PythonNetworkStream::RecvExchangePacket() {
return true; 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{}; TPacketCGExchange p{};
p.header = HEADER_CG_EXCHANGE; 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; p.arg1 = vid;
Send(&p, sizeof(p)); Send(&p, sizeof(p));
return true; return true;
} }
bool PythonNetworkStream::SendExchangeItemAddPacket(uint8_t window, uint16_t cell, uint8_t exchangePos) { bool PythonNetworkStream::SendExchangeItemAddPacket(uint8_t window, uint16_t cell, uint8_t exchangePos) {
TPacketCGExchange p{}; if (!main_actor_can_act(m_dwMainActorVID)) return true;
p.header = HEADER_CG_EXCHANGE; auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_ITEM_ADD);
p.subheader = EXCHANGE_SUBHEADER_CG_ITEM_ADD;
p.Pos.window_type = window; p.Pos.window_type = window;
p.Pos.cell = cell; p.Pos.cell = cell;
p.arg2 = exchangePos; p.arg2 = exchangePos;
@@ -1112,36 +1436,29 @@ bool PythonNetworkStream::SendExchangeItemAddPacket(uint8_t window, uint16_t cel
return true; return true;
} }
bool PythonNetworkStream::SendExchangeItemDelPacket(uint8_t exchangePos) { bool PythonNetworkStream::SendExchangeItemDelPacket(uint8_t) {
TPacketCGExchange p{}; // Windows: assert(!"Can't be called function"); return true; -- nothing is sent.
p.header = HEADER_CG_EXCHANGE;
p.subheader = EXCHANGE_SUBHEADER_CG_ITEM_DEL;
p.arg2 = exchangePos;
Send(&p, sizeof(p));
return true; return true;
} }
bool PythonNetworkStream::SendExchangeElkAddPacket(int64_t elk) { bool PythonNetworkStream::SendExchangeElkAddPacket(int64_t elk) {
TPacketCGExchange p{}; if (!main_actor_can_act(m_dwMainActorVID)) return true;
p.header = HEADER_CG_EXCHANGE; auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_ELK_ADD);
p.subheader = EXCHANGE_SUBHEADER_CG_ELK_ADD;
p.arg1 = elk; p.arg1 = elk;
Send(&p, sizeof(p)); Send(&p, sizeof(p));
return true; return true;
} }
bool PythonNetworkStream::SendExchangeAcceptPacket() { bool PythonNetworkStream::SendExchangeAcceptPacket() {
TPacketCGExchange p{}; if (!main_actor_can_act(m_dwMainActorVID)) return true;
p.header = HEADER_CG_EXCHANGE; auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_ACCEPT);
p.subheader = EXCHANGE_SUBHEADER_CG_ACCEPT;
Send(&p, sizeof(p)); Send(&p, sizeof(p));
return true; return true;
} }
bool PythonNetworkStream::SendExchangeExitPacket() { bool PythonNetworkStream::SendExchangeExitPacket() {
TPacketCGExchange p{}; if (!main_actor_can_act(m_dwMainActorVID)) return true;
p.header = HEADER_CG_EXCHANGE; auto p = exchange_packet(EXCHANGE_SUBHEADER_CG_CANCEL);
p.subheader = EXCHANGE_SUBHEADER_CG_CANCEL;
Send(&p, sizeof(p)); Send(&p, sizeof(p));
return true; return true;
} }
@@ -1206,6 +1523,7 @@ bool PythonNetworkStream::RecvMallDelPacket() {
} }
bool PythonNetworkStream::SendSafeBoxCheckinPacket(uint8_t window, uint16_t cell, uint8_t safeboxPos) { bool PythonNetworkStream::SendSafeBoxCheckinPacket(uint8_t window, uint16_t cell, uint8_t safeboxPos) {
PlayItemDropSound(GetPlayerItemData(window,cell).vnum);
TPacketCGSafeboxCheckin p{}; TPacketCGSafeboxCheckin p{};
p.header = HEADER_CG_SAFEBOX_CHECKIN; p.header = HEADER_CG_SAFEBOX_CHECKIN;
p.bSafeBoxPos = safeboxPos; 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) { 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{}; TPacketCGSafeboxCheckout p{};
p.header = HEADER_CG_SAFEBOX_CHECKOUT; p.header = HEADER_CG_SAFEBOX_CHECKOUT;
p.bSafeBoxPos = safeboxPos; p.bSafeBoxPos = safeboxPos;
@@ -1225,13 +1544,12 @@ bool PythonNetworkStream::SendSafeBoxCheckoutPacket(uint8_t safeboxPos, uint8_t
return true; return true;
} }
bool PythonNetworkStream::SendSafeBoxItemMovePacket(uint8_t srcPos, uint8_t dstPos, uint8_t count) { bool PythonNetworkStream::SendSafeBoxItemMovePacket(uint8_t srcPos, uint8_t dstPos, uint32_t count) {
TPacketCGSafeboxItemMove p{}; uint32_t vnum;if(CPythonSafeBox::Instance().GetSlotItemID(srcPos,&vnum))PlayItemDropSound(vnum);
p.header = HEADER_CG_SAFEBOX_ITEM_MOVE; // Windows sends TPacketCGItemMove {header, pos, change_pos, DWORD num} under HEADER_CG_SAFEBOX_ITEM_MOVE.
p.bSourcePos = srcPos; std::vector<uint8_t> bytes{HEADER_CG_SAFEBOX_ITEM_MOVE,1,srcPos,0,1,dstPos,0};
p.bTargetPos = dstPos; for(int shift=0;shift<32;shift+=8) bytes.push_back(static_cast<uint8_t>(count>>shift));
p.bCount = count; Send(bytes.data(), bytes.size());
Send(&p, sizeof(p));
return true; 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) { 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{}; TPacketCGSafeboxCheckout p{};
p.header = HEADER_CG_MALL_CHECKOUT; p.header = HEADER_CG_MALL_CHECKOUT;
p.bSafeBoxPos = safeboxPos; p.bSafeBoxPos = safeboxPos;
@@ -1254,6 +1573,156 @@ namespace {
void append16(std::vector<uint8_t>& bytes,uint16_t value) { bytes.push_back(value);bytes.push_back(value>>8); } void append16(std::vector<uint8_t>& bytes,uint16_t value) { bytes.push_back(value);bytes.push_back(value>>8); }
void append32(std::vector<uint8_t>& bytes,uint32_t value) { for(int shift=0;shift<32;shift+=8) bytes.push_back(value>>shift); } void append32(std::vector<uint8_t>& 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<uint8_t>& 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<copy && text[i];++i) bytes[start+i]=static_cast<uint8_t>(text[i]);
}
std::vector<uint8_t> guild_packet(uint8_t subheader) { return {HEADER_CG_GUILD,subheader}; }
}
// ── Script / quest (AVA2 PythonNetworkStreamPhaseGame.cpp) ──
bool PythonNetworkStream::SendAnswerMakeGuildPacket(const char* name) {
std::vector<uint8_t> 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<uint8_t> 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<uint8_t> 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<uint8_t> bytes{HEADER_CG_QUEST_CONFIRM,answer};append32(bytes,pid);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendSelectItemPacket(uint32_t itemPos) {
std::vector<uint8_t> bytes{HEADER_CG_SCRIPT_SELECT_ITEM};append32(bytes,itemPos);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendTargetInfoLoadPacket(uint32_t vid) {
std::vector<uint8_t> 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<uint8_t> 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<uint8_t> 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<uint8_t> 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<uint8_t> 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<uint8_t> 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<uint8_t> 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<uint8_t> 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<uint8_t> 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<uint8_t>(static_cast<uint8_t>(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<std::chrono::milliseconds(1000)) return true;
m_lastGuildCommentRefresh=now;
auto bytes=guild_packet(GUILD_SUBHEADER_CG_REFRESH_COMMENT);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendGuildChangeMemberGradePacket(uint32_t pid,uint8_t grade) {
auto bytes=guild_packet(GUILD_SUBHEADER_CG_CHANGE_MEMBER_GRADE);append32(bytes,pid);bytes.push_back(grade);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendGuildUseSkillPacket(uint32_t skillID,uint32_t targetVID) {
auto bytes=guild_packet(GUILD_SUBHEADER_CG_USE_SKILL);append32(bytes,skillID);append32(bytes,targetVID);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendGuildChangeMemberGeneralPacket(uint32_t pid,uint8_t flag) {
auto bytes=guild_packet(GUILD_SUBHEADER_CG_CHANGE_MEMBER_GENERAL);append32(bytes,pid);bytes.push_back(flag);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendGuildInviteAnswerPacket(uint32_t guildID,uint8_t answer) {
auto bytes=guild_packet(GUILD_SUBHEADER_CG_GUILD_INVITE_ANSWER);append32(bytes,guildID);bytes.push_back(answer);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendGuildChargeGSPPacket(uint32_t money) {
auto bytes=guild_packet(GUILD_SUBHEADER_CG_CHARGE_GSP);append32(bytes,money);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendGuildDepositMoneyPacket(uint32_t money) {
auto bytes=guild_packet(GUILD_SUBHEADER_CG_DEPOSIT_MONEY);append32(bytes,money);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendGuildWithdrawMoneyPacket(uint32_t money) {
auto bytes=guild_packet(GUILD_SUBHEADER_CG_WITHDRAW_MONEY);append32(bytes,money);
Send(bytes.data(),bytes.size());return true;
}
bool PythonNetworkStream::SendRefinePacket(uint8_t pos,uint8_t type,uint8_t storage,int32_t index) { bool PythonNetworkStream::SendRefinePacket(uint8_t pos,uint8_t type,uint8_t storage,int32_t index) {
const uint8_t bytes[]={HEADER_CG_REFINE,pos,type,storage,static_cast<uint8_t>(index)}; const uint8_t bytes[]={HEADER_CG_REFINE,pos,type,storage,static_cast<uint8_t>(index)};
Send(bytes,sizeof(bytes));return true; Send(bytes,sizeof(bytes));return true;
@@ -1279,3 +1748,23 @@ bool PythonNetworkStream::SendScriptButtonPacket(int button) {
} }
} // namespace ava2 } // namespace ava2
namespace ava2 {
bool PythonNetworkStream::SendBuildOfflineShopPacket(const std::string& name,const std::vector<TOfflineShopItemTable>& items,uint32_t vnum,uint8_t title) {
// Serialize the original Win32 packed layout. Original unused fields are zeroed.
std::vector<uint8_t> 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<uint8_t>(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<width;++i)bytes.push_back(uint8_t(value>>(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<uint8_t> 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;
}
}
+181 -6
View File
@@ -3,12 +3,15 @@
#include "Packet.h" #include "Packet.h"
#include "NetworkActorManager.h" #include "NetworkActorManager.h"
#include <Python.h> #include <Python.h>
#include <chrono>
#include <cstdint> #include <cstdint>
#include <optional>
#include <string> #include <string>
#include <vector> #include <vector>
#include <deque> #include <deque>
#include <memory> #include <memory>
#include <functional> #include <functional>
#include <utility>
namespace ava2 { namespace ava2 {
@@ -37,6 +40,8 @@ public:
bool IsGamePhase() const { return m_phase == PHASE_GAME; } bool IsGamePhase() const { return m_phase == PHASE_GAME; }
void StartGame(); void StartGame();
void ResetConnection(); void ResetConnection();
void SetGuildID(uint32_t id);
uint32_t GetGuildID() const {return m_guildID;}
void SetClientFilename(std::string name) { m_clientFilename=std::move(name); } void SetClientFilename(std::string name) { m_clientFilename=std::move(name); }
// ── Main Actor Attributes ── // ── Main Actor Attributes ──
@@ -53,11 +58,21 @@ public:
void PushRecvData(const uint8_t* data, size_t len); void PushRecvData(const uint8_t* data, size_t len);
void PushRecvData(const std::vector<uint8_t>& bytes); void PushRecvData(const std::vector<uint8_t>& bytes);
bool ProcessRecvData(); 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 ── // ── Client-to-Server Sending API ──
bool SendEnterGamePacket(); 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 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 SendOfflineShopPacket(bool buy,uint32_t owner=0,uint8_t position=0);
bool SendBuildOfflineShopPacket(const std::string& name,const std::vector<TOfflineShopItemTable>& 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 SendOfflineShopManagement(uint8_t operation,uint8_t position=0,uint32_t owner=0);
bool SendQuickSlotAddPacket(uint8_t index,uint8_t type,uint8_t pos); bool SendQuickSlotAddPacket(uint8_t index,uint8_t type,uint8_t pos);
bool SendQuickSlotDelPacket(uint8_t index); bool SendQuickSlotDelPacket(uint8_t index);
@@ -86,7 +101,7 @@ public:
// ── SafeBox & Mall Protocol ── // ── SafeBox & Mall Protocol ──
bool SendSafeBoxCheckinPacket(uint8_t window, uint16_t cell, uint8_t safeboxPos); bool SendSafeBoxCheckinPacket(uint8_t window, uint16_t cell, uint8_t safeboxPos);
bool SendSafeBoxCheckoutPacket(uint8_t safeboxPos, uint8_t window, uint16_t cell); 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 SendSafeBoxMoneyPacket(uint8_t state, uint32_t money);
bool SendMallCheckoutPacket(uint8_t safeboxPos, uint8_t window, uint16_t cell); 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 SendGiveItemPacket(uint32_t targetVID, uint8_t window, uint16_t cell, uint32_t count);
bool SendScriptAnswerPacket(int answer); bool SendScriptAnswerPacket(int answer);
bool SendScriptButtonPacket(int button); 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 // Raw outgoing bytes for network transport / unit test inspection
const std::vector<uint8_t>& GetSendQueue() const { return m_sendBuffer; } const std::vector<uint8_t>& GetSendQueue() const { return m_sendBuffer; }
std::vector<uint8_t> PopSendBytes(); std::vector<uint8_t> PopSendBytes();
void ClearSendQueue() { m_sendBuffer.clear();m_sendPackets.clear(); } void ClearSendQueue() { m_sendBuffer.clear();m_sendPackets.clear(); }
std::vector<std::vector<uint8_t>> PopSendPackets(); std::vector<std::vector<uint8_t>> PopSendPackets();
// Packets with whether the transport appends the sequence byte (SendSequence()).
std::vector<std::pair<std::vector<uint8_t>,bool>> PopSendPacketsWithSequence();
std::pair<int32_t,int32_t> GetDungeonDestination() const { return m_dungeonDestination; }
// Callback when damage occurs // Callback when damage occurs
using DamageCallback = std::function<void(uint32_t vid, int damage, uint8_t flag)>; using DamageCallback = std::function<void(uint32_t vid, int damage, uint8_t flag)>;
void SetDamageCallback(DamageCallback cb) { m_damageCallback = cb; } void SetDamageCallback(DamageCallback cb) { m_damageCallback = cb; }
// Callback when chat is received // Callback when chat is received
using ChatCallback = std::function<void(uint8_t type, const std::string& text, uint32_t vid)>;
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<uint8_t>& GetUnportedPackets() const { return m_unportedPackets; }
// Callback when whisper is received // Callback when whisper is received
using WhisperCallback = std::function<void(uint8_t type, const std::string& from, const std::string& text)>; using WhisperCallback = std::function<void(uint8_t type, const std::string& from, const std::string& text)>;
@@ -124,7 +196,9 @@ public:
void SetFlyCallback(FlyCallback cb) { m_flyCallback = cb; } void SetFlyCallback(FlyCallback cb) { m_flyCallback = cb; }
private: 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 // Handlers matching CPythonNetworkStreamPhaseGame
bool RecvPhasePacket(); bool RecvPhasePacket();
@@ -157,7 +231,15 @@ private:
bool m_startGameRequested=false; bool m_startGameRequested=false;
std::string m_clientFilename="ava2_client"; std::string m_clientFilename="ava2_client";
std::vector<std::vector<uint8_t>> m_sendPackets; std::vector<std::vector<uint8_t>> 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<bool> 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<int32_t,int32_t> m_dungeonDestination{};
bool RecvItemSetPacket(); bool RecvItemSetPacket();
bool RecvItemSetPacket2(); bool RecvItemSetPacket2();
bool RecvItemUpdatePacket(); bool RecvItemUpdatePacket();
@@ -172,6 +254,7 @@ private:
bool RecvWarpPacket(); bool RecvWarpPacket();
bool RecvExchangePacket(); bool RecvExchangePacket();
bool RecvShopPacket(); bool RecvShopPacket();
bool RecvOfflineShopPacket();
bool RecvSafeBoxSetPacket(); bool RecvSafeBoxSetPacket();
bool RecvSafeBoxDelPacket(); bool RecvSafeBoxDelPacket();
bool RecvSafeBoxWrongPasswordPacket(); bool RecvSafeBoxWrongPasswordPacket();
@@ -181,31 +264,123 @@ private:
bool RecvMallSetPacket(); bool RecvMallSetPacket();
bool RecvMallDelPacket(); 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<class Packet> 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 Peek(size_t size, void* outBuf);
bool Read(size_t size, void* outBuf); bool Read(size_t size, void* outBuf);
void Send(const void* data, size_t size); void Send(const void* data, size_t size);
// Windows Send() without SendSequence() (XTrap ACK).
void SendUnsequenced(const void* data, size_t size);
private: private:
EPhase m_phase = PHASE_OFFLINE; EPhase m_phase = PHASE_OFFLINE;
PyObject* m_poHandler = nullptr; PyObject* m_poHandler = nullptr;
PyObject* m_phaseWindows[7] = {nullptr}; PyObject* m_phaseWindows[7] = {nullptr};
uint32_t m_guildID=0;
uint32_t m_dwMainActorVID = 0; uint32_t m_dwMainActorVID = 0;
uint16_t m_wMainActorRace = 0; uint16_t m_wMainActorRace = 0;
uint8_t m_byMainActorEmpire = 0; uint8_t m_byMainActorEmpire = 0;
std::optional<std::chrono::steady_clock::time_point> m_lastGuildCommentRefresh;
uint8_t m_byMainActorSkillGroup = 0; uint8_t m_byMainActorSkillGroup = 0;
std::string m_strMainActorName; std::string m_strMainActorName;
std::string m_strFieldMusicFileName; std::string m_strFieldMusicFileName;
float m_fFieldMusicVolume = 0.02f; float m_fFieldMusicVolume = 0.02f;
std::vector<uint8_t> m_recvBuffer; std::vector<uint8_t> m_recvBuffer;
uint8_t m_lastPacket[2] {};
bool m_dispatchUnported = false;
bool m_unknownPacketQuit = false;
std::vector<uint8_t> m_unportedPackets;
PyObject* m_poSerCommandParserWnd = nullptr;
std::vector<std::string> m_emoticonStrings;
std::string m_strLastCommand;
bool m_isEnableChatInsultFilter = false;
std::vector<std::string> 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<uint8_t> m_sendBuffer; std::vector<uint8_t> m_sendBuffer;
// Temporary pending actor data when CharacterAdd arrives before CharacterAdditionalInfo // Temporary pending actor data when CharacterAdd arrives before CharacterAdditionalInfo
SNetworkActorData m_pendingActorData; SNetworkActorData m_pendingActorData;
DamageCallback m_damageCallback; DamageCallback m_damageCallback;
ChatCallback m_chatCallback;
WhisperCallback m_whisperCallback; WhisperCallback m_whisperCallback;
GroundItemCallback m_groundItemCallback; GroundItemCallback m_groundItemCallback;
FlyCallback m_flyCallback; FlyCallback m_flyCallback;
+287
View File
@@ -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 <cstdlib>
#include <cstring>
#include <iostream>
#include <strings.h>
namespace ava2 {
namespace {
using CTokenVector = std::vector<std::string>;
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<std::string>& 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
File diff suppressed because it is too large Load Diff
+219 -3
View File
@@ -1,6 +1,8 @@
#include "ActorInstance.h" #include "ActorInstance.h"
#include "MapObjectManager.h" #include "MapObjectManager.h"
#include "CRenderTarget.h" #include "CRenderTarget.h"
#include "RaceData.h"
#include "src/eter_resource/ResourceManager.h"
#include <filesystem> #include <filesystem>
#include <cmath> #include <cmath>
#include <algorithm> #include <algorithm>
@@ -21,9 +23,186 @@ std::string ActorInstance::ResolvePath(const std::string& path) const {
if (std::filesystem::exists(clean)) return clean; if (std::filesystem::exists(clean)) return clean;
if (std::filesystem::exists("build/dev/" + clean)) return "build/dev/" + clean; if (std::filesystem::exists("build/dev/" + clean)) return "build/dev/" + clean;
if (std::filesystem::exists("../" + clean)) return "../" + 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; return clean;
} }
std::shared_ptr<Gr2ModelInstance> 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>(Gr2ModelInstance::Load(resolved));
}
void ActorInstance::SetMainModel(std::shared_ptr<Gr2ModelInstance> 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<MotionType>(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) { bool ActorInstance::SetModel(const std::string& modelPath) {
std::string resolved = ResolvePath(modelPath); std::string resolved = ResolvePath(modelPath);
if (!std::filesystem::exists(resolved)) { if (!std::filesystem::exists(resolved)) {
@@ -101,12 +280,44 @@ bool ActorInstance::PlayMotion(MotionType type, bool loop) {
return true; 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<MotionType>(index), gr2);
return PlayMotion(static_cast<MotionType>(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 { bool ActorInstance::IsMotionFinished() const {
if (m_loopMotion) return false; if (m_loopMotion) return false;
return m_animTime >= m_motionDuration; 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; if (dt <= 0.0f) return;
float rad = moveYaw * DEG_TO_RAD; float rad = moveYaw * DEG_TO_RAD;
m_yaw = moveYaw; 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; if (dt <= 0.0f) return;
// 0. Click-to-Move destination pathing (aligned with 40250 CPythonPlayer) // 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 // Advance animation time
m_animTime += dt; 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) { if (m_motionDuration > 0.001f && m_animTime >= m_motionDuration) {
m_animTime = std::fmod(m_animTime, m_motionDuration); m_animTime = std::fmod(m_animTime, m_motionDuration);
} }
+69 -2
View File
@@ -2,6 +2,7 @@
#include "Gr2ModelRenderer.h" #include "Gr2ModelRenderer.h"
#include "TerrainHeightmap.h" #include "TerrainHeightmap.h"
#include <deque>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <memory> #include <memory>
@@ -9,6 +10,8 @@
namespace ava2 { namespace ava2 {
class RaceData;
// Metin2 standard motion types (aligned with 40250 CRaceMotionData::EName) // Metin2 standard motion types (aligned with 40250 CRaceMotionData::EName)
enum class MotionType { enum class MotionType {
None = 0, None = 0,
@@ -44,6 +47,33 @@ public:
// Attach skinned hair / armor parts // Attach skinned hair / armor parts
bool AttachPart(const std::string& partPath); 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; } void SetScale(float s) { m_scale = s; }
float GetScale() const { return m_scale; } float GetScale() const { return m_scale; }
@@ -59,6 +89,17 @@ public:
float GetAnimTime() const { return m_animTime; } float GetAnimTime() const { return m_animTime; }
bool IsAttacking() const { return m_isAttacking; } 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 // World transform
void SetPosition(float x, float y, float z) { m_posX = x; m_posY = y; m_posZ = z; } 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; } 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; bool HitTestScreen(float clickX, float clickY, const Gr2SceneRenderer& renderer, float tolerancePx = 40.0f) const;
// Smooth movement and continuous animation update // 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 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 (变身系统) // Polymorph System (变身系统)
bool SetPolymorph(uint32_t mobVnum); bool SetPolymorph(uint32_t mobVnum);
@@ -120,6 +161,9 @@ public:
void SetSleep(bool value) { m_sleep=value; } void SetSleep(bool value) { m_sleep=value; }
void SetParalysis(bool value) { m_paralysis=value; } void SetParalysis(bool value) { m_paralysis=value; }
void SetFaint(bool value) { m_faint=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 CanAct() const { return !IsDead() && !m_stunned && !m_paralysis && !m_faint && !m_sleep; }
bool IsDead() const { return m_curHP <= 0; } bool IsDead() const { return m_curHP <= 0; }
@@ -163,6 +207,26 @@ public:
private: private:
std::string ResolvePath(const std::string& path) const; std::string ResolvePath(const std::string& path) const;
std::shared_ptr<Gr2ModelInstance> LoadPartModel(const std::string& path) const;
void SetMainModel(std::shared_ptr<Gr2ModelInstance> 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<Gr2ModelInstance> 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<Gr2ModelInstance> m_model; std::shared_ptr<Gr2ModelInstance> m_model;
std::string m_modelPath; std::string m_modelPath;
@@ -172,6 +236,9 @@ private:
float m_animTime = 0.0f; float m_animTime = 0.0f;
float m_motionDuration = 1.0f; float m_motionDuration = 1.0f;
bool m_loopMotion = true; bool m_loopMotion = true;
int m_motionMode = 1; // CRaceMotionData::MODE_GENERAL
std::deque<std::pair<uint32_t, bool>> m_motionQueue; // m_MotionDeque (index, loop)
bool PlayMotionIndex(uint32_t index, bool loop);
bool m_isAttacking = false; bool m_isAttacking = false;
int m_comboIndex = 0; int m_comboIndex = 0;
std::unordered_map<std::string, float> m_buffs; std::unordered_map<std::string, float> m_buffs;
+5
View File
@@ -170,6 +170,11 @@ bool EnvironmentData::LoadFromString(const std::string& content) {
continue; continue;
} }
if (current_scope.empty() && lower_token == "reserved") {
int v = 0; line_stream >> v; reserve = (v != 0);
continue;
}
// Directional Light scope // Directional Light scope
if (current_scope == "directionallight") { if (current_scope == "directionallight") {
if (lower_token == "direction") { if (lower_token == "direction") {
+1
View File
@@ -71,6 +71,7 @@ struct LensFlareData {
struct EnvironmentData { struct EnvironmentData {
std::string name; std::string name;
bool reserve = false; // MapUtil.cpp Environment_Load "reserved" (bReserve)
DirectionalLight dir_light; DirectionalLight dir_light;
MaterialData material; MaterialData material;
FogData fog; FogData fog;
+97 -27
View File
@@ -148,6 +148,51 @@ void Gr2ModelInstance::AttachPart(std::shared_ptr<Gr2ModelInstance> part) {
if (part) m_attached_parts.push_back(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<Gr2ModelInstance>& 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<unsigned char>(c) < 128) c = static_cast<char>(std::tolower(static_cast<unsigned char>(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<Render3DDraw>& 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() { void Gr2ModelInstance::DetachAll() {
m_attached_models.clear(); m_attached_models.clear();
m_attached_parts.clear(); m_attached_parts.clear();
@@ -306,6 +351,7 @@ std::vector<Render3DDraw> Gr2ModelInstance::BuildDrawCommandsWithPalette(const s
} }
} }
} }
ApplySkins(draws, 0);
return draws; return draws;
} }
@@ -435,6 +481,8 @@ std::vector<Render3DDraw> Gr2ModelInstance::BuildDrawCommands(float animation_ti
} }
} }
ApplySkins(draws, 0);
// 2. Build attached skinning parts (e.g. hair, armor) using current skin matrices // 2. Build attached skinning parts (e.g. hair, armor) using current skin matrices
for (const auto& part : m_attached_parts) { for (const auto& part : m_attached_parts) {
if (!part) continue; if (!part) continue;
@@ -461,6 +509,10 @@ std::vector<Render3DDraw> Gr2ModelInstance::BuildDrawCommands(float animation_ti
const auto& B = world_pose[bone_idx]; const auto& B = world_pose[bone_idx];
float attached_local[16]; float attached_local[16];
MultiplyMat4(am.offset, B.data(), attached_local); 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]; float attached_engine[16];
MultiplyMat4(attached_local, R_GRANNY_TO_ENGINE, attached_engine); MultiplyMat4(attached_local, R_GRANNY_TO_ENGINE, attached_engine);
float final_world[16]; float final_world[16];
@@ -470,7 +522,12 @@ std::vector<Render3DDraw> Gr2ModelInstance::BuildDrawCommands(float animation_ti
std::copy(attached_engine, attached_engine + 16, final_world); 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) { for (auto& ad : attach_draws) {
std::copy(final_world, final_world + 16, ad.world); std::copy(final_world, final_world + 16, ad.world);
draws.push_back(std::move(ad)); draws.push_back(std::move(ad));
@@ -630,6 +687,16 @@ void Gr2SceneRenderer::SetCameraLookAt(float eyeX, float eyeY, float eyeZ,
m_view[15]= 1.0f; 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) { void Gr2SceneRenderer::SetPerspective(float fovYDegrees, float aspect, float zNear, float zFar) {
float fovRad = fovYDegrees * 3.1415926535f / 180.0f; float fovRad = fovYDegrees * 3.1415926535f / 180.0f;
float h = 1.0f / std::tan(fovRad * 0.5f); 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()) { if (i * 3 + 2 < draw.normals.size()) {
xverts[i].nx = draw.normals[i * 3 + 0]; // Lit normals are transformed by the world 3x3 (D3DTS_WORLD) before N.L.
xverts[i].ny = draw.normals[i * 3 + 1]; float on0 = draw.normals[i * 3 + 0], on1 = draw.normals[i * 3 + 1], on2 = draw.normals[i * 3 + 2];
xverts[i].nz = 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 { } else {
xverts[i].nx = 0.0f; xverts[i].ny = 1.0f; xverts[i].nz = 0.0f; 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; 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) { auto make_screen_vertex = [&](TransformedVertex& v) {
if (v.w_clip > 1e-5f) { 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; } if (nlen > 1e-5f) { nx /= nlen; ny /= nlen; nz /= nlen; }
float ndotl = std::max(0.0f, nx * lx + ny * ly + nz * lz); 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 pr = 255.0f, pg = 255.0f, pb = 255.0f;
float frag_alpha = 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 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; float va = (b0 * ((d0 >> 24) & 0xFF) + b1 * ((d1 >> 24) & 0xFF) + b2 * ((d2 >> 24) & 0xFF)) / 255.0f;
if (draw.lighting) { if (draw.lighting) {
pr = std::clamp(pr * vr * 1.4f, 0.0f, 255.0f); // D3D8 fixed-function: Emissive + MatAmb*LightAmb + Diffuse*LightDiff*N.L.
pg = std::clamp(pg * vg * 1.4f, 0.0f, 255.0f); 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);
pb = std::clamp(pb * vb * 1.4f, 0.0f, 255.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 { } else {
pr = std::clamp(pr * vr, 0.0f, 255.0f); pr = std::clamp(pr * vr, 0.0f, 255.0f);
pg = std::clamp(pg * vg, 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); pg = b0 * ((d0 >> 8) & 0xFF) + b1 * ((d1 >> 8) & 0xFF) + b2 * ((d2 >> 8) & 0xFF);
pb = b0 * (d0 & 0xFF) + b1 * (d1 & 0xFF) + b2 * (d2 & 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); frag_alpha = b0 * ((d0 >> 24) & 0xFF) + b1 * ((d1 >> 24) & 0xFF) + b2 * ((d2 >> 24) & 0xFF);
} 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);
if (draw.lighting) { 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);
pr = std::clamp(pr * light_intensity, 0.0f, 255.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);
pg = std::clamp(pg * light_intensity, 0.0f, 255.0f); }
pb = std::clamp(pb * light_intensity, 0.0f, 255.0f);
} }
if (m_fog_enabled && draw.fog) { if (m_fog_enabled && draw.fog) {
@@ -1012,7 +1078,6 @@ void Gr2SceneRenderer::RenderDraw(SDL_Surface* targetSurface, const Render3DDraw
rasterize_triangle(*vin2, vnew2, vnew1); rasterize_triangle(*vin2, vnew2, vnew1);
} }
} }
}
} }
void Gr2SceneRenderer::RenderScene(SDL_Surface* targetSurface, const std::vector<Render3DDraw>& draws) { void Gr2SceneRenderer::RenderScene(SDL_Surface* targetSurface, const std::vector<Render3DDraw>& draws) {
@@ -1199,15 +1264,20 @@ void Gr2SceneRenderer::RenderSceneGPU(SDL_Renderer* renderer, const std::vector<
va *= ((d >> 24) & 0xFF) / 255.0f; 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()) { if (draw.lighting && i * 3 + 2 < draw.normals.size()) {
float nx = draw.normals[i * 3 + 0]; float on[3] = {draw.normals[i * 3 + 0], draw.normals[i * 3 + 1], draw.normals[i * 3 + 2]};
float ny = draw.normals[i * 3 + 1]; float nx = on[0] * draw.world[0] + on[1] * draw.world[4] + on[2] * draw.world[8];
float nz = draw.normals[i * 3 + 2]; 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 ndotl = std::max(0.0f, nx * lx + ny * ly + nz * lz);
float light_intensity = 0.52f + 0.58f * ndotl; 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);
vr = std::clamp(vr * light_intensity, 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);
vg = std::clamp(vg * light_intensity, 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);
vb = std::clamp(vb * light_intensity, 0.0f, 1.0f);
} }
if (m_fog_enabled && draw.fog && clip[3] > 0.0f) { if (m_fog_enabled && draw.fog && clip[3] > 0.0f) {
+21
View File
@@ -4,6 +4,7 @@
#include <gr2/gr2.h> #include <gr2/gr2.h>
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <string> #include <string>
#include <unordered_map>
#include <vector> #include <vector>
#include <memory> #include <memory>
@@ -22,6 +23,16 @@ public:
void AttachModel(const std::string& bone_name, std::shared_ptr<Gr2ModelInstance> attachment, const float* offset_matrix = nullptr); void AttachModel(const std::string& bone_name, std::shared_ptr<Gr2ModelInstance> attachment, const float* offset_matrix = nullptr);
void AttachPart(std::shared_ptr<Gr2ModelInstance> part); void AttachPart(std::shared_ptr<Gr2ModelInstance> part);
void DetachAll(); void DetachAll();
void DetachModel(const std::string& bone_name);
void DetachPart(const std::shared_ptr<Gr2ModelInstance>& 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) // Build 3D draw commands for this model and all attached components (weapons, hair, armor parts)
std::vector<Render3DDraw> BuildDrawCommands(float animation_time = -1.0f, const float* world_matrix = nullptr); std::vector<Render3DDraw> BuildDrawCommands(float animation_time = -1.0f, const float* world_matrix = nullptr);
@@ -41,7 +52,11 @@ private:
std::string bone_name; std::string bone_name;
std::shared_ptr<Gr2ModelInstance> model; std::shared_ptr<Gr2ModelInstance> model;
float offset[16]; float offset[16];
bool animated = false;
bool scaled = false;
float scale[3] = {1.0f, 1.0f, 1.0f};
}; };
void ApplySkins(std::vector<Render3DDraw>& draws, size_t first) const;
std::unique_ptr<gr2::File> m_file; std::unique_ptr<gr2::File> m_file;
std::string m_filepath; std::string m_filepath;
@@ -50,6 +65,7 @@ private:
std::vector<AttachedModel> m_attached_models; std::vector<AttachedModel> m_attached_models;
std::vector<std::shared_ptr<Gr2ModelInstance>> m_attached_parts; std::vector<std::shared_ptr<Gr2ModelInstance>> m_attached_parts;
std::unordered_map<std::string, std::string> m_skins;
}; };
// 3D Scene and Model Renderer (modeled after 40250 pipeline architecture) // 3D Scene and Model Renderer (modeled after 40250 pipeline architecture)
@@ -61,6 +77,11 @@ public:
void SetCameraLookAt(float eyeX, float eyeY, float eyeZ, void SetCameraLookAt(float eyeX, float eyeY, float eyeZ,
float targetX, float targetY, float targetZ, float targetX, float targetY, float targetZ,
float upX, float upY, float upZ); 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); void SetPerspective(float fovYDegrees, float aspect, float zNear, float zFar);
+455
View File
@@ -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 <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
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<unsigned char>(c) < 128) c = static_cast<char>(std::tolower(static_cast<unsigned char>(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<unsigned>(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<unsigned>(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::Motion>* 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<uint32_t>(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<uint32_t>* 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<RaceData>(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<std::string>* paths) {
auto push = [paths](std::initializer_list<const char*> 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<RaceData>(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<std::string> paths;
GetRaceResourcePathes(race, &paths);
auto data = std::make_unique<RaceData>(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<std::string, uint32_t> 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<uint32_t>(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
+135
View File
@@ -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 <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>
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<Skin> 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<uint32_t, std::vector<Motion>> 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<Motion>* GetMotions(uint32_t name) const { return GetMotions(MODE_GENERAL, name); }
const std::vector<Motion>* 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<uint32_t>* 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<uint32_t, Shape> m_shapes, m_hairs;
std::map<uint32_t, std::string> m_attachingBoneNames;
std::map<uint16_t, MotionVectorMap> m_motionModes;
std::map<uint32_t, uint32_t> m_normalAttack;
std::map<uint32_t, std::vector<uint32_t>> 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<std::string>* paths);
static bool LoadRaceMotionList(RaceData& race, const std::string& pathName, const std::string& motionListFileName);
private:
RaceData* LoadRace(uint32_t race);
std::map<uint32_t, std::unique_ptr<RaceData>> m_races;
std::map<uint32_t, std::string> m_raceNames;
std::map<std::string, std::string> m_raceSrcNames;
std::string m_pathName;
RaceData* m_selected = nullptr;
std::map<int, float> 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
+24 -14
View File
@@ -2,6 +2,7 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <fstream> #include <fstream>
#include <sstream>
#include <iostream> #include <iostream>
namespace ava2 { 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; std::cerr << "TerrainHeightmap::LoadTextureSet failed to open: " << textureset_path << std::endl;
return false; 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; std::string line;
int current_id = 0; int current_id = 0;
bool in_texture = false; bool in_texture = false;
@@ -299,10 +306,19 @@ void TerrainHeightmap::GenerateProcedural(int width, int height, float cell_scal
void TerrainHeightmap::UpdateBounds() { void TerrainHeightmap::UpdateBounds() {
float total_w = static_cast<float>(m_width - 1) * m_cell_scale; float total_w = static_cast<float>(m_width - 1) * m_cell_scale;
float total_h = static_cast<float>(m_height - 1) * m_cell_scale; float total_h = static_cast<float>(m_height - 1) * m_cell_scale;
m_world_min_x = -total_w * 0.5f; m_world_min_x = m_has_origin ? m_origin_x : -total_w * 0.5f;
m_world_max_x = total_w * 0.5f; m_world_max_x = m_world_min_x + total_w;
m_world_min_z = -total_h * 0.5f; m_world_min_z = m_has_origin ? m_origin_z : -total_h * 0.5f;
m_world_max_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() { 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(u);
draw.uv0.push_back(v); draw.uv0.push_back(v);
float lx = 0.577f, ly = 0.577f, lz = 0.577f; // CTerrain vertices carry no baked shade; the D3D light on the terrain material does it.
float dot = std::max(0.25f, nx * lx + ny * ly + nz * lz); draw.diffuse.push_back(0xFFFFFFFFu);
uint8_t c = static_cast<uint8_t>(std::clamp(dot * 255.0f, 0.0f, 255.0f));
uint32_t color = (0xFF << 24) | (c << 16) | (c << 8) | c;
draw.diffuse.push_back(color);
} }
} }
@@ -739,11 +752,8 @@ Render3DDraw TerrainHeightmap::BuildDrawCommand(const float world[16], int step)
draw.uv0.push_back(u); draw.uv0.push_back(u);
draw.uv0.push_back(v); draw.uv0.push_back(v);
float lx = 0.577f, ly = 0.577f, lz = 0.577f; // CTerrain vertices carry no baked shade; the D3D light on the terrain material does it.
float dot = std::max(0.25f, nx * lx + ny * ly + nz * lz); draw.diffuse.push_back(0xFFFFFFFFu);
uint8_t c = static_cast<uint8_t>(std::clamp(dot * 255.0f, 0.0f, 255.0f));
uint32_t color = (0xFF << 24) | (c << 16) | (c << 8) | c;
draw.diffuse.push_back(color);
} }
} }
+24 -5
View File
@@ -33,6 +33,16 @@ struct TerrainQuadNode {
std::unique_ptr<TerrainQuadNode> children[4]; std::unique_ptr<TerrainQuadNode> 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: * TerrainHeightmap:
* Parses Metin2 terrain heightmap data (such as height.raw: 131x131 uint16_t), * Parses Metin2 terrain heightmap data (such as height.raw: 131x131 uint16_t),
@@ -41,7 +51,7 @@ struct TerrainQuadNode {
* and textureset configuration (metin2_map1.txt). * and textureset configuration (metin2_map1.txt).
* Implements 8x8 patch subdivision and QuadTree frustum culling. * Implements 8x8 patch subdivision and QuadTree frustum culling.
*/ */
class TerrainHeightmap { class TerrainHeightmap : public TerrainHeightSource {
public: public:
static constexpr int RAW_XSIZE = 131; static constexpr int RAW_XSIZE = 131;
static constexpr int RAW_YSIZE = 131; static constexpr int RAW_YSIZE = 131;
@@ -62,7 +72,7 @@ public:
static constexpr uint8_t ATTR_FLAG_BANPK = ATTR_BANPK; static constexpr uint8_t ATTR_FLAG_BANPK = ATTR_BANPK;
TerrainHeightmap(); TerrainHeightmap();
~TerrainHeightmap() = default; ~TerrainHeightmap() override = default;
// Load from Metin2 height.raw file (131x131 uint16_t, 34322 bytes) // 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); 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) // Load TextureSet file (e.g. textureset/metin2_map1.txt)
bool LoadTextureSet(const std::string& textureset_path); bool LoadTextureSet(const std::string& textureset_path);
bool LoadTextureSetFromString(const std::string& content);
// Procedural terrain generation for testing // Procedural terrain generation for testing
void GenerateProcedural(int width = 64, int height = 64, float cell_scale = 100.0f, float hill_amplitude = 80.0f); 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) // Query height at grid or world coordinates (continuous bilinear interpolation)
float GetHeightAtGrid(int x, int y) const; 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) // Query normal at world space coordinates (normalized, Y-up)
void GetNormalAtWorld(float world_x, float world_z, float out_normal[3]) const; 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; std::string GetTexturePathForTile(uint8_t tile_id) const;
// Query attribute flag (ATTR_BLOCK, ATTR_WATER, ATTR_BANPK) // 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 GetAttrAtGrid(int x, int y) const;
uint8_t GetAttrAtWorld(float world_x, float world_z) 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 // Build single full-mesh 3D draw command
Render3DDraw BuildDrawCommand(const float world[16] = nullptr, int step = 1) const; Render3DDraw BuildDrawCommand(const float world[16] = nullptr, int step = 1) const;
@@ -149,6 +164,10 @@ private:
float m_min_height = 0.0f; float m_min_height = 0.0f;
float m_max_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<float> m_heights; // m_width * m_height floats std::vector<float> m_heights; // m_width * m_height floats
std::vector<float> m_normals; // (m_width * m_height) * 3 floats std::vector<float> m_normals; // (m_width * m_height) * 3 floats
+1
View File
@@ -134,6 +134,7 @@ public:
// Active renderer reference for Python bindings // Active renderer reference for Python bindings
void SetCurrentSceneRenderer(const Gr2SceneRenderer* renderer) { m_currentSceneRenderer = renderer; } void SetCurrentSceneRenderer(const Gr2SceneRenderer* renderer) { m_currentSceneRenderer = renderer; }
const Gr2SceneRenderer* GetCurrentSceneRenderer() const { return m_currentSceneRenderer; }
void SetCurrentRenderer(SDL_Renderer* renderer) { m_currentRenderer = renderer; } void SetCurrentRenderer(SDL_Renderer* renderer) { m_currentRenderer = renderer; }
private: private:
+20 -1
View File
@@ -10,10 +10,12 @@
#include <string> #include <string>
#include <algorithm> #include <algorithm>
#include <vector> #include <vector>
#include <filesystem>
class CResourceManager : public CSingleton<CResourceManager> class CResourceManager : public CSingleton<CResourceManager>
{ {
public: public:
static void SetResourceRoot(const std::filesystem::path& root) { s_resourceRoot=root; }
CResourceManager() = default; CResourceManager() = default;
virtual ~CResourceManager() virtual ~CResourceManager()
{ {
@@ -73,6 +75,12 @@ public:
return pRes; 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) static std::string NormalizePath(const char* c_szPath)
{ {
std::string path = c_szPath ? c_szPath : ""; std::string path = c_szPath ? c_szPath : "";
@@ -108,6 +116,16 @@ public:
candidates.push_back("ymir work/" + path); 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 // Handle legacy CP949/Latin-1 raw bytes in filenames by generating UTF-8 candidates
size_t initial_size = candidates.size(); size_t initial_size = candidates.size();
for (size_t i = 0; i < initial_size; ++i) for (size_t i = 0; i < initial_size; ++i)
@@ -151,7 +169,7 @@ private:
for (const auto& c : candidates) for (const auto& c : candidates)
{ {
auto* img = new CGraphicImage(path); auto* img = new CGraphicImage(path);
if (img->LoadFile(c.c_str())) if (img->LoadFile(c.c_str(),path))
{ {
return img; return img;
} }
@@ -230,5 +248,6 @@ private:
return subImg; return subImg;
} }
inline static std::filesystem::path s_resourceRoot;
std::unordered_map<std::string, CResource*> m_resourceMap; std::unordered_map<std::string, CResource*> m_resourceMap;
}; };
+44 -2
View File
@@ -481,8 +481,50 @@ namespace UI
return ret ? TRUE : FALSE; return ret ? TRUE : FALSE;
} }
BOOL CWindow::OnMouseMiddleButtonDown() { return FALSE; } // EterPythonLib/PythonWindow.cpp CWindow::OnMouseMiddleButtonDown/Up, RunMouseWheelEvent,
BOOL CWindow::OnMouseMiddleButtonUp() { return FALSE; } // 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) BOOL CWindow::OnKeyDown(int ikey)
{ {
+17 -3
View File
@@ -32,7 +32,19 @@ namespace UI
void SetText(const char* text) { if (text) m_text = text; } void SetText(const char* text) { if (text) m_text = text; }
const char* GetText() const { return m_text.c_str(); } const char* GetText() const { return m_text.c_str(); }
void SetValue(const char* text) { SetText(text); } void SetValue(const char* text) { SetText(text); }
void SetValueString(const std::string& text) { m_text = text; }
void SetHorizonalAlign(int align) { m_hAlign = align; } 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 SetVerticalAlign(int align) { m_vAlign = align; }
void SetMax(int max) { m_max = max; } void SetMax(int max) { m_max = max; }
void SetFontName(const char* name) { if (name) m_font = name; } void SetFontName(const char* name) { if (name) m_font = name; }
@@ -57,6 +69,8 @@ namespace UI
D3DXVECTOR2 GetPosition() const { return m_v2Position; } D3DXVECTOR2 GetPosition() const { return m_v2Position; }
void Update() {} void Update() {}
void Render(); 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 ""; } static const char* Hyperlink_GetText(const std::string&, int, int*) { return ""; }
private: private:
D3DXVECTOR2 m_v2Position = D3DXVECTOR2(0.0f, 0.0f); D3DXVECTOR2 m_v2Position = D3DXVECTOR2(0.0f, 0.0f);
@@ -213,10 +227,10 @@ namespace UI
virtual BOOL OnMouseRightButtonDoubleClick(); virtual BOOL OnMouseRightButtonDoubleClick();
virtual BOOL OnMouseMiddleButtonDown(); virtual BOOL OnMouseMiddleButtonDown();
virtual BOOL OnMouseMiddleButtonUp(); virtual BOOL OnMouseMiddleButtonUp();
virtual BOOL OnMouseWheelScroll(short wDelta) { return FALSE; } virtual BOOL OnMouseWheelScroll(short wDelta);
virtual void SetScrollable() { m_bIsScrollable = true; } virtual void SetScrollable() { m_bIsScrollable = true; }
virtual BOOL OnMouseWheel(int nLen) { return FALSE; } virtual BOOL OnMouseWheel(int nLen);
virtual BOOL RunMouseWheelEvent(long nLen) { return FALSE; } virtual BOOL RunMouseWheelEvent(long nLen);
virtual BOOL OnKeyDown(int ikey); virtual BOOL OnKeyDown(int ikey);
virtual BOOL OnKeyUp(int ikey); virtual BOOL OnKeyUp(int ikey);
+60 -2
View File
@@ -412,16 +412,74 @@ namespace UI
if (m_pPointWindow) m_pPointWindow->OnMouseRightButtonDoubleClick(); 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) void CWindowManager::RunMouseMiddleButtonDown(long x, long y)
{ {
SetMousePosition(x, 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) void CWindowManager::RunMouseMiddleButtonUp(long x, long y)
{ {
SetMousePosition(x, 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) void CWindowManager::RunKeyDown(int vkey)
+2
View File
@@ -116,6 +116,8 @@ namespace UI
void RunMouseRightButtonDoubleClick(long x, long y); void RunMouseRightButtonDoubleClick(long x, long y);
void RunMouseMiddleButtonDown(long x, long y); void RunMouseMiddleButtonDown(long x, long y);
void RunMouseMiddleButtonUp(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 RunKeyDown(int vkey);
void RunKeyUp(int vkey); void RunKeyUp(int vkey);
+74
View File
@@ -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
+15
View File
@@ -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 <cstdint>
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
+32
View File
@@ -0,0 +1,32 @@
#pragma once
// State semantics ported from AVA2 UserInterface/PythonGuild.cpp.
#include <array>
#include <cstdint>
#include <map>
#include <string>
#include <vector>
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<uint8_t,12> levels{};uint16_t power=0,maxPower=0; } skill;
bool enabled=false;
uint32_t levelSum=0,levelAverage=0,offerSum=0;
std::vector<Member> members;
std::vector<Comment> comments;
std::map<uint32_t,Grade> grades;
std::map<uint32_t,std::string> names;
std::map<uint32_t,uint32_t> skillSlots;
std::array<uint32_t,6> 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();
}
+5 -3
View File
@@ -20,6 +20,7 @@ class ItemProto {
public: public:
std::map<uint32_t,ItemProtoRecord> records; std::map<uint32_t,ItemProtoRecord> records;
std::vector<uint32_t> ranges; std::vector<uint32_t> ranges;
std::vector<ItemProtoRecord> recentRecords;
const ItemProtoRecord* find(uint32_t id) const { const ItemProtoRecord* find(uint32_t id) const {
auto exact=records.find(id);if(exact!=records.end())return &exact->second; 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; 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; 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. // AVA2's active ENABLE_PROTOSTRUCT_AUTODETECT leaves dwStride0 for MIPT.
// TItemTableAll::Process has no case0, so every destination stays zeroed. // TItemTableAll::Process has no case0, so every destination stays zeroed.
if(legacy){records[0]=ItemProtoRecord{};return true;} if(legacy){records[0]=ItemProtoRecord{};recentRecords.assign(count,ItemProtoRecord{});return true;}
std::map<uint32_t,ItemProtoRecord> loaded;std::vector<uint32_t> loadedRanges; std::map<uint32_t,ItemProtoRecord> loaded;std::vector<uint32_t> loadedRanges;std::vector<ItemProtoRecord> ordered;
for(uint32_t i=0;i<count;++i){auto r=std::span<const uint8_t>(raw).subspan(size_t(i)*stride,stride);size_t shift=stride==172?0:4;ItemProtoRecord item; for(uint32_t i=0;i<count;++i){auto r=std::span<const uint8_t>(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); item.vnum=wire::read32(r,0);if(shift)item.range=wire::read32(r,4);
const char* name=reinterpret_cast<const char*>(r.data()+29+shift);item.name.assign(name,strnlen(name,25)); const char* name=reinterpret_cast<const char*>(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.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]; item.alterToMagicPercent=r[169+shift];item.specular=r[170+shift];item.gainSocketPercent=r[171+shift];
if(item.range)loadedRanges.push_back(item.vnum); 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); for(auto& [id,item]:loaded)records[id]=std::move(item);
ranges.insert(ranges.end(),loadedRanges.begin(),loadedRanges.end()); ranges.insert(ranges.end(),loadedRanges.begin(),loadedRanges.end());
return true; return true;
+36
View File
@@ -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 <array>
namespace ava2 {
namespace {
std::array<std::string,USESOUND_NUM> useSounds;
std::array<std::string,DROPSOUND_NUM> 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<useSounds.size())useSounds[type]=filename;}
void SetItemDropSound(uint32_t type,const std::string& filename) {if(type<dropSounds.size())dropSounds[type]=filename;}
std::optional<std::string> 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<std::string> 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());}
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <cstdint>
#include <optional>
#include <string>
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<std::string> GetItemUseSound(uint32_t vnum);
std::optional<std::string> GetItemDropSound(uint32_t vnum);
const std::string& GetPotionSound();
void PlayItemUseSound(uint32_t vnum);
void PlayItemDropSound(uint32_t vnum);
void PlayUsePotionSound();
}
+7 -4
View File
@@ -5,6 +5,7 @@
#include <poll.h> #include <poll.h>
#include <fcntl.h> #include <fcntl.h>
#include <unistd.h> #include <unistd.h>
#include <algorithm>
#include <atomic> #include <atomic>
#include <cerrno> #include <cerrno>
#include <cstring> #include <cstring>
@@ -111,7 +112,9 @@ void LoginClient::pump() {
} }
flush();if(status_==Status::Failed) return; flush();if(status_==Status::Failed) return;
for(int iteration=0;iteration<16;++iteration) { 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<std::size_t>(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==EINTR) continue;
if(n<0 && (errno==EAGAIN || errno==EWOULDBLOCK)) break; if(n<0 && (errno==EAGAIN || errno==EWOULDBLOCK)) break;
if(n<=0) { fail("server disconnected");return; } if(n<=0) { fail("server disconnected");return; }
@@ -131,10 +134,10 @@ void LoginClient::pump() {
flush();if(status_==Status::Failed) return; flush();if(status_==Status::Failed) return;
} }
} }
wire::Bytes LoginClient::take_game_input() { return session_?session_->take_game_input():wire::Bytes{}; } 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) { void LoginClient::send_game_packet(wire::Bytes packet,bool sequence) {
if(status_!=Status::Loading || !session_) throw std::logic_error("game transport is not ready"); 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) { void LoginClient::direct_enter(std::uint8_t slot) {
if(!session_ || status_!=Status::Selecting || slot>=session_->characters().size() || !session_->characters()[slot].id) if(!session_ || status_!=Status::Selecting || slot>=session_->characters().size() || !session_->characters()[slot].id)
+3 -2
View File
@@ -18,10 +18,11 @@ public:
void connect(Endpoint auth,Endpoint game,std::string account,std::string password); void connect(Endpoint auth,Endpoint game,std::string account,std::string password);
void cancel(); void cancel();
void pump(); // no blocking socket operation or DNS lookup on the caller thread 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 select(std::uint8_t slot);
void direct_enter(std::uint8_t slot); void direct_enter(std::uint8_t slot);
wire::Bytes take_game_input(); wire::Bytes take_game_input(std::size_t max=LoginSession::kRecvBufferSize);
void send_game_packet(wire::Bytes packet); void send_game_packet(wire::Bytes packet,bool sequence=true);
std::vector<Event> take_events(); std::vector<Event> take_events();
Status status() const { return status_; } Status status() const { return status_; }
const LoginSession* session() const { return session_.get(); } const LoginSession* session() const { return session_.get(); }
+7 -6
View File
@@ -39,7 +39,7 @@ void LoginSession::emit(Bytes bytes,bool sequence) {
std::vector<Bytes> LoginSession::take_output() { auto out=std::move(output_); output_.clear(); return out; } std::vector<Bytes> LoginSession::take_output() { auto out=std::move(output_); output_.clear(); return out; }
void LoginSession::feed(std::span<const std::uint8_t> input) { void LoginSession::feed(std::span<const std::uint8_t> input) {
if(state_==State::Failed) return; 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()); raw_.insert(raw_.end(),input.begin(),input.end());
while(!raw_.empty() && state_!=State::Failed) { while(!raw_.empty() && state_!=State::Failed) {
std::size_t n=encrypted_?8:1; std::size_t n=encrypted_?8:1;
@@ -120,14 +120,15 @@ bool LoginSession::process_packet() {
} }
return true; return true;
} }
wire::Bytes LoginSession::take_game_input() { wire::Bytes LoginSession::take_game_input(std::size_t max) {
if(state_!=State::Loading) return {}; if(state_!=State::Loading || max==0) return {};
auto bytes=std::move(plain_);plain_.clear();return bytes; 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(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"); 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) { void LoginSession::select(std::uint8_t slot) {
if(state_!=State::Selecting) throw std::logic_error("selection requires character roster and select phase"); if(state_!=State::Selecting) throw std::logic_error("selection requires character roster and select phase");
+8 -2
View File
@@ -20,9 +20,15 @@ public:
void reconnect_game(); void reconnect_game();
void feed(std::span<const std::uint8_t> input); void feed(std::span<const std::uint8_t> input);
std::vector<wire::Bytes> take_output(); std::vector<wire::Bytes> 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); void select(std::uint8_t slot);
wire::Bytes take_game_input(); // Windows networkmodule.py: net.SetTCPRecvBufferSize(128*1024). A full buffer pauses recv() (restSize<=0).
void send_game_packet(wire::Bytes packet); 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_; } State state() const { return state_; }
const std::string& failure() const { return failure_; } const std::string& failure() const { return failure_; }
const std::vector<wire::Bytes>& pack_metadata() const { return pack_metadata_; } const std::vector<wire::Bytes>& pack_metadata() const { return pack_metadata_; }
+37 -4
View File
@@ -23,6 +23,11 @@
#ifdef AVA2_HAS_PYTHON #ifdef AVA2_HAS_PYTHON
#include "python_runtime.h" #include "python_runtime.h"
#include "python_net.h" #include "python_net.h"
#include "python_event_manager.h"
#include "python_system.h"
#include "eter_base/Random.h"
#include <ctime>
#include <random>
#include "python_gameplay_modules.h" #include "python_gameplay_modules.h"
#include "eter_image/GrpDevice.h" #include "eter_image/GrpDevice.h"
#include "eter_ui/PythonWindowManager.h" #include "eter_ui/PythonWindowManager.h"
@@ -156,6 +161,12 @@ int main(int argc, char** argv) {
#endif #endif
#ifdef AVA2_HAS_PYTHON #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<ava2::PythonRuntime> python; std::unique_ptr<ava2::PythonRuntime> python;
if (!stdlib.empty() || !script_root.empty()) { if (!stdlib.empty() || !script_root.empty()) {
python = std::make_unique<ava2::PythonRuntime>(stdlib, script_root); python = std::make_unique<ava2::PythonRuntime>(stdlib, script_root);
@@ -182,6 +193,10 @@ int main(int argc, char** argv) {
#endif #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()); if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) throw std::runtime_error(SDL_GetError());
struct Quit { ~Quit(){ SDL_Quit(); } } quit; struct Quit { ~Quit(){ SDL_Quit(); } } quit;
@@ -191,8 +206,16 @@ int main(int argc, char** argv) {
); );
if (!gpu) throw std::runtime_error(SDL_GetError()); 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<SDL_Window, decltype(&SDL_DestroyWindow)> window( std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> 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 SDL_DestroyWindow
); );
if (!window) throw std::runtime_error(SDL_GetError()); 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()); 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_SetRenderVSync(renderer.get(), 1);
SDL_StartTextInput(window.get()); SDL_StartTextInput(window.get());
float dpi_scale = SDL_GetWindowPixelDensity(window.get()); float dpi_scale = SDL_GetWindowPixelDensity(window.get());
@@ -219,9 +242,10 @@ int main(int argc, char** argv) {
graphicDevice.Init(renderer.get()); graphicDevice.Init(renderer.get());
UI::CWindowManager* wm = python ? python->window_manager() : nullptr; UI::CWindowManager* wm = python ? python->window_manager() : nullptr;
if (wm) { if (wm) {
wm->SetScreenSize(1280, 720); wm->SetScreenSize(screen_width, screen_height);
wm->SetResolution(1280, 720); wm->SetResolution(screen_width, screen_height);
} }
if (python) ava2::CPythonSystem::Instance().GetDisplaySettings();
// Preview data must be explicitly requested; never shadow authenticated roster. // Preview data must be explicitly requested; never shadow authenticated roster.
if (preview_data) { if (preview_data) {
@@ -949,6 +973,8 @@ int main(int argc, char** argv) {
ava2::LoginViewSnapshot snapshot; ava2::LoginViewSnapshot snapshot;
if (python && !view_script.empty()) { if (python && !view_script.empty()) {
python->pump_network(); python->pump_network();
// CheckPacket unknown header / "quit" server command: Windows PostQuitMessage(0)
if (ava2::PythonNetworkStream::Instance().IsQuitRequested()) running = false;
snapshot = python->view_snapshot(); snapshot = python->view_snapshot();
} }
#endif #endif
@@ -1711,6 +1737,8 @@ int main(int argc, char** argv) {
#ifdef AVA2_HAS_PYTHON #ifdef AVA2_HAS_PYTHON
graphicDevice.BeginScene(false); graphicDevice.BeginScene(false);
if (wm) { 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->Update();
wm->Render(); wm->Render();
} }
@@ -1813,6 +1841,11 @@ int main(int argc, char** argv) {
#ifdef AVA2_HAS_PYTHON #ifdef AVA2_HAS_PYTHON
graphicDevice.Init(nullptr); graphicDevice.Init(nullptr);
// CPythonApplication::Destroy: SaveConfig, then SaveInterfaceStatus while Python is alive.
if (python) {
ava2::CPythonSystem::Instance().SaveConfig();
ava2::CPythonSystem::Instance().SaveInterfaceStatus();
}
#endif #endif
ava2::SoundManager::Instance().Destroy(); ava2::SoundManager::Instance().Destroy();
SDL_StopTextInput(window.get()); SDL_StopTextInput(window.get());
+31
View File
@@ -0,0 +1,31 @@
#pragma once
// AVA2 UserInterface/PythonMessenger.cpp/.h, including observable callback order.
#include <Python.h>
#include <cstdint>
#include <map>
#include <set>
#include <string>
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<std::string> friends;
std::map<std::string,uint8_t> guild;
PyObject* handler=nullptr;
};
MessengerState& GetMessengerState();
}
+38
View File
@@ -1,10 +1,45 @@
#include "nonplayer_data.h" #include "nonplayer_data.h"
#include "python_wiki.h"
#include "legacy_cipher.h" #include "legacy_cipher.h"
#include "../third_party/ava2-lzo/lzo1x.h" #include "../third_party/ava2-lzo/lzo1x.h"
#include <cstring> #include <cstring>
#include <cstdlib>
#include <iostream>
#include "ava2_text_file.h"
namespace ava2 { namespace ava2 {
NonPlayerData& NonPlayerData::Instance() { static NonPlayerData data; return data; } 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; } 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;i<lines.size();++i) {
auto tokens=ava2TabTokens(lines[i],true);if(tokens.empty())continue; // SplitLineByTab
if(tokens.size()<4) { std::cerr<<"[AVA2 TraceError] LoadMobScale: invalid line "<<i<<" ("<<fileName<<")."<<std::endl; continue; }
const uint32_t vnum=uint32_t(std::atoi(tokens[0].c_str()));
mobScales.insert({vnum,MobScale{float(std::atof(tokens[1].c_str())),float(std::atof(tokens[2].c_str())),float(std::atof(tokens[3].c_str()))}});
}
return true;
}
const NonPlayerData::MobScale* NonPlayerData::getMobScale(uint32_t vnum) const { auto it=mobScales.find(vnum);return it==mobScales.end()?nullptr:&it->second; }
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<int> wear(NPC_WEAR_MAX);
for(size_t i=0;i<NPC_WEAR_MAX;++i) wear[i]=std::atoi(tokens[i+2].c_str());
if(wear[NPC_WEAR_RACE]>7) 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) { bool UseNonPlayerName(uint32_t race) {
if(race>=30000 && race<=30020) return false; 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}; 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; 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)); 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. for(auto& m:loaded) records.emplace(m.vnum,std::move(m)); // Original insert preserves first record.
return true; return true;
} catch(const std::exception&) { return false; } } catch(const std::exception&) { return false; }
+13
View File
@@ -19,8 +19,21 @@ public:
const MobRecord* get(uint32_t vnum) const; const MobRecord* get(uint32_t vnum) const;
void clear() { records.clear(); } void clear() { records.clear(); }
const std::map<uint32_t,MobRecord>& all() const { return records; } const std::map<uint32_t,MobRecord>& 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: private:
std::map<uint32_t,MobRecord> records; std::map<uint32_t,MobRecord> records;
std::map<uint32_t,MobScale> mobScales;
std::map<std::string,std::map<uint32_t,std::vector<int>>> npcWear;
}; };
bool UseNonPlayerName(uint32_t race); bool UseNonPlayerName(uint32_t race);
bool GetNonPlayerName(uint32_t race,std::string& name); bool GetNonPlayerName(uint32_t race,std::string& name);
+30
View File
@@ -0,0 +1,30 @@
#pragma once
// AVA2 UserInterface/PythonShop.cpp, active ENABLE_OFFLINESHOP_SYSTEM profile.
#include "eter_net/Packet.h"
#include <array>
#include <map>
#include <string>
namespace ava2 {
struct OfflineShopState {
std::array<TOfflineShopItemData,240> items{};
std::map<std::pair<uint8_t,uint16_t>,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();
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
// AVA2 UserInterface/PythonSkillPet.cpp/h, NEW_PET_SYSTEM feature profile.
#include <array>
#include <cstdint>
#include <map>
#include <string>
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<int32_t,3> slots{};
std::map<uint32_t,PetSkillRecord> records;
void Clear() {records.clear();} // Original Destroy retains all three slot assignments.
};
PetSkillState& GetPetSkillState();
bool LoadPetSkills(const std::string& path);
}
+297
View File
@@ -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
+5
View File
@@ -0,0 +1,5 @@
#pragma once
namespace ava2 {
// CPythonPlayerSettingsModule effect / emoticon / item-sound registration (AVA2 app.Create).
void LoadPlayerSettings();
}
+172 -11
View File
@@ -1,11 +1,28 @@
#include "player_settings.h"
#include "python_app.h" #include "python_app.h"
#include "server_clock.h" #include "server_clock.h"
#include "generated_app_constants.h" #include "generated_app_constants.h"
#include "../upstream/ava2-client/UserInterface/Locale_inc.h" #include "../upstream/ava2-client/UserInterface/Locale_inc.h"
#include "src/eter_image/MarkManager.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 <iostream>
#include <Python.h> #include <Python.h>
#include <chrono> #include <chrono>
#include <utility>
#include <string> #include <string>
#include <unordered_map>
#include <vector>
namespace ava2 { namespace ava2 {
namespace { namespace {
@@ -13,6 +30,8 @@ namespace {
std::uint32_t local_milliseconds() { return static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()); } std::uint32_t local_milliseconds() { return static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()); }
std::int64_t unix_seconds() { return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); } std::int64_t unix_seconds() { return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); }
ServerClock server_clock(local_milliseconds()); 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(); auto app_start=std::chrono::steady_clock::now();
float s_camera_distance = 1500.0f; float s_camera_distance = 1500.0f;
float s_camera_pitch = 30.0f; float s_camera_pitch = 30.0f;
@@ -49,12 +68,26 @@ PyObject* app_set_camera(PyObject*, PyObject* args) {
Py_RETURN_NONE; 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_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); 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_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_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_loop(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* app_exit(PyObject*, PyObject*) { Py_RETURN_NONE; } PyObject* app_exit(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* app_abort(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()); 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*) { PyObject* app_get_default_codepage(PyObject*, PyObject*) {
return PyInt_FromLong(1252); return PyInt_FromLong(GetDefaultCodePage());
} }
PyObject* app_dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; } 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_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); }
PyObject* app_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); } PyObject* app_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); }
PyObject* app_dummy_float_zero(PyObject*, PyObject*) { return PyFloat_FromDouble(0.0); } 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_tuple2(PyObject*, PyObject*) { return Py_BuildValue("ii", 0, 0); }
PyObject* app_dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 0, 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<int, std::vector<std::string>> 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<std::string> 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) { PyObject* app_set_guild_mark_path(PyObject*, PyObject* args) {
const char* path = nullptr; const char* path = nullptr;
if (PyArg_ParseTuple(args, "s", &path) && path) { 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()); } 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 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::int32_t>(std::chrono::duration_cast<std::chrono::seconds>(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() { std::uint8_t GetEnterGameLanguage() {
const char* locales[]={"ymir","en","de","tr","pt","es","fr","ro","pl","it","cz","hu"}; 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; for(std::uint8_t i=1;i<12;++i) if(s_locale_name==locales[i]) return i;
return 1; 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;} int GetTwoHandedAttackSpeedDecrease(){return twoHandedAttackSpeedDecrease;}
bool IsYmirLocale() { return s_locale_name=="ymir"; } bool IsYmirLocale() { return s_locale_name=="ymir"; }
@@ -163,7 +260,7 @@ void initapp() {
{"SetGlobalCenterPosition", app_dummy_none, METH_VARARGS, nullptr}, {"SetGlobalCenterPosition", app_dummy_none, METH_VARARGS, nullptr},
{"SetCenterPosition", app_dummy_none, METH_VARARGS, nullptr}, {"SetCenterPosition", app_dummy_none, METH_VARARGS, nullptr},
{"GetCursorPosition", app_dummy_tuple2, 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}, {"RunPythonFile", app_dummy_none, METH_VARARGS, nullptr},
{"IsWebPageMode", app_dummy_zero, METH_VARARGS, nullptr}, {"IsWebPageMode", app_dummy_zero, METH_VARARGS, nullptr},
{"ShowWebPage", app_dummy_none, METH_VARARGS, nullptr}, {"ShowWebPage", app_dummy_none, METH_VARARGS, nullptr},
@@ -193,16 +290,16 @@ void initapp() {
{"SetCameraSetting", app_dummy_none, METH_VARARGS, nullptr}, {"SetCameraSetting", app_dummy_none, METH_VARARGS, nullptr},
{"SetSightRange", app_dummy_none, METH_VARARGS, nullptr}, {"SetSightRange", app_dummy_none, METH_VARARGS, nullptr},
{"IsFileExist", app_dummy_zero, METH_VARARGS, nullptr}, {"IsFileExist", app_dummy_zero, METH_VARARGS, nullptr},
{"OpenTextFile", app_dummy_none, METH_VARARGS, nullptr}, {"OpenTextFile", app_open_text_file, METH_VARARGS, nullptr},
{"CloseTextFile", app_dummy_none, METH_VARARGS, nullptr}, {"CloseTextFile", app_close_text_file, METH_VARARGS, nullptr},
{"GetTextFileLineCount", app_dummy_str, METH_VARARGS, nullptr}, {"GetTextFileLineCount", app_get_text_file_line_count, METH_VARARGS, nullptr},
{"GetTextFileLine", app_dummy_str, METH_VARARGS, nullptr}, {"GetTextFileLine", app_get_text_file_line, METH_VARARGS, nullptr},
{"GetLocaleServiceName", app_get_locale_service_name, METH_VARARGS, nullptr}, {"GetLocaleServiceName", app_get_locale_service_name, METH_VARARGS, nullptr},
{"GetLocaleName", app_get_locale_name, METH_VARARGS, nullptr}, {"GetLocaleName", app_get_locale_name, METH_VARARGS, nullptr},
{"GetLocalePath", app_get_locale_path, METH_VARARGS, nullptr}, {"GetLocalePath", app_get_locale_path, METH_VARARGS, nullptr},
{"ForceSetLocale", app_dummy_none, METH_VARARGS, nullptr}, {"ForceSetLocale", app_dummy_none, METH_VARARGS, nullptr},
{"LoadLocaleAddr", 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}, {"SetCHEONMA", app_dummy_none, METH_VARARGS, nullptr},
{"IsCHEONMA", app_dummy_zero, METH_VARARGS, nullptr}, {"IsCHEONMA", app_dummy_zero, METH_VARARGS, nullptr},
{"GetDefaultCodePage", app_get_default_codepage, METH_VARARGS, nullptr}, {"GetDefaultCodePage", app_get_default_codepage, METH_VARARGS, nullptr},
@@ -295,4 +392,68 @@ void initapp() {
PyModule_AddIntConstant(module, "INFO_TEXTTAIL", 3); 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 } // namespace ava2
+9
View File
@@ -1,5 +1,6 @@
#pragma once #pragma once
#include <cstdint> #include <cstdint>
#include <string>
namespace ava2 { namespace ava2 {
int GetTwoHandedAttackSpeedDecrease(); int GetTwoHandedAttackSpeedDecrease();
@@ -8,5 +9,13 @@ bool IsYmirLocale();
std::int32_t GetServerTimeStamp(); std::int32_t GetServerTimeStamp();
void SetServerTime(std::int32_t time); void SetServerTime(std::int32_t time);
void ResetPythonAppState(); void ResetPythonAppState();
std::uint32_t GetLocalMSec();
std::int32_t GetApplicationSeconds();
void SetServerMSec(std::uint32_t time);
std::uint32_t GetServerMSec();
std::uint8_t GetEnterGameLanguage(); 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);
} }
+51
View File
@@ -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);
}
}
+1680
View File
File diff suppressed because it is too large Load Diff
+307
View File
@@ -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 <Python.h>
#include <deque>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
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<SChatLine> ms_kPool;
} TChatLine;
typedef std::deque<TChatLine*> TChatLineDeque;
typedef std::list<TChatLine*> 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<CWhisper> 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<SChatLine> ms_kPool;
} TChatLine;
typedef struct SWaitChat
{
int iType;
std::string strChat;
DWORD dwAppendingTime;
} TWaitChat;
typedef std::deque<TChatLine*> TChatLineDeque;
typedef std::list<TChatLine*> TChatLineList;
typedef std::map<std::string, CWhisper*> TWhisperMap;
typedef std::set<std::string> TIgnoreCharacterSet;
typedef std::list<TWaitChat> TWaitChatList;
typedef struct SChatSet
{
int m_ix;
int m_iy;
int m_iHeight;
int m_iStep;
float m_fEndPos;
int m_iBoardState;
std::vector<int> m_iMode;
TChatLineList m_ShowingChatLineList;
std::vector<int> 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<int, TChatSet> 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<BYTE, TChatLineDeque> m_ChatLineNewDeque;
D3DXCOLOR m_akD3DXClrChat[CHAT_TYPE_MAX_NUM];
DWORD m_dwFixedMillisecond = 0;
};
void initChat();
} // namespace ava2
+1483
View File
File diff suppressed because it is too large Load Diff
+44
View File
@@ -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 <bit>
#include <cstring>
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<int32_t>(r.vnum_reward),r.count_reward,int(r.item_reward_stackable!=0),
std::bit_cast<int32_t>(r.vnum_material_1),r.count_material_1,std::bit_cast<int32_t>(r.vnum_material_2),r.count_material_2,
std::bit_cast<int32_t>(r.vnum_material_3),r.count_material_3,std::bit_cast<int32_t>(r.vnum_material_4),r.count_material_4,
std::bit_cast<int32_t>(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);
}
}
+37
View File
@@ -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 <cstring>
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);
}
}
+51
View File
@@ -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 <cstring>
namespace ava2 {
DungeonInfoState& GetDungeonInfoState() {static DungeonInfoState state;return state;}
namespace {
template<size_t N> 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<uint8_t Sub> 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<DUNGEON_INFO_SUB_HEADER_TELEPORT>,METH_VARARGS,nullptr},
{"Ranking",request<DUNGEON_INFO_SUB_HEADER_RANKING>,METH_VARARGS,nullptr},{"Mision",request<DUNGEON_INFO_SUB_HEADER_MISION>,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);
}
}
File diff suppressed because it is too large Load Diff
+220
View File
@@ -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 <Python.h>
#include <list>
#include <map>
#include <string>
#include <vector>
namespace ava2 {
class CPythonEventManager
{
public:
typedef UI::CGraphicTextInstance CGraphicTextInstance;
struct TTextLine
{
int ixLocal, iyLocal;
CGraphicTextInstance* pInstance;
};
typedef std::list<TTextLine> 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<std::string, int> EventTypeMap;
std::vector<TEventSet*> m_EventSetVector;
CDynamicPool<TEventSet> m_EventSetPool;
CDynamicPool<CGraphicTextInstance> m_ScriptTextLinePool;
CBorrowedObject m_poInterface;
std::string m_strLeftTimeString;
long m_lElapsedMillisecond = 0;
};
} // namespace ava2
File diff suppressed because it is too large Load Diff
+31 -1
View File
@@ -3,13 +3,13 @@
#include "eter_net/Packet.h" #include "eter_net/Packet.h"
#include <vector> #include <vector>
#include <functional> #include <functional>
#include <string>
namespace ava2 { namespace ava2 {
void initItem(); void initItem();
void initPlayer(); void initPlayer();
void initchrmgr(); void initchrmgr();
void initchr(); void initchr();
void initChat();
void initsnd(); void initsnd();
void initBackground(); void initBackground();
void GlobalToLocalPosition(int32_t& x,int32_t& y); void GlobalToLocalPosition(int32_t& x,int32_t& y);
@@ -31,6 +31,30 @@ struct PlayerItemSlot {
PlayerItemSlot GetPlayerItem(int slot); PlayerItemSlot GetPlayerItem(int slot);
void SetPlayerItem(int slot, uint32_t vnum, int count); void SetPlayerItem(int slot, uint32_t vnum, int count);
void ResetPlayerState(); 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 ClearPlayerPythonWindow();
void SetPlayerSkill(int slot,int index); void SetPlayerSkill(int slot,int index);
void SetPlayerSkillLevel(int index,int grade,int level); 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 AddPlayerQuickSlot(int index,uint8_t type,uint8_t pos);
void DeletePlayerQuickSlot(int index); void DeletePlayerQuickSlot(int index);
void SwapPlayerQuickSlots(int source,int target); 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); void SetPlayerItemData(uint8_t window, uint16_t cell, const TItemData& data);
TItemData GetPlayerItemData(uint8_t window, uint16_t cell); TItemData GetPlayerItemData(uint8_t window, uint16_t cell);
bool UsePlayerItem(int window, int slot, std::string& outEquippedWeaponModel, std::string& outActionMessage); bool UsePlayerItem(int window, int slot, std::string& outEquippedWeaponModel, std::string& outActionMessage);
@@ -47,6 +72,7 @@ std::string GetWeaponModelPathByVnum(uint32_t vnum);
std::vector<Render3DDraw> GetAllActiveChrDraws(); std::vector<Render3DDraw> GetAllActiveChrDraws();
void SetMainCharacterPosition(float x, float y, float z); void SetMainCharacterPosition(float x, float y, float z);
const std::string& GetMainCharacterName();
void SetMainCharacterName(const std::string& name); void SetMainCharacterName(const std::string& name);
long long GetPlayerStatusPoint(int type); long long GetPlayerStatusPoint(int type);
void SetPlayerStatusPoint(int type, long long value); void SetPlayerStatusPoint(int type, long long value);
@@ -55,5 +81,9 @@ class TerrainHeightmap;
TerrainHeightmap* GetActiveBackgroundTerrain(); TerrainHeightmap* GetActiveBackgroundTerrain();
void SetActiveBackgroundTerrain(std::unique_ptr<TerrainHeightmap> terrain); void SetActiveBackgroundTerrain(std::unique_ptr<TerrainHeightmap> terrain);
bool LoadBackgroundMap(const std::string& mapName, float x = 0.0f, float y = 0.0f, float z = 0.0f); 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 } // namespace ava2
+109
View File
@@ -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 <algorithm>
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.grade<b.grade;});
}
void GuildState::RemoveMember(uint32_t pid) {
auto it=std::find_if(members.begin(),members.end(),[pid](const Member& m){return m.pid==pid;});
if(it!=members.end())members.erase(it);
}
void GuildState::StartWar(uint32_t enemy) {
if(std::find(enemies.begin(),enemies.end(),enemy)!=enemies.end())return;
auto it=std::find(enemies.begin(),enemies.end(),0);if(it!=enemies.end())*it=enemy;
}
void GuildState::EndWar(uint32_t enemy) { for(auto& id:enemies)if(id==enemy)id=0; }
void GuildState::Destroy() { info={};skill={};enemies={};grades.clear();members.clear();names.clear();levelSum=levelAverage=0;enabled=false; }
namespace {
GuildState& g() {return GetGuildState();}
PyObject* number(uint32_t value) {return PyInt_FromLong(int32_t(value));}
bool index(PyObject* args,int& value) {return PyTuple_GetInteger(args,0,&value);}
#define GETTER(name,expression) PyObject* name(PyObject*,PyObject*) {return number(expression);}
GETTER(enabled,g().enabled) GETTER(id,g().info.id) GETTER(land,g().info.hasLand)
GETTER(money,g().info.money) GETTER(level,g().info.level) GETTER(count,g().members.size())
GETTER(comment_count,g().comments.size()) GETTER(level_sum,g().levelSum)
GETTER(level_average,g().levelAverage) GETTER(offer_sum,g().offerSum) GETTER(skill_points,g().skill.points)
#undef GETTER
PyObject* guild_name(PyObject*,PyObject* args) {
int id;if(!index(args,id))return PyString_FromString(g().info.name.c_str());
auto it=g().names.find(uint32_t(id));return PyString_FromString(it==g().names.end()?"Noname":it->second.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)<g().enemies.size()?g().enemies[slot]:0);
return PyString_FromString(it==g().names.end()?"":it->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)<g().members.size()?g().members[i].pid:uint32_t(-1));}
PyObject* is_member(PyObject*,PyObject* args) {int i;if(!index(args,i))return Py_BuildException();return number(uint32_t(i)<g().members.size());}
PyObject* is_name(PyObject*,PyObject* args) {char* name;if(!PyTuple_GetString(args,0,&name))return Py_BuildException();return number(g().ByName(name)!=nullptr);}
PyObject* grade(PyObject*,PyObject* args) {int i;if(!index(args,i))return Py_BuildException();auto it=g().grades.find(uint32_t(i));return it==g().grades.end()?Py_BuildValue("si","?",0):Py_BuildValue("si",it->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);
}
}
+68
View File
@@ -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);
}
}
File diff suppressed because it is too large Load Diff
+269
View File
@@ -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 <Python.h>
#include "eter_image/GrpImageInstance.h"
#include <cstdint>
#include <map>
#include <string>
#include <vector>
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<TMarkPosition> 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<uint32_t, SObserver> 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<TAtlasMarkInfo> TAtlasMarkInfoVector;
typedef std::vector<TGuildAreaInfo> 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<TSignalPoint> m_SignalPointVector;
PyObject* m_poHandler;
uint32_t (*m_now)() = nullptr;
};
void initMiniMap();
} // namespace ava2
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -17,6 +17,7 @@ std::array<float,3> GetGameEventCenter();
void initshop(); void initshop();
void ResetShopState(); void ResetShopState();
void ClearShopState(); void ClearShopState();
bool IsShopOpen();
struct ShopItemRecord { struct ShopItemRecord {
uint32_t vnum=0,count=0,buyVnum=0,buyCount=0; uint32_t vnum=0,count=0,buyVnum=0,buyCount=0;
int64_t price=0; int64_t price=0;
@@ -31,6 +32,10 @@ void SetShopTab(unsigned index,const std::string& name,unsigned coin);
void initskill(); void initskill();
float EvaluateSkillFormula(const std::string& formula, float level); float EvaluateSkillFormula(const std::string& formula, float level);
void ResetSkillDescriptions(); 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 LoadSkillDescriptions(const std::string& path);
bool LoadSkillTable(const std::string& path, bool cheonma=false); bool LoadSkillTable(const std::string& path, bool cheonma=false);
void initskillpet(); void initskillpet();
@@ -40,7 +45,7 @@ void initSash();
void initServerStateChecker(); void initServerStateChecker();
void initPlayerSettingsModule(); void initPlayerSettingsModule();
void initSwitchbot(); void initSwitchbot();
void initWiki(); void initWiki(); // src/python_wiki.cpp
void initCombatZoneSystem(); void initCombatZoneSystem();
void initBankManager(); void initBankManager();
void intdropitem(); void intdropitem();
+449 -72
View File
@@ -1,13 +1,19 @@
#include "python_net.h" #include "python_net.h"
#include "guild_state.h"
#include "python_gameplay_modules.h"
#include "login_client.h" #include "login_client.h"
#include "protocol.h" #include "protocol.h"
#include "eter_net/PythonNetworkStream.h" #include "eter_net/PythonNetworkStream.h"
#include "eter_net/NetworkActorManager.h" #include "eter_net/NetworkActorManager.h"
#include "shared/common/PythonUtils.h"
#include "python_runtime.h"
#include <Python.h> #include <Python.h>
#include <array> #include <array>
#include <iostream>
#include <chrono> #include <chrono>
#include <stdexcept> #include <stdexcept>
#include <algorithm> #include <algorithm>
#include <cstring>
namespace ava2 { namespace ava2 {
namespace { namespace {
@@ -31,19 +37,10 @@ void replace(PyObject*& old,PyObject* next) {
Py_XDECREF(previous); 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) { void callback(PyObject* target,const char* name,const char* text=nullptr) {
if(!target) return; PyCallClassMemberFunc(target,name,text?Py_BuildValue("(s)",text):Py_BuildValue("()"));
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<char*>("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);
} }
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; } 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_str(PyObject*, PyObject*) { return PyString_FromString(""); }
PyObject* net_dummy_tuple4(PyObject*, PyObject*) { return Py_BuildValue("iiii", 0, 0, 0, 0); } 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<uint8_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(state), static_cast<uint8_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(source), static_cast<uint8_t>(target), static_cast<uint32_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(grade), static_cast<uint8_t>(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<uint8_t>(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<uint8_t>(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<uint8_t>(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*) { PyObject* net_get_main_actor_vid(PyObject*, PyObject*) {
uint32_t vid = PythonNetworkStream::Instance().GetMainActorVID(); uint32_t vid = PythonNetworkStream::Instance().GetMainActorVID();
if (vid == 0 && has_mock_characters) vid = 1001; if (vid == 0 && has_mock_characters) vid = 1001;
@@ -377,6 +720,13 @@ PyObject* send_item_move_packet(PyObject*, PyObject* args) {
} // namespace } // 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() { const CharacterMoveState& get_last_character_move() {
return last_move_state; return last_move_state;
} }
@@ -393,6 +743,33 @@ void SetItemMovePacketCallback(ItemMovePacketCallback cb) {
s_itemMoveCallback = cb; s_itemMoveCallback = cb;
} }
// AVA2 PythonNetworkStreamModule.cpp: server-command / chat-filter / emoticon wrappers.
std::vector<std::string> 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) { static PyObject* net_send_refine_packet(PyObject*, PyObject* args) {
int targetPos = 0, type = 0, specialStorage = 0, indexSelect = -1; int targetPos = 0, type = 0, specialStorage = 0, indexSelect = -1;
if (PyArg_ParseTuple(args, "iiii", &targetPos, &type, &specialStorage, &indexSelect)) { if (PyArg_ParseTuple(args, "iiii", &targetPos, &type, &specialStorage, &indexSelect)) {
@@ -460,30 +837,30 @@ void initnet() {
{"Update", update, METH_NOARGS, nullptr}, {"Update", update, METH_NOARGS, nullptr},
{"GetConnectionState", status, METH_NOARGS, nullptr}, {"GetConnectionState", status, METH_NOARGS, nullptr},
{"GetBettingGuildWarValue", net_dummy_zero, METH_VARARGS, 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}, {"SetServerInfo", net_dummy_none, METH_VARARGS, nullptr},
{"GetServerInfo", net_dummy_str, METH_VARARGS, nullptr}, {"GetServerInfo", net_dummy_str, METH_VARARGS, nullptr},
{"PreserveServerCommand", net_dummy_none, METH_VARARGS, nullptr}, {"PreserveServerCommand", net_preserve_server_command, METH_VARARGS, nullptr},
{"GetPreservedServerCommand", net_dummy_str, METH_VARARGS, nullptr}, {"GetPreservedServerCommand", net_get_preserved_server_command, METH_VARARGS, nullptr},
{"StartGame", net_start_game, METH_VARARGS, nullptr}, {"StartGame", net_start_game, METH_VARARGS, nullptr},
{"Warp", net_warp, METH_VARARGS, nullptr}, {"Warp", net_warp, METH_VARARGS, nullptr},
{"IsTest", net_dummy_zero, METH_VARARGS, nullptr}, {"IsTest", net_dummy_zero, METH_VARARGS, nullptr},
{"SetMarkServer", net_dummy_none, METH_VARARGS, nullptr}, {"SetMarkServer", net_dummy_none, METH_VARARGS, nullptr},
{"IsChatInsultIn", net_dummy_zero, METH_VARARGS, nullptr}, {"IsChatInsultIn", net_is_chat_insult_in, METH_VARARGS, nullptr},
{"IsInsultIn", net_dummy_zero, METH_VARARGS, nullptr}, {"IsInsultIn", net_is_insult_in, METH_VARARGS, nullptr},
{"LoadInsultList", net_dummy_none, METH_VARARGS, nullptr}, {"LoadInsultList", net_load_insult_list, METH_VARARGS, nullptr},
{"UploadMark", net_dummy_none, METH_VARARGS, nullptr}, {"UploadMark", net_dummy_none, METH_VARARGS, nullptr},
{"UploadSymbol", 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}, {"GetMainActorVID", net_get_main_actor_vid, METH_VARARGS, nullptr},
{"GetMainActorRace", net_get_main_actor_race, METH_VARARGS, nullptr}, {"GetMainActorRace", net_get_main_actor_race, METH_VARARGS, nullptr},
{"GetMainActorEmpire", net_get_main_actor_empire, METH_VARARGS, nullptr}, {"GetMainActorEmpire", net_get_main_actor_empire, METH_VARARGS, nullptr},
{"GetMainActorSkillGroup", net_get_main_actor_skill_group, 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}, {"GetFieldMusicFileName", net_get_field_music_name, METH_VARARGS, nullptr},
{"GetFieldMusicVolume", net_get_field_music_volume, METH_VARARGS, nullptr}, {"GetFieldMusicVolume", net_get_field_music_volume, METH_VARARGS, nullptr},
{"ToggleGameDebugInfo", net_dummy_none, 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}, {"SetTCPRecvBufferSize", net_dummy_none, METH_VARARGS, nullptr},
{"SetTCPSendBufferSize", net_dummy_none, METH_VARARGS, nullptr}, {"SetTCPSendBufferSize", net_dummy_none, METH_VARARGS, nullptr},
{"SetUDPRecvBufferSize", 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}, {"SetOfflinePhase", net_dummy_none, METH_VARARGS, nullptr},
{"IsConnect", is_connected, METH_VARARGS, nullptr}, {"IsConnect", is_connected, METH_VARARGS, nullptr},
{"SendChatPacket", net_send_chat, 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}, {"SendWhisperPacket", net_send_whisper, METH_VARARGS, nullptr},
{"SendMobileMessagePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendMobileMessagePacket", net_dummy_none, METH_VARARGS, nullptr},
{"SendCharacterPositionPacket", send_character_position_packet, METH_VARARGS, nullptr}, {"SendCharacterPositionPacket", send_character_position_packet, METH_VARARGS, nullptr},
@@ -524,57 +901,57 @@ void initnet() {
{"SendShopBuyPacket", shop_buy, METH_VARARGS, nullptr}, {"SendShopBuyPacket", shop_buy, METH_VARARGS, nullptr},
{"SendShopSellPacket", shop_sell, METH_VARARGS, nullptr}, {"SendShopSellPacket", shop_sell, METH_VARARGS, nullptr},
{"SendShopSellPacketNew", shop_sell_new, METH_VARARGS, nullptr}, {"SendShopSellPacketNew", shop_sell_new, METH_VARARGS, nullptr},
{"SendExchangeStartPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendExchangeStartPacket", netSendExchangeStartPacket, METH_VARARGS, nullptr},
{"SendExchangeItemAddPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendExchangeItemAddPacket", netSendExchangeItemAddPacket, METH_VARARGS, nullptr},
{"SendExchangeItemDelPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendExchangeItemDelPacket", netSendExchangeItemDelPacket, METH_VARARGS, nullptr},
{"SendExchangeElkAddPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendExchangeElkAddPacket", netSendExchangeElkAddPacket, METH_VARARGS, nullptr},
{"SendExchangeAcceptPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendExchangeAcceptPacket", netSendExchangeAcceptPacket, METH_VARARGS, nullptr},
{"SendExchangeExitPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendExchangeExitPacket", netSendExchangeExitPacket, METH_VARARGS, nullptr},
{"SendOnClickPacket", net_send_onclick, METH_VARARGS, nullptr}, {"SendOnClickPacket", net_send_onclick, METH_VARARGS, nullptr},
{"RegisterEmoticonString", net_dummy_none, METH_VARARGS, nullptr}, {"RegisterEmoticonString", net_register_emoticon_string, METH_VARARGS, nullptr},
{"SendMessengerAddByVIDPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendMessengerAddByVIDPacket", netSendMessengerAddByVIDPacket, METH_VARARGS, nullptr},
{"SendMessengerAddByNamePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendMessengerAddByNamePacket", netSendMessengerAddByNamePacket, METH_VARARGS, nullptr},
{"SendMessengerRemovePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendMessengerRemovePacket", netSendMessengerRemovePacket, METH_VARARGS, nullptr},
{"SendPartyInvitePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartyInvitePacket", netSendPartyInvitePacket, METH_VARARGS, nullptr},
{"SendPartyInviteAnswerPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartyInviteAnswerPacket", netSendPartyInviteAnswerPacket, METH_VARARGS, nullptr},
{"SendPartyExitPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartyExitPacket", netSendPartyExitPacket, METH_VARARGS, nullptr},
{"SendPartyRemovePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartyRemovePacket", netSendPartyRemovePacketPID, METH_VARARGS, nullptr},
{"SendPartyRemovePacketPID", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartyRemovePacketPID", netSendPartyRemovePacketPID, METH_VARARGS, nullptr},
{"SendPartyRemovePacketVID", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartyRemovePacketVID", netSendPartyRemovePacketVID, METH_VARARGS, nullptr},
{"SendPartySetStatePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartySetStatePacket", netSendPartySetStatePacket, METH_VARARGS, nullptr},
{"SendPartyUseSkillPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartyUseSkillPacket", netSendPartyUseSkillPacket, METH_VARARGS, nullptr},
{"SendPartyParameterPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendPartyParameterPacket", netSendPartyParameterPacket, METH_VARARGS, nullptr},
{"SendSafeboxSaveMoneyPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendSafeboxSaveMoneyPacket", netSendSafeboxSaveMoneyPacket, METH_VARARGS, nullptr},
{"SendSafeboxWithdrawMoneyPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendSafeboxWithdrawMoneyPacket", netSendSafeboxWithdrawMoneyPacket, METH_VARARGS, nullptr},
{"SendSafeboxCheckinPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendSafeboxCheckinPacket", netSendSafeboxCheckinPacket, METH_VARARGS, nullptr},
{"SendSafeboxCheckoutPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendSafeboxCheckoutPacket", netSendSafeboxCheckoutPacket, METH_VARARGS, nullptr},
{"SendSafeboxItemMovePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendSafeboxItemMovePacket", netSendSafeboxItemMovePacket, METH_VARARGS, nullptr},
{"SendMallCheckoutPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendMallCheckoutPacket", netSendMallCheckoutPacket, METH_VARARGS, nullptr},
{"SendAnswerMakeGuildPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendAnswerMakeGuildPacket", netSendAnswerMakeGuildPacket, METH_VARARGS, nullptr},
{"SendQuestInputStringPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendQuestInputStringPacket", netSendQuestInputStringPacket, METH_VARARGS, nullptr},
{"SendQuestInputLongStringPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendQuestInputLongStringPacket", netSendQuestInputLongStringPacket, METH_VARARGS, nullptr},
{"SendQuestConfirmPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendQuestConfirmPacket", netSendQuestConfirmPacket, METH_VARARGS, nullptr},
{"SendGuildAddMemberPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildAddMemberPacket", netSendGuildAddMemberPacket, METH_VARARGS, nullptr},
{"SendGuildRemoveMemberPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildRemoveMemberPacket", netSendGuildRemoveMemberPacket, METH_VARARGS, nullptr},
{"SendGuildChangeGradeNamePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildChangeGradeNamePacket", netSendGuildChangeGradeNamePacket, METH_VARARGS, nullptr},
{"SendGuildChangeGradeAuthorityPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildChangeGradeAuthorityPacket", netSendGuildChangeGradeAuthorityPacket, METH_VARARGS, nullptr},
{"SendGuildOfferPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildOfferPacket", netSendGuildOfferPacket, METH_VARARGS, nullptr},
{"SendGuildPostCommentPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildPostCommentPacket", netSnedGuildPostCommentPacket, METH_VARARGS, nullptr},
{"SendGuildDeleteCommentPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildDeleteCommentPacket", netSnedGuildDeleteCommentPacket, METH_VARARGS, nullptr},
{"SendGuildRefreshCommentsPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildRefreshCommentsPacket", netSendGuildRefreshCommentsPacket, METH_VARARGS, nullptr},
{"SendGuildChangeMemberGradePacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildChangeMemberGradePacket", netSendGuildChangeMemberGradePacket, METH_VARARGS, nullptr},
{"SendGuildUseSkillPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildUseSkillPacket", netSendGuildUseSkillPacket, METH_VARARGS, nullptr},
{"SendGuildChangeMemberGeneralPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildChangeMemberGeneralPacket", netSendGuildChangeMemberGeneralPacket, METH_VARARGS, nullptr},
{"SendGuildInviteAnswerPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildInviteAnswerPacket", netSendGuildInviteAnswerPacket, METH_VARARGS, nullptr},
{"SendGuildChargeGSPPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildChargeGSPPacket", netSendGuildChargeGSPPacket, METH_VARARGS, nullptr},
{"SendGuildDepositMoneyPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildDepositMoneyPacket", netSendGuildDepositMoneyPacket, METH_VARARGS, nullptr},
{"SendGuildWithdrawMoneyPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildWithdrawMoneyPacket", netSendGuildWithdrawMoneyPacket, METH_VARARGS, nullptr},
{"SendRequestRefineInfoPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendRequestRefineInfoPacket", netSendRequestRefineInfoPacket, METH_VARARGS, nullptr},
{"SendRefinePacket", net_send_refine_packet, METH_VARARGS, nullptr}, {"SendRefinePacket", net_send_refine_packet, METH_VARARGS, nullptr},
{"SendScriptAnswerPacket", net_send_script_answer_packet, METH_VARARGS, nullptr}, {"SendScriptAnswerPacket", net_send_script_answer_packet, METH_VARARGS, nullptr},
{"SendScriptButtonPacket", net_send_script_button_packet, METH_VARARGS, nullptr}, {"SendScriptButtonPacket", net_send_script_button_packet, METH_VARARGS, nullptr},
{"SendSelectItemPacket", net_dummy_none, METH_VARARGS, nullptr}, {"SendSelectItemPacket", netSendSelectItemPacket, METH_VARARGS, nullptr},
{"SetEmpireLanguageMode", net_dummy_none, METH_VARARGS, nullptr}, {"SetEmpireLanguageMode", net_set_empire_language_mode, METH_VARARGS, nullptr},
{"SetSkillGroupFake", net_dummy_none, METH_VARARGS, nullptr}, {"SetSkillGroupFake", net_dummy_none, METH_VARARGS, nullptr},
{"SendGuildSymbol", net_dummy_none, METH_VARARGS, nullptr}, {"SendGuildSymbol", net_dummy_none, METH_VARARGS, nullptr},
{"DisconnectUploader", 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}, {"CalendarOpen", net_dummy_none, METH_VARARGS, nullptr},
{"CalendarClose", net_dummy_none, METH_VARARGS, nullptr}, {"CalendarClose", net_dummy_none, METH_VARARGS, nullptr},
{"CalendarSend", 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}, {"SendMiniGameCatchKingStart", net_dummy_none, METH_VARARGS, nullptr},
{"SendMiniGameCatchKingDeckCardClick", net_dummy_none, METH_VARARGS, nullptr}, {"SendMiniGameCatchKingDeckCardClick", net_dummy_none, METH_VARARGS, nullptr},
{"SendMiniGameCatchKingFieldCardClick", 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(); auto& stream=PythonNetworkStream::Instance();
stream.PushRecvData(client.take_game_input()); stream.PushRecvData(client.take_game_input(stream.RecvBufferSpace()));
stream.ProcessRecvData(); stream.ProcessRecvData();
if(client.status()==LoginClient::Status::Loading) { 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);
} }
} }
+2
View File
@@ -5,7 +5,9 @@ void register_python_net();
void reset_python_net(); void reset_python_net();
void pump_python_net(); void pump_python_net();
void set_mock_character(int slot, const Character& chr); 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); void set_mock_empire(std::uint8_t empire);
bool LoadInsultList(const std::string& path); // CPythonNetworkStream::LoadInsultList
struct CharacterMoveState { struct CharacterMoveState {
std::uint8_t func = 0; std::uint8_t func = 0;
+92
View File
@@ -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 <algorithm>
#include <bit>
#include <cstring>
namespace ava2 {
OfflineShopState& GetOfflineShopState() {static OfflineShopState state;return state;}
void ClearOfflineShopState() {GetOfflineShopState()={};}
namespace {
template<int field> 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<int32_t>(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<int32_t>(item->owner_id));
}
template<bool attribute> 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<int field> 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<int32_t>(s.displayed));
if constexpr(field==4)return PyInt_FromLong(std::bit_cast<int32_t>(s.watchers));
if constexpr(field==5)return PyLong_FromLongLong(s.money);
if constexpr(field==6)return PyLong_FromLongLong(std::bit_cast<int64_t>(s.flag));
if constexpr(field==7)return PyInt_FromLong(std::bit_cast<int32_t>(s.type));
if constexpr(field==8)return PyInt_FromLong(s.time);
}
template<int field> 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<TOfflineShopItemTable> 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<b.display_pos;});
PythonNetworkStream::Instance().SendBuildOfflineShopPacket(name,items,uint32_t(vnum),uint8_t(title));Py_RETURN_NONE;
}
PyObject* decoration(PyObject*,PyObject* args) {
char* sign;int vnum,type;if(!PyTuple_GetString(args,0,&sign)||!PyTuple_GetInteger(args,1,&vnum)||!PyTuple_GetInteger(args,2,&type))return Py_BuildException();
PythonNetworkStream::Instance().SendOfflineShopChangeDecoration(sign,uint32_t(vnum),uint32_t(type));Py_RETURN_NONE;
}
}
void InitOfflineShopMethods() {
static PyMethodDef methods[]={
{"IsOfflineShop",stateField<0>,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<true>,METH_VARARGS,nullptr},
{"GetOfflineShopItemMetinSocket",detail<false>,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);
}
}
+62
View File
@@ -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 <bit>
#include <cstdlib>
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<CGraphicImage*>(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<int32_t>(it->second.imageHandle));
}
PyObject* emptySkill(PyObject*,PyObject*) {return PyInt_FromLong(std::bit_cast<int32_t>(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+1<lines.size();++line) {
auto fields=ava2TabTokens(lines[line],false);if(fields.size()<6)return false;
const uint32_t index=uint32_t(std::strtol(fields[0].c_str(),nullptr,10));if(!index)continue;
auto& record=records[index];record.index=index;record.name=fields[1];
record.icon="d:/ymir work/ui/skill/pet/"+fields[2]+".sub";
// Windows _snprintf(char[65],65,...) can omit its terminator; retain bounded bytes safely.
if(record.icon.size()>65)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);
}
}
+65
View File
@@ -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 <bit>
#include <iostream>
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<int32_t>(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<CGraphicImage*>(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 "<<id<<" already exists\n";
GetQuestState().apply(type,q,uint8_t(flags),GetQuestTime(),true);
Py_RETURN_NONE;
}
}
void initquest() {
static PyMethodDef methods[]={
{"GetQuestCount",count,METH_VARARGS,nullptr},{"GetQuestData",data,METH_VARARGS,nullptr},
{"GetQuestIndex",index,METH_VARARGS,nullptr},{"GetQuestLastTime",last_time,METH_VARARGS,nullptr},
{"Clear",clear,METH_VARARGS,nullptr},{"Add",add,METH_VARARGS,nullptr},{nullptr,nullptr,0,nullptr}};
auto* module=Py_InitModule("quest",methods);PyModule_AddIntConstant(module,"QUEST_MAX_NUM",5);
}
}
+41
View File
@@ -1,8 +1,18 @@
#include "pet_skill_state.h"
#include "eter_ui/PythonWindowManager.h" #include "eter_ui/PythonWindowManager.h"
#include "src/eter_image/GrpImageInstance.h" #include "src/eter_image/GrpImageInstance.h"
#include "src/eter_image/GrpExpandedImageInstance.h" #include "src/eter_image/GrpExpandedImageInstance.h"
#include "src/eter_image/GrpMarkInstance.h" #include "src/eter_image/GrpMarkInstance.h"
#include "python_runtime.h" #include "python_runtime.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 "python_net.h" #include "python_net.h"
#include "python_app.h" #include "python_app.h"
#include "python_dbg.h" #include "python_dbg.h"
@@ -12,6 +22,8 @@
#include "python_ime.h" #include "python_ime.h"
#include "python_grp.h" #include "python_grp.h"
#include "python_native_modules.h" #include "python_native_modules.h"
#include "python_event_manager.h"
#include "python_chat.h"
#include "../upstream/ava2-client/UserInterface/Locale_inc.h" #include "../upstream/ava2-client/UserInterface/Locale_inc.h"
#include <Python.h> #include <Python.h>
#include <algorithm> #include <algorithm>
@@ -72,8 +84,18 @@ std::string ReadPackedText(const std::string& name) {
PythonRuntime::PythonRuntime(const std::filesystem::path& stdlib,const std::filesystem::path& root) { PythonRuntime::PythonRuntime(const std::filesystem::path& stdlib,const std::filesystem::path& root) {
if(Py_IsInitialized()) throw std::logic_error("one embedded Python runtime allowed"); if(Py_IsInitialized()) throw std::logic_error("one embedded Python runtime allowed");
ResetPythonAppState(); ResetPythonAppState();
GetPetSkillState()=PetSkillState{};
ResetSkillDescriptions(); ResetSkillDescriptions();
ResetShopState(); 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"); if(!std::filesystem::is_regular_file(stdlib)) throw std::runtime_error("python27.zip missing");
pack_root=std::filesystem::canonical(root); pack_root=std::filesystem::canonical(root);
static bool registered=false; static bool registered=false;
@@ -132,6 +154,7 @@ PythonRuntime::PythonRuntime(const std::filesystem::path& stdlib,const std::file
registered=true; registered=true;
} }
Py_FrozenFlag=1;Py_IgnoreEnvironmentFlag=1;Py_NoSiteFlag=1;Py_DontWriteBytecodeFlag=1; Py_FrozenFlag=1;Py_IgnoreEnvironmentFlag=1;Py_NoSiteFlag=1;Py_DontWriteBytecodeFlag=1;
CResourceManager::SetResourceRoot(std::filesystem::absolute(root));
m_resourceManager = std::make_unique<CResourceManager>(); m_resourceManager = std::make_unique<CResourceManager>();
Py_Initialize(); Py_Initialize();
m_windowManager = std::make_unique<UI::CWindowManager>(); m_windowManager = std::make_unique<UI::CWindowManager>();
@@ -214,6 +237,15 @@ sys.meta_path.insert(0, _AVA2PackImporter())
)PY"); } catch(...) { )PY"); } catch(...) {
reset_python_net(); reset_python_net();
ClearPlayerPythonWindow(); 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(); Py_Finalize();
if (m_windowManager) if (m_windowManager)
{ {
@@ -236,6 +268,15 @@ sys.meta_path.insert(0, _AVA2PackImporter())
PythonRuntime::~PythonRuntime() { PythonRuntime::~PythonRuntime() {
reset_python_net(); reset_python_net();
ClearPlayerPythonWindow(); 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(); Py_Finalize();
if (m_windowManager) if (m_windowManager)
{ {

Some files were not shown because too many files have changed in this diff Show More